作用:操作Excel文檔
讀取
1.openpyxl.load_workbook():打開文檔
>>> wb = openpyxl.load_workbook('example.xlsx')#該文件需要在當前工作目錄下
2.wb.get_sheet_names()#獲取當前工作簿中的表名
3.sheet = wb.get_sheet_by_name('Sheet3')#獲取表
4.an = wb.get_active_sheet()#獲取活動表
5.sheet['A1'].value#獲取表中A1格數據
6.c= sheet['B1'],>>> c.row#c指向的數據所在的行
>>> c.column #c指向的數據所在的列
>>> c.coordinate#c指向的數據所在的二維位置
7.sheet.cell(row=1,column=2)#返回第一行第二列數據
8.>>> sheet.max_column#獲取最大列的列數(數字)
>>> sheet.max_row#獲取最大行所在的行數
9.(sheet['A1':'C3'])#切片,獲取A1到C3二維表格內容,可以用for來遍歷
for rowOfcellobjects in sheet['A1':'C3']:for cellObj in rowOfcellobjects:
print(cellObj.coordinate,cellObj.value)
10.sheet.columns[1]#獲取第一列,可遍歷
sheet.rows[1]#獲取第一行
寫入
1.wb = openpyxl.Workbook()#創建一個新的工作簿,默認只有一個表,表名爲Sheet
2.sheet.title = ' '#修改表名
3.wb.save('cyl.xlsx')#將工作簿保存爲cyl.xlsx
4.wb.create_sheet(index=x,title = 'x')#在當前工作簿的第x-1個位置創建表x
5.wb.remove_sheet(wb.get_sheet_by_name())#刪除表
利用公式
sheet['B9'] = ' =SUM(B1:B9)'#公式以等號開始
調整行、列
1.sheet.sheet.row_dimensions[x].height=#設置第x行行高
2.sheet.column_dimensions['B'].width = #設置B列列寬
3.sheet.merge_cells['A1:D3']#合併單元格
4.sheet.unmerge_cells['A1:D3']#拆分單元格,將A1拆分爲A1到D3
5.sheet.freeze_panes = 'B2'#凍結B2單元格所在行上邊的行(不包括本行)以及左邊的列