To combine Excel sheets in Python, you can use the pandas
library. Here’s an example that demonstrates how to achieve this:
import pandas as pd
# Read the Excel sheets into separate dataframes
df1 = pd.read_excel('file.xlsx', sheet_name='Sheet1')
df2 = pd.read_excel('file.xlsx', sheet_name='Sheet2')
# Combine the dataframes
combined_df = pd.concat([df1, df2], ignore_index=True)
# Write the combined dataframe to a new Excel file
combined_df.to_excel('combined_file.xlsx', index=False)
In this example, we assume you have an Excel file named ‘file.xlsx’ with two sheets: ‘Sheet1’ and ‘Sheet2’. We read each sheet into separate dataframes (df1
and df2
) using the read_excel()
function from pandas. Make sure to specify the correct sheet names in the sheet_name
parameter.
Then, we combine the dataframes using the concat()
function from pandas. We pass the dataframes as a list [df1, df2]
and set ignore_index=True
to reindex the combined dataframe.
Finally, we write the combined dataframe to a new Excel file named ‘combined_file.xlsx’ using the to_excel()
function.
Make sure to replace 'file.xlsx'
with the path to your Excel file and specify the correct sheet names. Also, replace 'combined_file.xlsx'
with the desired output filename.
+ There are no comments
Add yours