Search code examples
python-3.xexcelpandasopenpyxlpandas.excelwriter

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

  • 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)