【发布时间】:2021-09-20 12:59:13
【问题描述】:
我有一个现有的 excel 文件,我必须每周用新数据更新它,并将其附加到现有工作表的最后一行。按照这篇文章How to write to an existing excel file without overwriting data (using pandas)?中提供的解决方案,我以这种方式完成了这项工作@
import pandas as pd
import openpyxl
from openpyxl import load_workbook
book = load_workbook(excel_path)
writer = pd.ExcelWriter(excel_path, engine = 'openpyxl', mode = 'a')
writer.book = book
## ExcelWriter for some reason uses writer.sheets to access the sheet.
## If you leave it empty it will not know that sheet Main is already there
## and will create a new sheet.
ws = book.worksheets[1]
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df.to_excel(writer, 'Preço_por_quilo', startrow = len(ws["C"]), header = False, index = False)
writer.save()
writer.close()
这段代码运行正常,直到今天,它返回以下错误:
ValueError: Sheet 'Preço_por_quilo' already exists and if_sheet_exists is set to 'error'.
这显然是由 openpyxl 包的最新更新产生的,它向 ExcelWriter 函数添加了“if_sheet_exists”参数。 如何更正此代码,以便将我的数据附加到工作表的最后一行?
【问题讨论】: