Skip to content

ENH: #40231 does not allow writing multiple dataframes to a single sheet #42221

Closed
@feefladder

Description

@feefladder

The problem

The following code works well, both in 1.4.0 and 1.2.5:

df = pd.DataFrame(["=1+7"])
with pd.ExcelWriter("test.xlsx",engine="openpyxl") as writer:
    df.to_excel(writer,sheet_name="Sheet2")
    pd.DataFrame(["=1+1"]).to_excel(writer,sheet_name="Sheet2",header=None,index=False,startcol=4,startrow=3)

however, the following code raises an error in 1.4.0, but works in 1.2.5 (it creates a new sheet and writes both dataframes to it):

pd.DataFrame(["=1+1"]).to_excel("test.xlsx")
df = pd.DataFrame(["=1+7"])
with pd.ExcelWriter("test.xlsx",engine="openpyxl",mode="a") as writer:
    df.to_excel(writer,sheet_name="Sheet2")
    pd.DataFrame(["=1+1"]).to_excel(writer,sheet_name="Sheet2",header=None,index=False,startcol=4,startrow=3)

Also other options cannot replicate the old behaviour.

Describe the solution you'd like

An added option to if_sheet_exists="write_to" that justs selects the sheet and writes into it, without first deleting its contents. This also allows to append a dataframe within a sheet.

EDIT: in #40230 this was also suggested behaviour, but it was not implemented:

Originally I considered adding a flag like overwrite=True to pd.ExcelWriter but I don't think this would be sufficient to cover all the potential behaviours, so would suggest an enum along the lines of the if_exists option in df.to_sql, with the following options:

* new_sheet: Create a new sheet with a different name.

* overwrite_sheet: Delete the contents of the sheet, then write to it.

* overwrite_cells: Write directly to the named sheet without deleting the previous contents.

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementIO Excelread_excel, to_excelRegressionFunctionality that used to work in a prior pandas version

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions