Python将数据帧附加到现有的Excel文件和工作表。
Python将数据帧附加到现有的Excel文件和工作表。
我有一个关于将DataFrame附加到现有文件的现有表格上的问题。
我尝试自己编写代码:
writer = pd.ExcelWriter('existingFile.xlsx', engine='openpyxl', mode='a') df.to_excel(writer, sheet_name="existingSheet", startrow=writer.sheets["existingSheet"].max_row, index=False, header=False)
但是会导致一个错误:
ValueError: Sheet 'existingSheet' already exists and if_sheet_exists is set to 'error'.
我在Google上找到了这个函数在这里;
Append existing excel sheet with new dataframe using python pandas
即使使用了这个函数,仍然会导致相同的错误,尽管我认为这个函数可以防止这个具体的错误。
能否请您帮忙?
非常感谢!
问题的原因是,在将DataFrame附加到现有的Excel文件和工作表时,使用了错误的参数设置,导致内容被替换而不是追加。
解决方法是,在ExcelWriter中添加关键字参数if_sheet_exists,并将其设置为'replace'。这样就可以使用最新版本的pandas,并将DataFrame追加到工作表中。
下面是正确的代码示例:
import pandas as pd # 打开现有的Excel文件,使用openpyxl引擎 writer = pd.ExcelWriter('existingFile.xlsx', engine='openpyxl', mode='a', if_sheet_exists='replace') # 将DataFrame追加到工作表中 df.to_excel(writer, sheet_name='Sheet1', index=False) # 保存并关闭Excel文件 writer.save() writer.close()
这样做将确保DataFrame被追加到现有的工作表中,而不是替换其中的内容。
问题出现的原因是Pandas 1.4版本中的`if_sheet_exists`参数的`overlay`选项无法正常工作。根据提问者的回答,他们尝试了使用pandas==1.4.0版本,但并没有报错,只是每次都会覆盖已存在的表格。
解决方法是使用旧版本的pandas。提问者在问题中提供了一个解决方法,即在`pd.ExcelWriter`中使用`engine='openpyxl'`、`mode='a'`和`if_sheet_exists='overlay'`参数。代码如下:
with pd.ExcelWriter(excelPath, engine='openpyxl', mode='a', if_sheet_exists='overlay') as writer: timeseries.to_excel(writer, timeseriesSheetName)
这种方法在pandas 1.4.2版本中有效。如果你遇到了同样的问题,可以尝试使用这种方法来将DataFrame追加到现有的Excel文件和工作表中。