Home >Backend Development >Python Tutorial >How to Add New Sheets to an Existing Excel File Using 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.
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.
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>
In the suggested code from the given link:
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!