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列的數據。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM