python模塊之——openpyxl 處理xlsx/ xlsm文件
項目原因需要編輯excel文件,經過查詢,最先嘗試xlwt 、wlrd這個兩個模塊,但是很快發現這兩個模塊只能編輯xls文件,然而office07 之后的excel默認保存格式都是xlsx / xlsm,所以xlwt 、wlrd解決不了問題。后來發現openpyxl模塊就是為處理 xlsx/xlsm/xltx/xltm而存在的,最終用該模塊完美的解決的問題。但是請注意,openpyxl也只能處理xlsx、xlsm文件,對xls也只能改道之前提到的兩個模塊。
一、openpyxl模塊介紹
Author: Eric Gazoni , Charlie Clark
網址:openpyxl.readthedocs.io/en/stable/
該模塊有幾個重要的概念:Workbooks、Sheets、Cells,通過這三個概念,就可以定位到最細的cell,並對其進行刪除、修改、增加等操作。
二、安裝
在cmd中 $ pip install openpyxl就可以完成
三、使用
1、創建新文件並編輯
import openpyxl ################ #創建一個新的workbook wb=openpyxl.Workbook() #創建一個worksheet ws = wb.active #插入sheet ws1=wb.create_sheet("Mysheet") # insert at the end (default) ws2 = wb.create_sheet("Mysheet", 0) # insert at first position #對sheet2名進行修改 ws2.title = "New Title" #獲取一個sheet,使其可進行編輯,使用方式和字典使用一樣 w2=wb["New Tile"] #這樣就可以對sheet3編輯了 #改變sheet名的背景色 ws2.sheet_properties.tabColor = "1072BA" #獲取所有已經創建的sheetnames wb.sheetnames #遍歷所有的sheet for sheet in wb: print(sheet.title) ########################## #編輯處理cell的內容 (方法一) ws1["A4"]="Hello" #編輯處理cell的內容 (方法二) ws1.cell(row=4,column=2,value=10) #編輯處理cell的內容 (方法三) ws1.cell(row=4,column=3).value=20 #Notes & Warning: #When a worksheet is created in memory, it contains no cells. They are created when first accessed. #When a worksheet is created in memory, it contains no cells. They are created when first accessed. #Because of this feature, scrolling through cells instead of accessing them directly will create them all in memory, even if you don’t assign them a value. #Something like for i in range(1,101): for j in range(1,101): ws.cell(row=i, column=j) #will create 100x100 cells in memory, for nothing. ########################## #處理多cell cell_range=ws["A1":"C2"] colC=ws["C"] col_range=ws["C:D"] row10=ws[10] row_range=ws[3:6] #遍歷cell (按照rows遍歷) for row in ws.iter_rows(min_row=1,min_col=1,max_col=3,max_row=2): ````for cell in row: ```` print(cell) <Cell Sheet1.A1> <Cell Sheet1.B1> <Cell Sheet1.C1> <Cell Sheet1.A2> <Cell Sheet1.B2> <Cell Sheet1.C2> #遍歷cell (按照cols遍歷) for row in ws.iter_cols(min_row=1,min_col=1,max_col=3,max_row=2): ````for cell in row: ```` print(cell) <Cell Sheet1.A1> <Cell Sheet1.A2> <Cell Sheet1.B1> <Cell Sheet1.B2> <Cell Sheet1.C1> <Cell Sheet1.C2> wb.save("G:/TEMP/test.xlsx")
2.讀取並編輯已經存在的文件
import openpyxl FilePath="G:/TEMP" FileName="test.xlsx" wb=openpyxl.load_workbook(FilePath+"/"+FileName) lisSheetName=wb.sheetnames print(lisSheetName) ws=wb[lisSheetName[1]] #編輯處理cell的內容 (方法一) ws["A4"]="Hello" #編輯處理cell的內容 (方法二) ws.cell(row=4,column=2,value=10) #編輯處理cell的內容 (方法三) ws.cell(row=4,column=3).value=20
wb.save(FilePath+"/"+FileName)
3. 附加
#在excel插入函數和公式 ws["D4"]="=SUM(1,1)" ws["E4"]="=SUM(A4:D4)" # 插入畫圖 #(略)
更詳細可搜索openpyxl進入官方文檔查詢