0
0
Pandasdata~5 mins

Writing to Excel with to_excel in Pandas

Choose your learning style9 modes available
Introduction

We use to_excel to save data from a table (DataFrame) into an Excel file. This helps share or keep data in a common, easy-to-open format.

You want to share your data analysis results with someone who uses Excel.
You need to save your cleaned data for later use in Excel.
You want to create reports that others can open in Excel.
You want to export data from Python to Excel for further manual editing.
You want to back up your data in a widely used spreadsheet format.
Syntax
Pandas
DataFrame.to_excel(excel_writer, sheet_name='Sheet1', index=True, header=True)

excel_writer is the file path or Excel writer object where data will be saved.

sheet_name sets the name of the Excel sheet (default is 'Sheet1').

Examples
Saves the DataFrame df to an Excel file named output.xlsx with default sheet name and index included.
Pandas
df.to_excel('output.xlsx')
Saves df to output.xlsx with sheet named 'Data' and without row index numbers.
Pandas
df.to_excel('output.xlsx', sheet_name='Data', index=False)
Saves df without column headers in the Excel file.
Pandas
df.to_excel('output.xlsx', header=False)
Sample Program

This program creates a small table with names and ages, saves it to an Excel file named people.xlsx on a sheet called 'PeopleData', without row indexes. Then it reads the file back and prints it to confirm the data saved correctly.

Pandas
import pandas as pd

# Create a simple DataFrame
 data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
 df = pd.DataFrame(data)

# Save DataFrame to Excel file
 df.to_excel('people.xlsx', sheet_name='PeopleData', index=False)

# Read back the file to check
 df_check = pd.read_excel('people.xlsx', sheet_name='PeopleData')
print(df_check)
OutputSuccess
Important Notes

If you do not want to save the row numbers, set index=False.

You need to have the openpyxl package installed to write Excel files (.xlsx).

By default, column headers are saved. Use header=False to skip them.

Summary

to_excel saves your DataFrame as an Excel file for easy sharing and storage.

You can choose the sheet name, and whether to include row indexes and headers.

Make sure to install openpyxl to work with Excel files in pandas.