Table of Contents
Generating New Sheets in an Existing Excel File with Pandas
Understanding the Issue
Solution Using the "openpyxl" Engine
Explanation
WebSocket, ws, and Dict
Home Backend Development Python Tutorial How to Add New Sheets to an Existing Excel File Using Pandas?

How to Add New Sheets to an Existing Excel File Using Pandas?

Nov 03, 2024 am 07:06 AM

How to Add New Sheets to an Existing Excel File Using Pandas?

Generating New Sheets in an Existing Excel File with Pandas

When dealing with Excel data in Python, users may encounter the challenge of saving new sheets to an existing Excel file. This guide provides a solution using the Pandas library, covering the limitations of the "xlsxwriter" engine and the implementation of the "openpyxl" engine.

Understanding the Issue

In the given code, the user creates an Excel file with two sheets, "x1" and "x2." However, attempting to add new sheets, "x3" and "x4," overrides the original data. This occurs because the "xlsxwriter" engine only saves data to a new file or overwrites an existing one.

Solution Using the "openpyxl" Engine

To preserve existing data while adding new sheets, use the "openpyxl" engine. The following code demonstrates this approach:

<code class="python">import pandas as pd
import numpy as np
from openpyxl import load_workbook

path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"

book = load_workbook(path)  # Load the existing Excel file
writer = pd.ExcelWriter(path, engine='openpyxl')  # Create a Pandas writer connected to the workbook
writer.book = book  # Assign the workbook to the Pandas writer

x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)

x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)

df3.to_excel(writer, sheet_name='x3')  # Write the new dataframes to the existing file
df4.to_excel(writer, sheet_name='x4')

writer.close()  # Save the changes to the file</code>
Copy after login

Explanation

  1. Load the existing Excel file: This line reads the existing Excel file into a workbook object using the load_workbook function.
  2. Create a Pandas writer: Here, a Pandas ExcelWriter is created with the engine='openpyxl' parameter, which specifies the use of the "openpyxl" engine.
  3. Assign the workbook to the writer: The writer.book attribute is set to the loaded workbook object, linking the Pandas writer to the existing file.
  4. Generate new dataframes: Similar to the original code, new dataframes ("x3" and "x4") are created.
  5. Write new dataframes: The new dataframes are saved to the existing file using the to_excel method, specifying the sheet names ("x3" and "x4").
  6. Save changes: Finally, the changes made by the Pandas writer are saved to the Excel file by calling the writer.close() method.

WebSocket, ws, and Dict

In the suggested code from the given link:

  • WebSocket (ws): This refers to each worksheet in the loaded workbook.
  • ws.title: It represents the name of a specific worksheet within the workbook.
  • Dict: The code uses a dictionary to create a mapping between worksheet names and worksheet objects. This allows the Pandas writer to access specific sheets within the loaded workbook.

The above is the detailed content of How to Add New Sheets to an Existing Excel File Using Pandas?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles