最近在工作的時候需要追加寫Excel,但是在百度上搜的都不是pandas 最新的版本,都是舊版本,官網給的列子也騙我,只好自己去讀源碼,找原因,今天把這個記錄下來,省着以后再忘。
Python版本:3.9
pandas版本:1.3.0
首先呢,創造一下數據:
from pandas import ExcelWriter import pandas as pd df = pd.DataFrame([i for i in range(1, 10)]) with ExcelWriter("path_to_file.xlsx", mode="w", engine="openpyxl") as writer: df.to_excel(writer, sheet_name="Sheet31", index_label="數據")
得到的樣本數據為:
得到如圖所示的數據
然后我們進行追加操作:
with ExcelWriter("path_to_file.xlsx", mode="a", engine="openpyxl") as writer: writer.if_sheet_exists = "replace" # 在此版本的pandas 中,加入的這個屬性,他有三個值:now , replace, error 這三個屬性分別對應着:創建新的sheet,替換當前sheet里面的內容,當存在sheet 時,拋出異常 df1 = pd.read_excel("path_to_file.xlsx", index_col="數據") # 由於沒有找到好的方法,所以我們讀出之前文件的內容 f = [df1, df] result = pd.concat(f, axis=0) # 將兩個文件concat,也就是合並 result.to_excel(writer, sheet_name="Sheet31", index_label="數據") # 保存 注意:index_label必須要和上面的index_col相同,不然下次讀文件的時候會出index_col不存在的錯誤
參考圖片
致辭,敬禮!博客園原創,引用請貼出原文鏈接。感謝支持。