0
0
PandasHow-ToBeginner · 3 min read

How to Write Excel Files Using pandas in Python

To write Excel files in pandas, use the DataFrame.to_excel() method. You need to provide the filename and optionally specify the sheet name. This method saves your DataFrame as an Excel file that you can open with Excel or other spreadsheet software.
📐

Syntax

The basic syntax to write a pandas DataFrame to an Excel file is:

  • df.to_excel('filename.xlsx', sheet_name='Sheet1', index=False)

Here, df is your DataFrame, filename.xlsx is the output file name, sheet_name sets the Excel sheet name, and index=False prevents writing row numbers.

python
df.to_excel('filename.xlsx', sheet_name='Sheet1', index=False)
💻

Example

This example creates a simple DataFrame and writes it to an Excel file named output.xlsx. It shows how to save data and control the sheet name and index.

python
import pandas as pd

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

df.to_excel('output.xlsx', sheet_name='People', index=False)
print('Excel file saved as output.xlsx')
Output
Excel file saved as output.xlsx
⚠️

Common Pitfalls

Common mistakes when writing Excel files with pandas include:

  • Forgetting to install openpyxl or xlsxwriter which pandas uses to write Excel files.
  • Not setting index=False if you don't want row numbers saved.
  • Using an invalid filename or path.

Always ensure the required engine is installed and the filename is correct.

python
import pandas as pd

data = {'A': [1, 2], 'B': [3, 4]}
df = pd.DataFrame(data)

# Wrong: missing engine and index saved by default
# df.to_excel('file.xls')  # May cause error or save index unintentionally

# Right: specify engine and avoid saving index

df.to_excel('file.xlsx', engine='openpyxl', index=False)
📊

Quick Reference

ParameterDescriptionDefault
pathFile path or object to write toRequired
sheet_nameName of the Excel sheet'Sheet1'
indexWrite row names (index)True
engineExcel writer engine ('openpyxl', 'xlsxwriter')Auto-detected
startrowUpper left cell row to start writing0
startcolUpper left cell column to start writing0

Key Takeaways

Use df.to_excel('filename.xlsx') to save DataFrame as an Excel file.
Set index=False to avoid saving row numbers unless needed.
Install openpyxl or xlsxwriter to enable Excel writing support.
Specify sheet_name to control the Excel sheet where data is saved.
Check file path and name to avoid errors when saving.