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:
[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)
