【问题标题】:Struggling to append dataframe to existing .xlsx file in PythonStruggling to append dataframe to existing .xlsx file in Python
【发布时间】:2022-12-27 15:30:20
【问题描述】:

I am trying to append a dataframe to an existing excel spreadsheet, but I am having trouble appending it to an existing SHEET (my excel file only has one sheet, titled "Sheet1," that contains the existing dataset).

    with pd.ExcelWriter(xlsx_path, mode="a", engine="openpyxl",sheet_name="Sheet1",if_sheet_exists="overlay") as writer:
          transfer.to_excel(writer,header=None,index=False)

When I use the aforementioned code, when I open the existing spreadsheet, the new data from the dataframe I requested to be appended via the to_excel function appears in a separate sheet, entitled "Sheet 11." Can someone elucidate why this is occurring? How can I just get the new data from the dataframe to appear at the bottom of the existing spreadsheet in Sheet1?

Thanks!

Refer to notes written above.

【问题讨论】:

    标签: python excel pandas dataframe openpyxl


    【解决方案1】:

    I dont know why the data is appended to 'Sheet11', however 'sheet_name=' is not an attribute in ExcelWriter so you should get a warning about that. The attribute should be used with 'to_excel'.
    You'll need to state what row to append from otherwise the new data will start from row 1 over-writting any existing data. You can get the max row for the sheet and use that.

    sheet_to_update = 'Sheet1'
    with pd.ExcelWriter(xlsx_path,
                        mode="a",
                        engine="openpyxl",
                        if_sheet_exists="overlay") as writer:
        transfer.to_excel(writer,
                    header=None,
                    index=False,
                    sheet_name=sheet_to_update,
                    startrow=writer.sheets[sheet_to_update].max_row)
    

    【讨论】:

      猜你喜欢
      • 2022-12-01
      • 2022-12-19
      • 2022-12-02
      • 1970-01-01
      • 2022-12-02
      • 2023-02-24
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多