Sub topic 7
Writing several sheets to one workbook
This chapter assumes you can write a single sheet with df.to_excel, have openpyxl installed, and know how to build a DataFrame and a groupby summary.
Why one call per file does not work
Each call to df.to_excel("report.xlsx") with a file name opens the file and writes it from scratch. If you call it twice with the same path, the second call replaces the first. The workbook ends up with only the last sheet.
To put several DataFrames in one workbook, open the file once and write each DataFrame into it. pd.ExcelWriter does this.
Using ExcelWriter
pd.ExcelWriter is an object that holds an open workbook. You pass it to to_excel in place of a file name, and each call adds a sheet. Use it as a context manager (a with block), so the file is saved and closed when the block ends.
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"]),
})
summary = df.groupby("customer", dropna=True)["amount"].sum().to_frame()
with pd.ExcelWriter("report.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="orders", index=False, freeze_panes=(1, 0))
summary.to_excel(writer, sheet_name="summary")The workbook now has two sheets, orders and summary.
engine="openpyxl"selects the library that writes.xlsxfiles. pandas picks it for you if it is installed, but naming it makes the dependency explicit.sheet_namesets the tab name. The default isSheet1, so two calls without names would collide.index=Falseis used fordfbecause its index is just row numbers.- The
summarycall keeps the index, because aftergroupbythe customer names are the index. Dropping it would lose them. freeze_panes=(1, 0)freezes the first row, so the header stays visible when you scroll. The tuple is(rows, columns)to freeze.
Placing data on a sheet
You can write more than one DataFrame to the same sheet. Give startrow or startcol to move the next block so it does not overwrite the first.
with pd.ExcelWriter("side_by_side.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="report", index=False)
summary.to_excel(writer, sheet_name="report", startcol=6)Both frames land on the sheet report. The summary starts at column G (zero-based column 6), leaving a gap after the four columns of df.
Appending to an existing workbook
By default ExcelWriter creates a new file and overwrites any file at that path. To add sheets to a workbook that already exists, use append mode.
with pd.ExcelWriter(
"report.xlsx",
engine="openpyxl",
mode="a",
if_sheet_exists="replace",
) as writer:
summary.to_excel(writer, sheet_name="summary_v2")mode="a" is supported by openpyxl. if_sheet_exists says what to do when a sheet name is already taken: "error" (the default), "replace", "new" (pandas picks a fresh name), or "overlay" (write over the existing cells). It is only valid together with mode="a".
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Only the last sheet is in the file | Several `to_excel("file.xlsx")` calls, each overwriting the file | Use one `ExcelWriter` and pass `writer` |
| `ValueError: Sheet 'summary' already exists` | Append mode with a repeated name | Set `if_sheet_exists` or change the name |
| File is empty or corrupt | The writer was never closed | Use a `with` block, or call `writer.close()` |
| Sheet name rejected | Names over 31 characters, or containing `[ ] : * ? / \` | Shorten and clean the name |
Exercise
You call df.to_excel("out.xlsx", sheet_name="a") and then other.to_excel("out.xlsx", sheet_name="b"). The file contains only sheet b. Rewrite the code so both sheets are kept, and say why index=False may be wrong for a groupby result.
Show answer
Open one writer and pass it to both calls: with pd.ExcelWriter("out.xlsx") as writer: then df.to_excel(writer, sheet_name="a") and other.to_excel(writer, sheet_name="b"). The first version failed because each call with a file name rewrites the whole file. A groupby result stores its group labels in the index, so index=False would drop them and leave only the aggregated values.