How to write to existing Excel file in Pandas

In this post you learn how to write to existing Excel file in Pandas library of Python. In pandas, you can write to an existing Excel file using the pandas.DataFrame.to_excel method.

Example of writing to Excel file

Here is an example:

import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'col1': [1, 2, 3, 4, 5], 'col2': [3, 4, 5, 6, 7]})

# write data to an existing Excel file
writer = pd.ExcelWriter('existing_file.xlsx', engine='openpyxl', mode='a')
df.to_excel(writer, index=False, sheet_name='Sheet1')
writer.save()

How to write to existing Excel file in Pandas

In this example, existing_file.xlsx is the name of the existing Excel file. The engine parameter is set to ‘openpyxl’ to specify the engine used to write the file, and mode=’a’ means to open the file in append mode, so the new data will be appended to the existing data instead of overwriting it. The sheet_name parameter is set to ‘Sheet1’ to specify the name of the sheet where the data will be written. The index parameter is set to False to exclude the index column.

Note: The script is showing the warning you should be aware of in the future versions:

FutureWarning: save is not part of the public API, usage can give unexpected results and will be removed in a future version
writer.save()

This Post Has 3 Comments

Leave a Reply