python xlrd_python模块之xlrd
python處理excel的模塊,xlrd讀取excel,xlwt寫入excel
一、安裝
pip install xlrd
二、使用
1. 打開excel,得到Book對象
import xlrd
rb = xlrd.open_workbook(r'E:\python\test.xlsx', formatting_info=True)
# excel文件被打開為一個Book對象,即 rb(xlrd.book.Book類)
sheets = rb.sheet_names()
# 獲取Book對象的屬性:包含所有sheet表名的列表(xlrd.book.Book.sheet_names)
2. 指定sheet工作表(基于Book對象),得到Sheet對象
sheet1 = rb.sheet_by_index(0)
# 通過索引獲取第0個工作表,并打開為Sheet對象(xlrd.sheet.Sheet類)
sheet2 = rb.sheet_by_name('sheet2')
# 直接通過工作表名稱打開為Sheet對象,如果打開的是同一個表,則和上面的方法獲取到的對象完全等價==
3. Sheet對象的屬性
print(sheet1.name, sheet1.nrows, sheet1.ncols)
# sheet1的名稱、行數、列數
print(sheet1.row_values(0), sheet1.col_values(0), sheet1.cell_value(0, 0))
# sheet1的某一行/某一列所有值的列表,某行某列的值
4. Cell對象(基于Sheet對象)的屬性
cell_0_0 = sheet1.cell(0, 0)
# sheet1的某行某列的Cell對象(xlrd.sheet.Cell類)
row_0 = sheet1.row(0)
col_0 = sheet1.col(0)
# sheet1的某一行/某一列所有cell對象的列表
print(cell_0_0.value)
# cell_0_0對象的值
print(cell_0_0.ctype)
# cell_0_0對象的類型
# _0 empty, 1 string, 2 number, 3 date, 4 boolean, 5 error
5. 日期的處理
excel中的日期時間通過xlrd讀取到數據后,會轉換成一串數字
2018/07/10會轉換為43291.0
2018/7/10 18:15:02 會轉換成43291.76043981482
cell_0_0_tuple = xlrd.xldata_as_tuple(cell_0_0.value, datemode=0)
# 首先要判斷ctype屬于日期,然后才能轉換為tuple(年,月,日,時,分,秒)
# datemode在此處的含義是從1900年開始,如果等于1,則是從1904年開始(使用0即可)
from datetime import datetime, date
date(*cell_0_0_tuple[:3]).strftime('%Y/%m/%d')
# 使用date模塊,將tuple的年月日轉換為date對象(只支持三位參數),使用strftime方法格式化。
6. 合并單元格數據處理
merged = sheet1.merged_cells
返回結果是一個由tuple組成的list,每個tuple含四個元素,形成一個合并單元格的矩陣。
[(rl1, rh1, cl1, ch1), (rl2, rh2, cl1, ch2)] ; l為開始,h-1為結束
(4,5,1,3), 合并了第4行(實際第五行,不贅述)到第4行,第1列到第2列的數據。
總結
以上是生活随笔為你收集整理的python xlrd_python模块之xlrd的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python英语字典程序修改_详解如何修
- 下一篇: 怎么用python自制计算公式_自制计算