Sub topic 6
Saving a DataFrame to Excel
This chapter covers DataFrame.to_excel for a single sheet. You should already know how to build a DataFrame and read its dtypes, and how to install packages with pip. You should also know the basics of to_csv from the earlier chapters. Writing several sheets and formatting come in the next two chapters.
Why write Excel at all
Excel is the right output when the reader is a person who will open the file in a spreadsheet. Colleagues, managers and clients often expect .xlsx. It also stores real numbers and real dates in cells, so nothing needs re-parsing on open, which a CSV cannot guarantee. The cost is speed and size. Excel files are slower to write than CSV or Parquet, and a sheet has a hard row limit.
Install an engine first
pandas does not write .xlsx files itself. It delegates to a library called an engine. For .xlsx, the default engine is openpyxl, which you install separately:
pip install openpyxlWithout it, to_excel raises ModuleNotFoundError: No module named 'openpyxl'. The same package is also needed for read_excel on .xlsx files.
Other engines exist. xlsxwriter is a common alternative for write-only work with rich formatting. pandas 2.0 and later no longer write the old .xls format, because the xlwt engine was removed. Save as .xlsx unless you have a strong reason not to.
The minimal write
The examples in this chapter use this DataFrame. It has text, missing values, floats and dates.
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)This creates orders.xlsx with one sheet named orders. The first row holds the column names and the remaining rows hold the data. The file is overwritten if it already exists, with no warning.
Cell types follow the dtypes. Integers and floats become numeric cells. The datetime64 column becomes real date cells, which Excel can sort and filter as dates. Missing values (None and NaN) become empty cells.
Why `index=False` matters
By default, to_excel writes the index as the first column. With a default RangeIndex that gives you a column of 0, 1, 2 with an empty header. Reading the file back then shows it as Unnamed: 0:
df.to_excel("orders_with_index.xlsx", sheet_name="orders")
back = pd.read_excel("orders_with_index.xlsx")
print(back.columns.tolist())
# ['Unnamed: 0', 'order_id', 'customer', 'amount', 'ordered_at']
back = pd.read_excel("orders_with_index.xlsx", index_col=0)
print(back.columns.tolist())
# ['order_id', 'customer', 'amount', 'ordered_at']Use index=False when the index is only a row counter. Keep it when the index carries meaning, such as dates or customer IDs, and give it a name with index_label="order_key" so the header cell is not blank.
Common arguments
| Argument | What it does | Default |
|---|---|---|
| `sheet_name` | Name of the sheet. | `"Sheet1"` |
| `index` | Write the index as a column. | `True` |
| `index_label` | Header text for the index column. | index name |
| `header` | `True`, `False`, or a list of names that replaces the column names. | `True` |
| `columns` | Subset and order of columns to write. | all columns |
| `na_rep` | Text written in place of missing values. | `""` (empty cell) |
| `float_format` | A `%` format string applied to floats, such as `"%.2f"`. | `None` |
| `startrow`, `startcol` | Zero-based position of the upper-left cell. | `0`, `0` |
| `freeze_panes` | `(rows, cols)` to keep visible while scrolling. | `None` |
| `engine` | `"openpyxl"` or `"xlsxwriter"`. | chosen from the extension |
Sheet names have limits. Excel allows at most 31 characters and rejects [ ] : * ? / \. A bad name raises an error when the file is written, so check names you build from data.
A worked example with options
This call selects and renames columns, marks missing values, rounds floats, leaves two blank rows for a title, and freezes the header.
df.to_excel(
"orders_report.xlsx",
sheet_name="orders",
index=False,
columns=["order_id", "customer", "amount"],
header=["ID", "Customer", "Amount"],
na_rep="n/a",
float_format="%.2f",
startrow=2,
startcol=1,
freeze_panes=(3, 0),
)Points to notice:
startrow=2puts the header in spreadsheet row 3, and the data starts in row 4.startcol=1leaves column A empty.freeze_panes=(3, 0)freezes the top three rows, so the header stays visible while you scroll. The numbers count rows and columns from the top-left of the sheet, not from the data.headertakes a list with exactly one name per written column. A list of the wrong length raises aValueError.na_rep="n/a"writes the textn/ainto the cell. In theamountcolumn that mixes text into a numeric column. That is fine for a human reader, but it is a problem if the file feeds a formula or another program.
The two blank rows are empty on purpose. You can fill them afterwards with a title, using the ExcelWriter techniques from the next chapter.
float_format changes the stored value
float_format does not only change how a number is displayed. pandas formats the float with your string and stores the rounded result in the cell:
pd.DataFrame({"x": [1.23456]}).to_excel("rounded.xlsx", index=False)
pd.DataFrame({"x": [1.23456]}).to_excel("rounded2.xlsx", index=False, float_format="%.2f")
print(pd.read_excel("rounded.xlsx")["x"][0]) # 1.23456
print(pd.read_excel("rounded2.xlsx")["x"][0]) # 1.23Once the file is saved, the extra digits are gone. If a reader needs full precision but a tidy look, write the full value and format the cells in Excel instead. Number formats for cells are covered in the formatting chapter.
Dates, times and time zones
Naive datetime64 columns are written as Excel dates and times. A column that has only midnight times still gets a date-and-time cell format by default, which some readers find noisy. The date format is set on the writer, not on to_excel:
with pd.ExcelWriter(
"orders_dates.xlsx",
engine="openpyxl",
date_format="YYYY-MM-DD",
datetime_format="YYYY-MM-DD HH:MM",
) as writer:
df.to_excel(writer, sheet_name="orders", index=False)Excel has no concept of time zones. A column of timezone-aware timestamps fails with ValueError: Excel does not support datetimes with timezones. Remove the zone first, after converting to the zone you want readers to see:
events = pd.DataFrame({
"at": pd.to_datetime(["2026-03-01 09:00", "2026-03-01 17:30"]).tz_localize("UTC"),
})
events["at"] = events["at"].dt.tz_convert("Europe/Berlin").dt.tz_localize(None)
events.to_excel("events.xlsx", index=False)After this the sheet shows Berlin local times, and the zone information is not recorded anywhere in the file. Put the zone in the column name (such as at_berlin) so the reader knows.
Gotchas with cell contents
- Strings that start with
=. openpyxl treats a string beginning with=as a formula. A value such as"=1+1"shows up as2in Excel, and a malformed one can produce an error cell or a corrupt-file warning. This is also a security concern when the data comes from users, because spreadsheet formulas can run functions. Prefix or clean untrusted text before writing it. - Long text. A single cell holds at most 32,767 characters. Longer strings are truncated or rejected, depending on the engine.
- Infinite values.
infand-infare written as the text"inf"and"-inf"by default. Change this withinf_rep, or replace them withNaNfirst. - Large integers. Excel stores numbers as 64-bit floats, so integers beyond about 15 digits (long IDs, card numbers) lose precision when a person edits or reads them in Excel. Write such IDs as strings.
- Row limit. A sheet holds at most 1,048,576 rows and 16,384 columns. A larger DataFrame raises an error or must be split. If your data is that large, CSV or Parquet is the better choice.
- A file open in Excel. On Windows, writing to a workbook that is open in Excel fails with
PermissionError. Close it, or write to a new name.
Reading it back
Reading the file back is the quickest check that the write worked:
back = pd.read_excel("orders.xlsx", sheet_name="orders")
print(back.dtypes)Dates come back as datetime64[ns], numbers as int64 or float64, and empty cells as NaN. Unlike CSV, no parse_dates argument is needed, because Excel stores the type of each cell. Columns that mix text and numbers come back as object. The full verification technique appears in the last chapter.
Exercise
You run df.to_excel("report.xlsx") on a DataFrame with the default index, then open the file and see an extra first column with an empty header. Later pd.read_excel("report.xlsx") returns a column named Unnamed: 0. What single argument avoids this, and what would you do instead if the index held meaningful customer IDs?
Show answer
Pass index=False to to_excel so the index is not written. If the index holds meaningful IDs, keep it and name it with index_label="customer_id" (or give the index a name before writing), then read it back with index_col=0 in read_excel.
Exercise
A DataFrame column contains timestamps created with tz_localize("UTC"). to_excel raises a ValueError. Write the line that converts the column at to Berlin local time and removes the zone so the write succeeds.
Show answer
df["at"] = df["at"].dt.tz_convert("Europe/Berlin").dt.tz_localize(None). Excel cannot store time zones, so the zone must be removed. Convert to the wanted zone first so the displayed times are correct.