12

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
  • 231
  • 1
  • 3
  • 8

4 Answers4

21

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

I believe still there's no direct way to do this, correct me if I'm wrong. That's the reason we need to play with these 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, or ignore it if you need any other better solution.

9

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
  • 174
  • 1
  • 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.

Fee
  • 177
  • 1
  • 3
0

I know this is an old question, but I faced the same issue recently and answers are not worked for me and here is how I solved the issue:

import pandas as pd
import xlwings as xw

filename = 'path\to\the\file.xlsx'
wb = xw.Book(filename)
wb.activate()
wb.app.screen_updating = False #xl will open and freeze
wb.app.display_alerts = False
wb.app.calculation = 'manual'

ws = wb.sheets['Sheet Name To Change']
ws.value = <DataFrameName>


wb.activate()
wb.app.screen_updating = True
wb.app.display_alerts = True
wb.app.calculation = 'automatic'
wb.save()

Let me know if you found this helpful, I am not very familiar with answering so please correct any kind of error.

123bmc
  • 27
  • 4