• Post author:
  • Post category:Pandas
  • Post last modified:March 27, 2024
  • Reading time:12 mins read
You are currently viewing Pandas Write to Excel with Examples

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

Pandas to Excel Key Points

  • By default, it uses .xlsx.writer if it is installed otherwise it uses openpyxl
  • Supports saving multiple DataFrames to a single sheet.
  • Save multiple sheets, and append existing sheets or files.
  • Use ExcelWriter()

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 write excel

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

This creates an excel file with the contents as below. By default, It exports column names, indexes, and data to a sheet named 'Sheet1'.

pandas write excel

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

2. Write to Multiple Sheets

The ExcelWriter class allows you to write or export multiple Pandas DataFrames to separate sheets. First, you need to create an object for ExcelWriter.

The below example writes data from df object to a sheet named Technologies and df2 object 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')

3. Append to Existing Excel File

ExcelWriter can be used to append DataFrame to an excel file. Use mode param with value 'a' to append. The code below opens an existing file and adds data from the DataFrame 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')

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

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

Frequently Asked Questions on Pandas Write to Excel

How do I write a Pandas DataFrame to an Excel file?

You can use the to_excel() method of a Pandas DataFrame to write it to an Excel file.

How can I specify the sheet name when writing 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).

How do I write multiple DataFrames to different sheets in the same Excel file?

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)

How can I set the index in the Excel file and control whether it is included or not?

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 this article, you have learned how to write Pandas DataFrame to an excel file by using to_excel(). Also explored how to write to specific sheets, multiple sheets, and append to existing excel files.

References

Naveen Nelamali

Naveen Nelamali (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn and Medium