Click here to Skip to main content
15,558,870 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using Python to output some tables into an existing Excel file by using the below code:

writer = pd.ExcelWriter("output.xlsx", engine='xlsxwriter')
dataframe1.to_excel(writer, sheet_name = 'data1', index = False)
dataframe2.to_excel(writer, sheet_name = 'data2', index = False)
writer.save()

This code would completely delete the existing Excel file, and reload the data to the two spreadsheets by creating a new Excel file. However, I have some pivot tables and charts linking to the data sitting in these two spreadsheets. So, the pivot tables and charts are gone after I run the code.

Is there a way to keep the original Excel file, and only replace the data in the "data1" and "data2" spreadsheets? such that the pivot tables and charts are still there and can be refreshed based on the newly replaced data.

Thank you very much for the help.

What I have tried:

I tried the below code but it doesn't work.

writer = pd.ExcelWriter("output.xlsx", engine='xlsxwriter')
dataframe1.to_excel(writer, sheet_name = 'data1', index = False)
dataframe2.to_excel(writer, sheet_name = 'data2', index = False)
writer.save()
Posted
Updated 5-Feb-21 5:14am

1 solution

Start with pandas.read_excel — pandas 1.2.1 documentation[^] to load the existing data. You can then modify it before writing it out. But for security always write the output to a different file so you do not destroy the original data.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900