Overwrite an excel sheet with pandas dataframe without affecting other sheets

13,643

Solution 1

I didn't find any other option other than this, this would be a quick solution for you.

I believe still there'sno direct way to do this, correct me if I'm wrong. That's the reason we need to play with this logical ways.

import pandas as pd

def write_excel(filename,sheetname,dataframe):
    with pd.ExcelWriter(filename, engine='openpyxl', mode='a') as writer: 
        workBook = writer.book
        try:
            workBook.remove(workBook[sheetname])
        except:
            print("Worksheet does not exist")
        finally:
            dataframe.to_excel(writer, sheet_name=sheetname,index=False)
            writer.save()

df = pd.DataFrame({'Col1':[1,2,3,4,5,6], 'col2':['foo','bar','foobar','barfoo','foofoo','barbar']})

write_excel('PRODUCT.xlsx','PRODUCTS',df)

Let me know if you found this helpful, igonre if you need any other better solution.

Solution 2

Similar to Gavaert's answer... For Pandas 1.3.5, add the 'if_sheet_exists="replace"' option:

import pandas as pd

with pd.ExcelWriter("file.xlsx", engine="openpyxl", mode="a", if_sheet_exists="replace") as writer:
    df.to_excel(writer, 'Logs', index=False)

Solution 3

Since Pandas version 1.3.0 on_sheet_exists is an option of ExcelWriter. It can be used as such:

import pandas as pd

with pd.ExcelWriter("my_sheet.xlsx",engine="openpyxl",mode="a",on_sheet_exists="replace") as writer:
    pd.write_excel(writer,df)

Since none of the ExcelWriter methods or properties are public, it is advised to not use them.

Share:
13,643
prashant
Author by

prashant

Updated on June 17, 2022

Comments

  • prashant
    prashant almost 2 years

    I want to overwrite an existing sheet in an excel file with Pandas dataframe but don't want any changes in other sheets of the same file. How this can be achieved. I tried below code but instead of overwriting, it is appending the data in 'Sheet2'.

    import pandas as pd
    from openpyxl import load_workbook
    
    book = load_workbook('sample.xlsx')
    writer = pd.ExcelWriter('sample.xlsx', engine = 'openpyxl')
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
    df.to_excel(writer, 'sheet2', index = False)
    writer.save()