To append existing Excel sheet with new dataframe using Python Pandas, we can use ExcelWriter
.
For instance, we write
import pandas as pd
import openpyxl
workbook = openpyxl.load_workbook("test.xlsx")
writer = pd.ExcelWriter('test.xlsx', engine='openpyxl')
writer.book = workbook
writer.sheets = dict((ws.title, ws) for ws in workbook.worksheets)
data_df.to_excel(writer, 'Existing_sheetname')
writer.save()
writer.close()
to call load_workbook
with the Excel file path.
Then we caLL ExcelWrite
to create the writer
.
And set writer.book
to workbook
.
Then we get the sheets from workbook.worksheets
and convert it to a dict before assigning it to writer.sheets
.
Next, we call to_excel
with writer
and a sheet name that already exists to append the Excel sheet values to the data_df
dataframe.
Then we save the writer
and close it.