【问题标题】:How to make Pandas Excel writer append to an existing sheet in a workbook instead of creating a new worksheet?如何使 Pandas Excel 编写器附加到工作簿中的现有工作表而不是创建新工作表?
【发布时间】:2019-04-25 17:25:30
【问题描述】:

我有一个带有两张工作表(“变量”、“固定”)的 Excel 工作簿。同时,我有一个包含一些数据的数据框(熊猫)。我想将数据框中的数据附加到该工作表中现有数据下方的工作表(“变量”)。但是,以下代码创建了一个名为“variable1”的新工作表并转储数据而不是附加到工作表“variable”。

path = "data.xlsx"
book = load_workbook(path)
writer = pd.ExcelWriter(path, engine='openpyxl', mode='a')
writer.book = book
df3.to_excel(writer, sheet_name="variable",startrow=9,
index=False,header=False)
writer.save()
writer.close()

我已经尝试了上面的代码。 df3 是我的熊猫数据框。我希望我的数据从第 9 行粘贴,因为现有数据一直到工作表“变量”中的第 8 行。该代码创建一个新工作表('variable1')并从第 9 行转储数据。我希望它将信息粘贴到工作表('variable')中,而不是创建一个新工作表。 有人可以帮我理解这种动态吗?

【问题讨论】:

    标签: pandas openpyxl pandas.excelwriter


    【解决方案1】:

    要附加一个 excel 文档,请使用:

    # open the workbook
    wb = openpyxl.load_workbook('file_name.xlsx')
    # assign a var to worksheet
    ws = wb['sheet_name']
    

    然后您可以执行以下操作:

    # write to cell 
    wb['sheet_name'].cell(row=4, column=1).value = string_to_enter_to_cell
    
    # format cells
    for row in ws['A4:L4']:
            for cell in row:
                cell.value = None
                cell.border = no_border
    

    【讨论】:

    • 感谢您的建议。最后,我最终将数据存储在两个不同的数据框中,并将它们连接起来并放入一个新的 Excel 表中。@55thSwiss
    • 酷,我很高兴你取得了一些进展 :)
    猜你喜欢
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多