Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite data on an existing excel sheet while preserving all other sheets?

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?

like image 820
user2436437 Avatar asked May 21 '20 11:05

user2436437


People also ask

How do I automatically update data from one spreadsheet to another?

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.


1 Answers

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.

like image 177
Mayank Porwal Avatar answered Sep 29 '22 07:09

Mayank Porwal