How to write to an existing Excel file without overwriting data using Python Pandas?

Sometimes, we want to write to an existing Excel file without overwriting data using Python Pandas.

In this article, we’ll look at how to write to an existing Excel file without overwriting data using Python Pandas.

How to write to an existing Excel file without overwriting data using Python Pandas?

To write to an existing Excel file without overwriting data using Python Pandas, we can use ExcelWriter.

For instance, we write

import pandas
from openpyxl import load_workbook

book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl') 
writer.book = book

writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()

to create the ExcelWriter instance with the Excel file path.

Load the workbook with

writer.book = book

We load the sheets with

writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

Then we write the columns Diff1 and Diff2 to the file with

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

And then we call save to save the changes.

Conclusion

To write to an existing Excel file without overwriting data using Python Pandas, we can use ExcelWriter.