准备工作
openpyxl只能处理xslx表格,处理不了xsl
导入依赖包
1 from openpyxl import Workbook, load_workbook
工作簿当中有多个工作表,工作表中有多条记录
工作表sheet
默认工作表
1 2 3 4 5 6 wb = Workbook() wb2 = load_workbook('./test2.xlsx' ) ws = wb.active print (ws.title) wb.save("./test.xlsx" )
本地表格读取到内存中,所有操作影响的只是内存中的数据,要想使本地的表格数据变化,需要调用save()
方法保存到本地
创建工作表
1 2 ws2 = wb.create_sheet("my_sheet2" , 1 )
修改工作表(查、增、删、改)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 print (ws.max_row) print (ws.max_column) print (ws.dimensions) print (ws.encoding) print (ws.sheet_view) ws1.title = "my_sheet111" names = wb.get_sheet_names() sheet_names = wb.sheetnames sheet = wb.get_sheet_by_name("Sheet" ) sheet = wb["Sheet" ] index = wb.index(ws2) wb.move_sheet("my_sheet111" , -1 ) del wb["my_sheet111" ] cp_sheet = wb.copy_worksheet(ws1)
操作单元格
获取和修改单个单元格
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 from openpyxl import Workbookwb = Workbook() ws = wb.active cell = ws["a6" ] cell2 = ws.cell(1 , 2 ) ws["a5" ] = 666 ws['A3' ] = datetime.datetime.now().strftime("%Y-%m-%d" ) ws.append([1 , 2 , 3 ]) cell = ws["a6" ] cell.value = 777 print (cell, cell.value) cell2 = ws.cell(6 , 1 ) print (cell2, cell2.value) print (c.coordinate) print (c.column_letter) print (c.col_idx) print (c.row)
获取多个单元格
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 from openpyxl import Workbookwb = Workbook() ws = wb.active i = 1 for x in range (1 , 11 ): for y in range (1 , 21 ): ws.cell(row=x, column=y, value=i) i += 1 row_cells = ws[2 ] print (row_cells) col_cells = ws["b" ] print (col_cells) row_range_cells = ws[2 :5 ] print (row_range_cells) col_range_cells = ws["B:D" ] print (col_range_cells) range_cells = ws["c3:f6" ] print (range_cells) cells = ws.iter_rows(min_row=1 , max_row=3 , min_col=2 , max_col=5 ) for cell in cells: print (cell) cells = ws.iter_cols(min_row=1 , max_row=3 , min_col=2 , max_col=5 ) for cell in cells: print (cell) for cell in ws.rows: print (cell) for cell in ws.columns: print (cell) for row in ws.values: for value in row: print (value)
操作单元格
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 from openpyxl import Workbookwb = Workbook() ws = wb.active i = 1 for x in range (1 , 11 ): for y in range (1 , 21 ): ws.cell(row=x, column=y, value=i) i += 1 print (ws["C2" ].value) ws.merge_cells("A1:F3" ) ws.unmerge_cells("A1:F3" ) print (ws["C2" ].value) ws.insert_cols(5 ) ws.insert_rows(2 , 3 ) ws.delete_cols(2 , 3 ) ws.delete_rows(5 , 3 ) ws.move_range("B1:D3" , rows=6 , cols=-1 , translate=False )