xlrd、xlwt 庫


1. 安裝與介紹

2. xlrd

3. xlwt

 

1. 安裝與介紹

xlrd 模塊實現對 excel 文件內容讀取,xlwt 模塊實現對 excel 文件的寫入。

模塊安裝:

pip install xlrd  # 新版僅支持 .xls。若要支持 .xlsx 可安裝舊版 pip install xlrd==1.2.0
pip install xlwt

 

2. xlrd

示例:

 1 import xlrd
 2 
 3 # 獲取excel文件薄對象
 4 wb = xlrd.open_workbook("e:\\test.xlsx")
 5 
 6 # 獲取所有sheet名稱
 7 sheet_name = wb.sheet_names()
 8 print(sheet_name)
 9 
10 # 根據sheet索引獲取sheet對象(從0開始)
11 sheet = wb.sheet_by_index(0)
12 # 根據sheet名獲取sheet對象
13 sheet = wb.sheet_by_name("業務場景")
14 # 獲取sheet對象的名稱、行數和列數
15 print("sheet_name:{}, nrows:{}, ncols:{}".format(sheet.name, sheet.nrows, sheet.ncols))
16 
17 # 獲取整行和整列的值(返回列表)
18 print(sheet.row_values(0))  # 獲取第一行的數據
19 print(sheet.col_values(1))  # 獲取第二列的數據
20 
21 # 獲取指定單元格的值
22 print(sheet.cell(0, 1).value)  # 獲取第1行第2列的值
23 print(sheet.cell_value(0, 1))  # 獲取第1行第2列的值
24 print(sheet.row(0)[1].value)  # 獲取第1行第2列的值
25 
26 
27 # 獲取單元格值的數據類型
28 print(sheet.cell(0, 1).ctype)
29 # ctype 值說明: 0 empty, 1 string, 2 number, 3 date, 4 boolean, 5 error
30 
31 
32 # 獲取日期類型的單元格值
33 from datetime import date
34 if sheet.cell(2, 1).ctype == 3:
35     print(sheet.cell(2, 1).value)  # 44089.0
36     date_value = xlrd.xldate_as_tuple(sheet.cell(2, 1).value, wb.datemode)
37     print(date_value)  # (2020, 9, 15, 0, 0, 0)
38     print(date(*date_value[:3]))  # 2020-09-15
39     print(date(*date_value[:3]).strftime("%Y/%m/%d"))  # 2020/09/15
40 
41 
42 # 將number類型的單元格值轉為整型
43 if sheet.cell(0, 0).ctype == 2:
44     print(sheet.cell(0, 0).value)  # 123.0
45     print(int(sheet.cell(0, 0).value))
46 
47 
48 # 獲取合並單元格的值(需要merged_cells屬性)
49 
50 # 需要在讀取excel文件的時候添加參數formatting_info,並設置為True(默認是False)
51 # 否則可能調用merged_cells屬性獲取到的是空值
52 wb2 = xlrd.open_workbook("e:\\test.xls", formatting_info=True)
53 # 注意:在讀取xlsx格式的Excel時,傳入formatting_info會直接拋出異常,而讀取xls類型的文件時不存在此問題。
54 # 拋異常的原因是formatting_info還沒有對新版本的xlsx的格式完成兼容
55 sheet2 = wb2.sheet_by_name("業務場景")
56 print(sheet2.merged_cells)  # [(0, 1, 0, 8), (2, 6, 0, 1)]
57 # merged_cells返回的這四個參數的含義是:(row,row_range,col,col_range)
58 # 分別表示:開始的行索引、結束的行索引(不包含)、開始的列索引、結束的列索引(不包含)
59 # (0, 1, 0, 8) 表示第1行的1-8列 合並
60 # (2, 6, 0, 1) 表示3-6行的1-2列 合並
61 
62 # 分別獲取合並2個單元格的內容:
63 # 規律:獲取merge_cells返回的row和col低位的索引即可。
64 print(sheet2.cell(0, 0).value)
65 print(sheet2.cell_value(2, 0))
66 
67 # 使用以下方法更加方便
68 merge_value = []
69 for (row, row_range, col, col_range) in sheet2.merged_cells:
70     merge_value.append((row, col))
71 for v in merge_value:
72     print(sheet2.cell(v[0], v[1]).value)

 

3. xlwt

示例:

 1 import xlwt
 2 from datetime import datetime
 3 
 4 # 封裝樣式設置函數
 5 def set_style(font_name, height, bold=False, format_str=""):
 6     # 初始化樣式
 7     style = xlwt.XFStyle()
 8 
 9     # 初始化字體
10     font = xlwt.Font()
11     font.name = font_name  # 如:Times New Roman
12     font.bold = bold
13     font.height = height
14 
15     # 初始化邊框
16     borders = xlwt.Borders()
17     borders.left = 6
18     borders.right = 6
19     borders.top = 6
20     borders.bottom = 6
21 
22     # 為樣式賦值字體、邊框
23     style.font = font
24     style.borders = borders
25     style.num_format_str = format_str
26 
27     return style
28 
29 # 創建workbook對象
30 wb = xlwt.Workbook()
31 # 創建sheet(缺少指定sheet的方法)
32 ws = wb.add_sheet("New Sheet", cell_overwrite_ok=True)
33 
34 # 設置第一列列寬
35 ws.col(0).wodth = 200*30
36 
37 # 寫入普通單元格
38 # 分別傳參:行索引、列索引、需要寫入的值、樣式設置函數
39 ws.write(0, 0, "cell value", set_style("Time New Roman", 220, bold=True, format_str="#,##0.00"))
40 ws.write(0, 1, datetime.now(), set_style("Time New Roman", 220, bold=True, format_str="DD-MM-YYYY"))
41 # 值為時間類型時,format_str有如下選項:
42 # D-MMM-YY, D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0
43 
44 # 寫入合並單元格
45 # 參數含義:開始的行下標、結束的行下標(包含)、始的列下標、結束的列下標(包含)、寫入的內容
46 # 列合並:寫入第2行,第2~5列
47 ws.write_merge(1, 1, 1, 4, "列合並")
48 # 行合並:寫入第1~3行,第3列
49 ws.write_merge(0, 2, 2, 2, "行合並")
50 
51 # 添加新樣式
52 styleOK = xlwt.easyxf("pattern: fore_colour light_blue;font: colour green, bold True;")
53 # 實例化樣式類
54 pattern = xlwt.Pattern()
55 pattern.pattern = xlwt.Pattern.SOLID_PATTERN  # 固定樣式
56 pattern.pattern_fore_colour = xlwt.Style.colour_map["red"]  # 背景顏色
57 styleOK.pattern = pattern
58 
59 ws.write(6, 0, 1, style=styleOK)
60 ws.write(6, 1, 1)
61 ws.write(6, 2, xlwt.Formula("A3+B3"))
62 
63 # 保存(僅支持xls)
64 wb.save("e:\\test_xlwt.xls")

 


免責聲明!

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



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