Home > Backend Development > Python Tutorial > How Can I Append Data to an Existing Excel Sheet Using Pandas Without Overwriting?

How Can I Append Data to an Existing Excel Sheet Using Pandas Without Overwriting?

DDD
Release: 2024-12-25 05:57:13
Original
794 people have browsed it

How Can I Append Data to an Existing Excel Sheet Using Pandas Without Overwriting?

Writing to Existing Excel Files without Overwriting Data Using Pandas

When using pandas to write to Excel files without overwriting existing data, a common scenario arises when you want to add a new sheet to a previously created file. However, the default behavior of pandas overwrites the entire file, erasing any existing tabs. To overcome this issue, we can leverage the openpyxl library.

Openpyxl Integration with Pandas ExcelWriter

Pandas utilizes openpyxl to handle XLSX files. By explicitly setting the 'engine' parameter in ExcelWriter to 'openpyxl,' we can gain access to more granular control over the file's content.

Code Implementation

import pandas
from openpyxl import load_workbook

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

# Populate a dictionary of existing sheets for ExcelWriter
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

# Write to the desired sheet without overwriting
data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()
Copy after login

In this code:

  • We load the existing Excel file using openpyxl's load_workbook.
  • We create a Pandas ExcelWriter object with the 'engine' parameter set to 'openpyxl,' linking it to our loaded workbook.
  • We populate the writer.sheets dictionary with the existing sheets to prevent ExcelWriter from creating a new "Main" sheet.
  • We write our desired data to the "Main" sheet without overwriting any other sections in the workbook.
  • Finally, we save the updated workbook to retain the changes.

The above is the detailed content of How Can I Append Data to an Existing Excel Sheet Using Pandas Without Overwriting?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template