How to write to an Excel spreadsheet using Python?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Python can write Excel files through several libraries, but the two most common workflows are: use pandas when your data is already tabular, or use openpyxl when you need cell-level control. The right tool depends on whether you are exporting a table or building a workbook more manually.
Write a DataFrame with pandas
If your data is already in a DataFrame, to_excel is the fastest route:
That creates an Excel workbook with one sheet and writes the rows directly. index=False avoids exporting the DataFrame index as an extra column.
Write Multiple Sheets
Pandas can also write several DataFrames into one workbook:
This is a good pattern for reports that need more than one worksheet.
Use openpyxl for Cell-Level Control
If you need to control individual cells, formulas, or workbook structure directly, use openpyxl:
This approach is more verbose than pandas, but it gives you direct workbook editing behavior.
Add Simple Formatting
openpyxl also lets you style cells:
That is often enough for headers, emphasis, or basic report polish.
Choose the Library by Use Case
A practical rule is:
- use pandas for DataFrame exports
- use
openpyxlfor workbook editing and formatting - use both together when needed, because pandas can write the data and
openpyxlcan refine the workbook afterward
This split keeps the code simpler than forcing one tool to do everything.
File Format Notes
Most modern Python Excel workflows target .xlsx. Older .xls support is much more limited and is rarely the best default for new code.
Also remember that Excel files are not plain text. If the file is open in Excel while your script writes it, the save can fail depending on the operating system and application state.
Updating an Existing Workbook
If you need to edit an existing Excel file instead of creating a new one, openpyxl is usually the better tool:
That kind of in-place workbook editing is much harder to express cleanly with a pure pandas export workflow.
Common Pitfalls
The biggest pitfall is forgetting index=False in pandas and accidentally exporting the DataFrame index as a normal column.
Another common issue is mixing up libraries. openpyxl works on .xlsx files and provides workbook control, while pandas is mainly about structured table export.
People also forget that writing to an existing workbook may overwrite sheets or files if they do not choose append or update behavior deliberately.
Summary
- Use
DataFrame.to_excel()when your data is already in pandas. - Use
openpyxlwhen you need cell-by-cell control or formatting. - Write multiple sheets with
pd.ExcelWriter. - Prefer
.xlsxfor modern Excel output. - Pick the library based on whether your task is tabular export or workbook manipulation.

