6

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()
prashant
  • 151
  • 1
  • 1
  • 7

3 Answers3

16

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.

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)
SoloDolo
  • 76
  • 5
1

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.

Gevaert Joep
  • 111
  • 2