Sub topic 7
Writing several sheets to one workbook
This chapter covers pd.ExcelWriter, the object that lets you put several DataFrames into one .xlsx file. It assumes you can already write a single sheet with to_excel, have openpyxl installed, and know how to build and group a DataFrame.
Why one `to_excel` call is not enough
A call such as df.to_excel("report.xlsx") opens the file, writes one sheet, and closes the file. If you make a second call with the same filename, pandas replaces the whole workbook. Only the second sheet survives.
import pandas as pd
a = pd.DataFrame({"x": [1, 2]})
b = pd.DataFrame({"y": [3, 4]})
a.to_excel("broken.xlsx", sheet_name="a", index=False)
b.to_excel("broken.xlsx", sheet_name="b", index=False) # overwrites the file
print(pd.ExcelFile("broken.xlsx").sheet_names)The output is ['b']. Sheet a is gone.
To keep both sheets, open the workbook once, write every sheet into it, and then save it once. pd.ExcelWriter does this.
Using ExcelWriter as a context manager
ExcelWriter holds the open workbook. You pass the writer object, instead of a filename, as the first argument of to_excel. Using it in a with block guarantees that the file is saved and closed when the block ends, even if an error occurs.
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")Points to notice:
- The workbook is written to disk when the
withblock exits. Until then, nothing is guaranteed to be in the file. engine="openpyxl"names the library that writes.xlsxfiles. If you omit it, pandas picks an installed engine from the file extension. Naming it makes the code behave the same on every machine.sheet_namesets the tab label. The default is"Sheet1", so give each sheet a distinct name or a later write will collide with an earlier one.index=Falseis used forordersbecause the default integer index carries no information. Thesummaryframe keeps its index, since the customer names are the index there. Dropping it would delete the only column that says whose total each row is.freeze_panes=(1, 0)keeps the first row visible while the user scrolls. The tuple is(rows, columns)to freeze, so(1, 0)freezes one row and no columns.
What the call sequence looks like
Each to_excel call on the writer adds one sheet to the in-memory workbook. Closing the writer saves it.
Writing many DataFrames in a loop
When the sheets come from a dictionary, loop over it inside one with block.
import pandas as pd
sales = pd.DataFrame({
"country": ["DE", "DE", "FR", "FR", "ES"],
"amount": [10.0, 12.5, 8.0, 9.5, 4.0],
})
parts = {name: group for name, group in sales.groupby("country")}
with pd.ExcelWriter("by_country.xlsx", engine="openpyxl") as writer:
for country, part in parts.items():
part.to_excel(writer, sheet_name=country, index=False)
print(pd.ExcelFile("by_country.xlsx").sheet_names)The output is ['DE', 'ES', 'FR']. The order follows the dictionary, which groupby fills in sorted key order.
Sheet names are limited. Excel rejects names longer than 31 characters. It also rejects names that contain any of [ ] : * ? / \, and names that are empty. If your sheet names come from data, clean them first:
import re
def safe_sheet_name(name: str) -> str:
cleaned = re.sub(r"[\[\]:*?/\\]", "_", str(name)).strip("'")
return cleaned[:31] or "sheet"
print(safe_sheet_name("Q1/Q2: North*East"))This prints Q1_Q2_ North_East. Two different inputs can clean to the same name, and the second write would then collide with the first. Check for duplicates if your names are user supplied.
Placing several tables on one sheet
A sheet is not limited to one table. The startrow and startcol arguments of to_excel set the top-left cell of the output, counting from zero. This is useful for a report that shows a detail table and a small total beside it.
import pandas as pd
detail = pd.DataFrame({"item": ["pen", "ink"], "qty": [3, 5]})
total = pd.DataFrame({"total_qty": [detail["qty"].sum()]})
with pd.ExcelWriter("one_sheet.xlsx", engine="openpyxl") as writer:
detail.to_excel(writer, sheet_name="report", index=False)
total.to_excel(
writer,
sheet_name="report",
index=False,
startrow=0,
startcol=4,
)Both calls name the sheet report, and the second writes into column E of the same sheet. Within one writer session, a repeated sheet name is the way to write more than one block to one sheet. The startcol offset leaves columns C and D empty so the blocks do not overlap. If the blocks did overlap, the later write would overwrite the cells of the earlier one.
Adding to an existing workbook
Sometimes the workbook already exists and you want to add a sheet. Open the writer in append mode with mode="a". You must also say what to do when a sheet name already exists, through if_sheet_exists.
import pandas as pd
extra = pd.DataFrame({"note": ["checked", "approved"]})
with pd.ExcelWriter(
"report.xlsx",
engine="openpyxl",
mode="a",
if_sheet_exists="replace",
) as writer:
extra.to_excel(writer, sheet_name="notes", index=False)The if_sheet_exists argument accepts these values:
| Value | Behavior when the sheet already exists |
|---|---|
| `"error"` | Raises `ValueError`. This is the default. |
| `"replace"` | Deletes the old sheet and writes the new one in its place. |
| `"new"` | Writes to a new sheet with a changed name, so nothing is lost. |
| `"overlay"` | Writes into the existing sheet, leaving other cells as they are. |
Append mode has these limits:
- It works with
openpyxl, which can read existing files. It does not work withxlsxwriter, which can only create new files. - The file must exist. In the default mode
"w", a file is created or replaced. In"a", a missing file raisesFileNotFoundError. openpyxlloads and rewrites the whole workbook. Charts, images, and some features it does not understand can be lost, so test with a copy of any workbook that someone built by hand.
Engines: which one writes the file
engine chooses the library behind the writer.
| Engine | Can append to files | Notes |
|---|---|---|
| `openpyxl` | Yes | Default for `.xlsx` when installed. Install with `pip install openpyxl`. |
| `xlsxwriter` | No | Creates new files only. Rich formatting. Install with `pip install xlsxwriter`. |
The engine also determines how you reach the formatting features of the underlying library, which the next chapter covers. For now, remember that writer.book is the workbook object and writer.sheets is a dictionary of the sheets written so far.
import pandas as pd
df = pd.DataFrame({"a": [1, 2]})
with pd.ExcelWriter("peek.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="data", index=False)
print(list(writer.sheets))This prints ['data']. The sheet is visible in writer.sheets as soon as it is written, before the file is saved.
Common errors
- Only the last sheet is present. You called
to_excelwith a filename repeatedly. Use oneExcelWriterinstead. ModuleNotFoundError: No module named 'openpyxl'. The engine is not installed. Runpip install openpyxl.ValueError: Sheet 'orders' already exists and if_sheet_exists is set to 'error'.You are in append mode and the name is taken. Pick a new name or setif_sheet_exists.ValueErrorabout an invalid sheet title. The name is over 31 characters or has a forbidden character. Clean it as shown above.- The file is empty or corrupt after a crash. The save happens when the writer closes. Always use the
withblock so closing is not skipped, and write to a temporary name first if other people read the file. - Duplicate sheets named
Sheet1. You omittedsheet_nameon several calls. Always name each sheet.
Exercises
Exercise
A script calls df1.to_excel("out.xlsx", sheet_name="first") and then df2.to_excel("out.xlsx", sheet_name="second"). Which sheets does out.xlsx contain, and how do you change the code so that it contains both?
Show answer
It contains only second, because the second call recreates the file. Open the file once with with pd.ExcelWriter("out.xlsx", engine="openpyxl") as writer: and call df1.to_excel(writer, sheet_name="first") and df2.to_excel(writer, sheet_name="second") inside the block.
Exercise
You have report.xlsx with a sheet named orders. You run a script with mode="a" that writes a new DataFrame to a sheet also named orders, and you did not set if_sheet_exists. What happens, and which setting keeps the old data while still saving the new data?
Show answer
pandas raises a ValueError, because the default is "error". Setting if_sheet_exists="new" writes the new data to a sheet with a changed name and leaves the old sheet untouched. Setting "replace" would delete the old data.
Exercise
Write a with block that saves a DataFrame detail to the sheet detail of two_tables.xlsx and a DataFrame total to the same sheet starting at column index 6, with no index column in either.
Show answer
with pd.ExcelWriter("twotables.xlsx", engine="openpyxl") as writer: detail.toexcel(writer, sheetname="detail", index=False) total.toexcel(writer, sheet_name="detail", index=False, startcol=6)