Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to save a pandas dataframe to an existing Excel sheet updating the entire sheet using openpyxl?

I have a dataframe:

data = {'Name': ['John', 'Laura', 'Colin', 'David'],
        'Age': [25, 30, 35, 40],
        'City': ['New York', 'London', 'Paris', 'Berlin']}

# Creating DataFrame 
df = pd.DataFrame(data)

I want to export this dataframe to the existing Excel file (.xlsx) ‘Data.xlsx’ to sheet ‘Sheet1’. The dataframe should start from the cell ‘A1’. If there is existing data on the sheet, I want to update the entire sheet. I tried the code below:

from openpyxl import load_workbook

file_path = 'Data.xlsx'

wb = load_workbook(file_path)

ws = wb['Sheet1']

ws['A1'] = df 

wb.save(file_path)

However, the following error occurs:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[4 rows x 3 columns] to Excel

How to fix it?

>Solution :

Why not use built in to_excel() with 'openpyxl' engine? use pd.ExcelWriter to keep the existing sheets

with pd.ExcelWriter(file_path, engine='openpyxl', mode='a') as writer:
    df.to_excel(writer, sheet_name='Sheet1', index=False)

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading