How to Save a Pandas DataFrame to an Excel File Using DataFrame.to_excel
DataFrame.to_excel() is the primary method for exporting pandas data to Excel format, internally delegating to engine-specific writers like XlsxWriter or openpyxl for efficient workbook generation.
The pandas-dev/pandas library provides a robust interface for saving tabular data to Microsoft Excel format. When you need to save a pandas DataFrame to an Excel file, the to_excel() method serves as the high-level entry point, handling everything from basic CSV-like exports to complex multi-sheet workbooks with conditional formatting.
How DataFrame.to_excel Works Under the Hood
Understanding the internal execution flow helps optimize performance and troubleshoot engine-specific issues.
Entry Point in NDFrame
The method is defined on the base NDFrame class in pandas/core/generic.py#L2136. This implementation validates arguments, creates or reuses an ExcelWriter instance, and forwards the DataFrame to the writer's write implementation.
Engine Selection and ExcelWriter
If you do not provide an engine parameter, pandas automatically selects one based on the file extension and available optional dependencies. This logic resides in pandas/io/excel/_base.py#L254.
Supported engines include:
- xlsxwriter – The default for
.xlsxfiles; fast and feature-rich - openpyxl – Alternative for
.xlsxwith advanced styling support - odf – For OpenDocument formats
- xlwt/xlrd – Legacy support for
.xlsfiles (Python 2 era)
Engine Implementations
Each engine implements a write method that converts pandas data structures into native Excel representations. For the common .xlsx format, the implementation lives in [pandas/io/excel/_xlsxwriter.py](https://github.com/pandas-dev/pandas/blob/main/pandas/io/excel/_xlsxwriter.py), which uses the third-party XlsxWriter library to build worksheets and apply formatting. For openpyxl-specific features, see [pandas/io/excel/_openpyxl.py](https://github.com/pandas-dev/pandas/blob/main/pandas/io/excel/_openpyxl.py).
Styling Support
When exporting a Styler object (e.g., df.style.to_excel(...)), the styling logic in pandas/io/formats/style.py#L510 converts CSS-based styles into corresponding Excel format objects before writing to disk.
Saving a DataFrame to Excel: Code Examples
Basic Single-Sheet Export
The simplest approach writes DataFrame contents to Sheet1 by default:
import pandas as pd
df = pd.DataFrame({
"A": [1, 2, 3],
"B": ["x", "y", "z"]
})
df.to_excel("output.xlsx")
Custom Sheet Names and Index Control
Suppress the index column and specify a custom sheet name:
df.to_excel(
"custom_sheet.xlsx",
sheet_name="MyData",
index=False
)
Using Specific Engines with ExcelWriter
For advanced control over engine options or to write multiple sheets, use the ExcelWriter context manager:
with pd.ExcelWriter(
"styled.xlsx",
engine="xlsxwriter",
engine_kwargs={"options": {"strings_to_numbers": True}}
) as writer:
df.to_excel(writer, sheet_name="Table", freeze_panes=(1, 0))
# Access the underlying workbook via writer.book for low-level tweaks
Exporting Styled DataFrames
Export conditional formatting and colors using the Styler API:
styled = df.style.applymap(
lambda v: "background-color: yellow" if v == 2 else ""
)
styled.to_excel("styled_output.xlsx", engine="openpyxl")
Note that openpyxl preserves rich styling better than xlsxwriter for complex CSS conversions.
Writing Multiple DataFrames to Different Sheets
Append multiple DataFrames to separate sheets within the same workbook:
with pd.ExcelWriter("multi_sheet.xlsx") as writer:
df.to_excel(writer, sheet_name="First", index=False)
df.describe().to_excel(writer, sheet_name="Summary")
Summary
DataFrame.to_excel()inpandas/core/generic.pyprovides the user-facing API for Excel exports.- Engine selection occurs automatically in
pandas/io/excel/_base.pybased on file extensions and available dependencies. - XlsxWriter (via
pandas/io/excel/_xlsxwriter.py) is the default engine for.xlsxfiles, offering high performance and memory efficiency. - Openpyxl (via
pandas/io/excel/_openpyxl.py) excels at handling complex styling and formatting. ExcelWritercontext managers enable multi-sheet exports and engine-specific keyword arguments.- Styler objects leverage
pandas/io/formats/style.pyto translate CSS properties into Excel formats.
Frequently Asked Questions
What is the difference between the xlsxwriter and openpyxl engines?
XlsxWriter is optimized for writing speed and memory efficiency, making it ideal for large datasets, while openpyxl provides superior support for reading and writing complex styles, formulas, and existing workbook modifications. According to the pandas source code in pandas/io/excel/_base.py, xlsxwriter is the default for .xlsx files when both are installed.
How do I prevent the index column from appearing in my Excel file?
Pass index=False to the to_excel() method. By default, pandas writes the DataFrame index as the first column in the Excel sheet, which you can suppress to export only the data values.
Can I export pandas DataFrame styles (colors, fonts) to Excel?
Yes. Create a Styler object using df.style and chain formatting methods before calling to_excel(). The styling logic in pandas/io/formats/style.py converts CSS properties to Excel format objects. Use engine="openpyxl" for best compatibility with complex styles.
How do I write multiple DataFrames to different sheets in the same Excel file?
Use the pd.ExcelWriter() context manager. Within the with block, call to_excel() on each DataFrame and specify a unique sheet_name parameter. This reuses the same workbook object across writes, as implemented in pandas/io/excel/_base.py.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s https://instagit.com/install.md