'ExcelWriter not overwriting sheet and instead creating a new one

This might be going right over my head.

I am using this block:

writer = pd.ExcelWriter(
    filepath, engine="openpyxl", mode="a", if_sheet_exists="replace"
)
df.to_excel(writer, "MySheetName", index=False)
writer.save()

to overwrite an existing Excel sheet with a pandas dataframe.

This is not overwriting the sheet 'MySheetName' and is instead creating a new sheet called 'MySheetName1'.

What am I missing here?



Solution 1:[1]

Not a real answer but I did a workaround by just deleting the original sheet and renaming the duplicate afterwards.

        from openpyxl import load_workbook
        wb = load_workbook(path)
        if 'Provider Detail' in wb.sheetnames:
            wb.remove(wb['Name'])
        wb.save(path)

        ss_sheet = wb['Name1']
        ss_sheet.title = 'Name'
        wb.save(path)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 smitty_werben_jagerm