Function: Manipulate Excel documents
read
1.openpyxl.load_workbook(): Open the document
>>> wb = openpyxl.load_workbook('example.xlsx')#The file needs to be in the current working directory
2.wb.get_sheet_names()#Get the sheet names in the current workbook
3.sheet = wb.get_sheet_by_name('Sheet3')#获取表
4.an = wb.get_active_sheet()#Get the active sheet
5.sheet['A1'].value#Get the data of grid A1 in the table
6.c= sheet['B1'], >>> the row where the data pointed to by c.row#c
>>> c.column #c refers to the column where the data is located
>>> The 2D position of the data pointed to by c.coordinate#c
7.sheet.cell(row=1,column=2)#Return the data of the first row and the second column
8. >>> sheet.max_column#Get the maximum number of columns (numbers)
>>> sheet.max_row#Get the number of rows where the maximum row is located
9.(sheet['A1':'C3'])#Slice, get the content of the two-dimensional table from A1 to C3, you can use for to traverse
for rowOfcellobjects in sheet['A1':'C3']:for cellObj in rowOfcellobjects:
print(cellObj.coordinate,cellObj.value)
10.sheet.columns[1]#Get the first column, which can be traversed
sheet.rows[1]#Get the first row
write
1.wb = openpyxl.Workbook()#Create a new workbook, there is only one table by default, the table name is Sheet
2.sheet.title = ' '#Modify sheet name
3.wb.save('cyl.xlsx')#Save the workbook as cyl.xlsx
4.wb.create_sheet(index=x,title = 'x')#Create sheet x at the x-1 position of the current workbook
5.wb.remove_sheet(wb.get_sheet_by_name())#删除表
Use the formula
sheet['B9'] = ' =SUM(B1:B9)'#The formula starts with an equal sign
Adjust rows and columns
1.sheet.sheet.row_dimensions[x].height=#Set the row height of the xth row
2.sheet.column_dimensions['B'].width = #Set the column width of column B
3.sheet.merge_cells['A1:D3']#merge cells
4.sheet.unmerge_cells['A1:D3']#Split cells, split A1 into A1 to D3
5.sheet.freeze_panes = 'B2'# Freeze the row above the row where the B2 cell is located (excluding this row) and the column on the left