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")