I have a pandas dataframe df
which I want to overwrite to a sheet Data
of an excel file while preserving all the other sheets since other sheets have formulas linked to sheet Data
I used the following code but it does not overwrite an existing sheet, it just creates a new sheet with the name Data 1
with pd.ExcelWriter(filename, engine="openpyxl", mode="a") as writer:
df.to_excel(writer, sheet_name="Data")
Is there a way to overwrite on an existing sheet?
Go to the destination worksheet and click the cell where you want to link the cell from the source worksheet. On the Home tab, click on the drop-down arrow button of Paste, and select Paste Link from “Other Paste Options.” Or right-click in the cell on the destination worksheet and choose Paste Link from Paste Options.
You can do it using openpyxl
:
import pandas as pd
from openpyxl import load_workbook
book = load_workbook(filename)
writer = pd.ExcelWriter(filename, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df.to_excel(writer, "Data")
writer.save()
You need to initialize writer.sheets
in order to let ExcelWriter
know about the sheets. Otherwise, it will create a new sheet with the name that you pass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With