【问题标题】:How to append a dataframe to an existing excel sheet (without overwriting it) after openpyxl update?openpyxl更新后如何将数据框附加到现有的excel工作表(不覆盖它)?
【发布时间】: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”参数。 如何更正此代码,以便将我的数据附加到工作表的最后一行?

【问题讨论】:

    标签: python excel openpyxl


    【解决方案1】:

    if_sheet_exists=replace 添加到df.to_excel 的末尾应该可以,如下所示:

    df.to_excel(writer, 'Preço_por_quilo', startrow = len(ws["C"]), header = False, index = False, if_sheet_exists='replace')
    

    更多关于它的使用信息可以在这里找到: https://pandas.pydata.org/docs/reference/api/pandas.ExcelWriter.html

    【讨论】:

    • 这不起作用,它返回“TypeError: to_excel() got an unexpected keyword argument 'if_sheet_exists'”。反过来,将此参数添加到 ExcelWriter 会覆盖现有工作表(我会丢失工作表上的数据)。
    • 您是否尝试过将 if_sheet_exists 设置为 None?参数也应该放在 writer 的原始声明中,而不是 df.to_excel()
    • 这也返回“ValueError: Sheet 'Preço_por_quilo' 已经存在并且 if_sheet_exists 设置为 'error'。”
    • if_sheet_exists 参数不与to_excel() 一起使用,而是与pandas.ExcelWriter 一起使用。这就是你得到这个错误的原因。我也有这个问题。看起来如果工作表存在,该怎么做的选择是'replace','new','error',它们分别创建替换现有工作表,创建一个名称略有不同的单独工作表(可能附加一个'_1'或其他东西),或引发错误。看起来没有附加到现有工作表的选项,考虑到这是进入附加模式的全部意义,这有点令人沮丧,对吧?
    猜你喜欢
    • 2017-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 2021-10-15
    • 1970-01-01
    相关资源
    最近更新 更多