Home >Backend Development >Python Tutorial >How Can I Append a Pandas DataFrame to an Existing Excel Sheet in Python Without Overwriting?

How Can I Append a Pandas DataFrame to an Existing Excel Sheet in Python Without Overwriting?

DDD
DDDOriginal
2024-12-03 12:49:11567browse

How Can I Append a Pandas DataFrame to an Existing Excel Sheet in Python Without Overwriting?

Append Existing Excel Sheet with New Dataframe Using Python Pandas

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:

  • If the sheet doesn't exist, Pandas will automatically create it.
  • You can specify the start row for appending data using the startrow parameter.
  • To preserve existing cell styles, set with_style=True in the copy_excel_cell_range function when using the Openpyxl and Pandas approach.
  • For Pandas versions < 1.4.0, use the helper function in the linked code example to append data without overwriting.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn