Sub topic 6
Saving a DataFrame to Excel
This chapter assumes you can build and inspect a DataFrame, install packages with pip, and run a script or notebook. You should also know the column dtypes int, float, string, and datetime.
Why Excel, and what it needs
Excel files (.xlsx) suit readers who will open the result in a spreadsheet. They hold several sheets and basic formatting. They are slower and larger than CSV or Parquet, so they are a poor choice for big data.
pandas does not write .xlsx files by itself. It relies on a separate library called an engine. For .xlsx, the usual engine is openpyxl. Install it first:
# Run once in a terminal:
# pip install openpyxlIf the engine is missing, to_excel raises an ImportError that names the package to install.
Writing one sheet
The method DataFrame.to_excel writes a DataFrame to one sheet. This example uses the same orders data as the CSV chapters.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3],
"customer": ["Ana", "Ben", None],
"amount": [19.99, 5.5, None],
"ordered_at": pd.to_datetime(["2026-01-05", "2026-01-06", "2026-01-07"]),
})
df.to_excel("orders.xlsx", sheet_name="orders", index=False)The arguments work like this:
- The first argument is the output path. The
.xlsxextension lets pandas pick the engine. sheet_namesets the tab name. The default is"Sheet1".index=Falseleaves out the row index. Without it, you get an extra first column of 0, 1, 2.
What Excel stores
Excel keeps cell types, so the round trip is better than with CSV. Numbers stay numbers and dates stay dates. Missing values become empty cells.
| Pandas value | Excel cell |
|---|---|
| int, float | Number |
| str | Text |
| datetime | Date and time, shown with a date format |
| None or NaN | Empty cell |
Reading the file back shows the effect:
back = pd.read_excel("orders.xlsx", sheet_name="orders")
print(back.dtypes)The ordered_at column returns as datetime64, with no parse_dates argument needed. Reading uses the same engine rule: openpyxl must be installed for read_excel too.
Common errors
- Timezone-aware datetimes. Excel cannot store timezones. Writing such a column raises a
ValueError. Remove the timezone first withdf["ordered_at"].dt.tz_localize(None), or convert to UTC before dropping it. - A locked file. If the
.xlsxis open in Excel on Windows, the write fails with aPermissionError. Close the file and run again. - Overwriting by accident.
to_excelreplaces any existing file at that path. Use a new name if you need to keep the old one. - Row limit. A sheet holds at most 1,048,576 rows and 16,384 columns. Larger frames raise an error or need splitting.
How the write flows
Checking your work
After writing, read the file back and look at the shape and dtypes. A quick check catches an unwanted index column, which shows up as an Unnamed: 0 column on read.
back = pd.read_excel("orders.xlsx")
print(back.shape)
print(list(back.columns))For df above, this prints (3, 4) and the four column names.
Exercise
You run df.toexcel("out.xlsx") and later read the file with pd.readexcel("out.xlsx"). The result has an extra column called "Unnamed: 0". Why does it appear, and how do you prevent it?
Show answer
toexcel writes the row index as the first column by default, and it has no header name, so readexcel labels it "Unnamed: 0". Prevent it by writing with index=False.
Exercise
A DataFrame column holds timezone-aware datetimes and to_excel raises a ValueError. What is a fix?
Show answer
Excel cannot store timezones. Strip the timezone before writing, for example df["col"] = df["col"].dt.tz_localize(None), after converting to the zone you want to show.