Home >Backend Development >Python Tutorial >How Can I Append a Pandas DataFrame to an Existing Excel Sheet in Python Without Overwriting?
Problem:
You have an existing Excel file and a Pandas DataFrame. You want to append the DataFrame to the end of the existing Excel sheet without overwriting it.
Solution:
There are two main approaches to append data to an existing Excel sheet using Pandas:
Approach 1: Using ExcelWriter
import pandas as pd df = pd.DataFrame(...) with pd.ExcelWriter('existing_sheet.xlsx', mode='a', engine='openpyxl') as writer: df.to_excel(writer, sheet_name='Sheet1', header=False, index=False, startrow=writer.sheets['Sheet1'].max_row + 1)
Approach 2: Using Openpyxl and Pandas
import pandas as pd from openpyxl import load_workbook df = pd.DataFrame(...) # Load existing Excel workbook book = load_workbook('existing_sheet.xlsx') sheet = book['Sheet1'] # Find last row in existing Excel sheet last_row = sheet.max_row # Append DataFrame data to existing sheet starting from last row + 1 pd.DataFrame.to_excel(df, book, sheet_name='Sheet1', startrow=last_row + 1, index=False) # Save changes to existing Excel file book.save('existing_sheet.xlsx')
Additional Tips:
The above is the detailed content of How Can I Append a Pandas DataFrame to an Existing Excel Sheet in Python Without Overwriting?. For more information, please follow other related articles on the PHP Chinese website!