Use pandas to_excel()
function to write a DataFrame to an Excel sheet with extension .xlsx. By default it writes a single DataFrame to an Excel file, you can also write multiple sheets by using an ExcelWriter object with a target file name, and sheet name to write to.
Note that creating an ExcelWriter object with a file name that already exists will result in the contents of the existing file being erased.
Related: Pandas read Excel Sheet
Key Points –
- Pandas provides the
to_excel()
function to export DataFrames to Excel files, allowing seamless integration with Excel for data analysis and reporting tasks. - By default, Pandas uses
xlsx.writer
if installed, otherwise, it falls back toopenpyxl
, ensuring compatibility across different environments. - For more control over Excel file writing,
ExcelWriter()
context manager can be used. It enables saving multiple DataFrames to a single sheet or multiple sheets within a single Excel file. - While
xlsx.writer
generally offers better performance, the choice between available backends may depend on the specific needs of the project and the environment in which it is executed.
Let’s create a pandas DataFrame from the list and explore using the to_excel()
function by using multiple parameters.
import pandas as pd
import numpy as np
# Create multiple lists
technologies = ['Spark','Pandas','Java','Python', 'PHP']
fee = [25000,20000,15000,15000,18000]
duration = ['5o Days','35 Days',np.nan,'30 Days', '30 Days']
discount = [2000,1000,800,500,800]
columns=['Courses','Fee','Duration','Discount']
# Create DataFrame from multiple lists
df = pd.DataFrame(list(zip(technologies,fee,duration,discount)), columns=columns)
print("Create DataFrame:\n", df)
Yields below output.
Pandas DataFrame to Excel
Use the to_excel()
function to write or export Pandas DataFrame to an excel sheet with the extension xslx. Using this you can write an excel file to the local file system, S3 e.t.c. Not specifying any parameter by default, it writes to a single sheet.
This function takes several optional parameters that can be used to skip the columns, skip the rows, not to write index, set column names, formatting, and many more.
# Write DataFrame to Excel file
df.to_excel('Courses.xlsx')
print(df)
By default, Pandas creates an Excel file with the contents below. It exports column names, indexes, and data to a sheet named Sheet1
.
You can change the name of the sheet from Sheet1 to something that makes sense to your data by using sheet_name
param. The below example exports it to the sheet named ‘Technologies
‘.
# Write dataframe to excel file with sheet name
df.to_excel('Courses.xlsx', sheet_name='Technologies')
Write to Multiple Sheets
The ExcelWriter class in Pandas allows you to export multiple Pandas DataFrames to separate sheets within the same Excel file. Before writing the DataFrames, you first need to create an instance of the ExcelWriter class.
In the following example, data from the DataFrame object df
is written to a sheet named Technologies
, and data from the DataFrame object df2
is written to a sheet named Schedule
.
# Write to Multiple Sheets
with pd.ExcelWriter('Courses.xlsx') as writer:
df.to_excel(writer, sheet_name='Technologies')
df2.to_excel(writer, sheet_name='Schedule')
Append to Existing Excel File
You can utilize ExcelWriter to append a DataFrame to an existing Excel file. Set the mode
parameter to a
to append data. The provided code opens an existing file and adds DataFrame data to the specified sheet.
# Append dataframe to existing excel file
with pd.ExcelWriter('Courses.xlsx',mode='a') as writer:
df.to_excel(writer, sheet_name='Technologies')
Save Selected Columns
Use param columns
to save selected columns from DataFrame to an excel file. The below example only saves columns Fee
, Duration
to excel file.
# Save Selected Columns to Excel File
df.to_excel('Courses.xlsx', columns = ['Fee','Duration'])
Use header
param with a list of values if you want to write with different column names.
Skip Index
To skip Index from writing use index=False
param. By default, it is set to True
mean writing a numerical Index to an excel sheet.
# Skip Index
df.to_excel('Courses.xlsx', index = False)
FAQ on Pandas Write to Excel
You can use the to_excel()
method of a Pandas DataFrame to write it to an Excel file.
You can specify the sheet name using the sheet_name
parameter in the to_excel()
method. For example, df.to_excel('output.xlsx', sheet_name='Sheet1', index=False)
.
You can use the ExcelWriter
object to write multiple DataFrames to different sheets within the same Excel file. For example, with pd.ExcelWriter('output.xlsx', engine='xlsxwriter') as writer: df1.to_excel(writer, sheet_name='Sheet1', index=False) df2.to_excel(writer, sheet_name='Sheet2', index=False)
Use the index
parameter in the to_excel()
method. To exclude the index, set it to False
. To include the index, set it to True
(default behavior). For example, df.to_excel('output.xlsx', index=False)
Conclusion
In conclusion, this article has demonstrated how to write a Pandas DataFrame to an Excel file using the to_excel()
function. You have also explored methods to write data to specific sheets, manage multiple sheets within a single file, and append data to existing Excel files.
Related Articles
- pandas write CSV file
- Pandas Read Multiple CSV Files into DataFrame
- How to Read Excel Multiple Sheets in Pandas
- Pretty Print Pandas DataFrame or Series?
- Pandas Handle Missing Data in Dataframe
- How to read CSV without headers in pandas
- How to Create Pandas Pivot Multiple Columns
- Pandas Pivot Table Explained with Examples