


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>
Explanation
- Load the existing Excel file: This line reads the existing Excel file into a workbook object using the load_workbook function.
- Create a Pandas writer: Here, a Pandas ExcelWriter is created with the engine='openpyxl' parameter, which specifies the use of the "openpyxl" engine.
- 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.
- Generate new dataframes: Similar to the original code, new dataframes ("x3" and "x4") are created.
- Write new dataframes: The new dataframes are saved to the existing file using the to_excel method, specifying the sheet names ("x3" and "x4").
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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 when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

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 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? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Fastapi ...

Using python in Linux terminal...

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)...
