Sub topic 8
Excel limits, engines, and light formatting
This chapter assumes you can already write a sheet with to_excel and ExcelWriter, and that you know how to install packages with pip. It covers three things: the hard limits of an .xlsx file, which library does the writing, and how to make a sheet readable.
Limits you cannot get around
An .xlsx worksheet has fixed capacity. Pandas does not split data across sheets for you.
| Limit | Value |
|---|---|
| Rows per sheet | 1,048,576 (the header uses one) |
| Columns per sheet | 16,384 |
| Characters per cell | 32,767 |
Writing a larger frame fails, or truncates text silently. Check the size before you write, and fall back to Parquet or CSV when the data is too big.
import pandas as pd
MAX_ROWS = 1_048_576 - 1 # one row is the header
def save_excel_or_parquet(df: pd.DataFrame, stem: str) -> str:
if len(df) > MAX_ROWS:
path = f"{stem}.parquet"
df.to_parquet(path, index=False)
else:
path = f"{stem}.xlsx"
df.to_excel(path, sheet_name="data", index=False)
return pathTwo more restrictions to know:
- Timezone-aware datetimes raise a
ValueError, because Excel has no timezone concept. Convert first withdf["col"].dt.tz_localize(None). - Pandas 2.0 removed writing the old
.xlsformat. Use.xlsx.
Choosing an engine
An engine is the library that actually writes the file. Pandas only wraps it.
| Engine | Install | Strengths |
|---|---|---|
| `openpyxl` | `pip install openpyxl` | Reads and writes `.xlsx`. Can edit existing workbooks. |
| `xlsxwriter` | `pip install xlsxwriter` | Writes new `.xlsx` files only. Rich formatting options. |
Name the engine explicitly so the result does not depend on which libraries happen to be installed.
To append a sheet to a file that already exists, use openpyxl in append mode:
with pd.ExcelWriter(
"report.xlsx", engine="openpyxl", mode="a", if_sheet_exists="replace"
) as writer:
df.to_excel(writer, sheet_name="extra", index=False)Append mode requires that report.xlsx exists, and xlsxwriter does not support it.
Light formatting
Heavy styling belongs in a spreadsheet tool. A few touches are cheap and make a sheet usable: a frozen header, sensible column widths, and number and date formats.
With xlsxwriter, the writer exposes the workbook and each sheet:
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3],
"customer": ["Ana", "Ben", "Cy"],
"amount": [1234.5, 5.5, 19.99],
"ordered_at": pd.to_datetime(["2026-01-05", "2026-01-06", "2026-01-07"]),
})
with pd.ExcelWriter(
"formatted.xlsx",
engine="xlsxwriter",
datetime_format="yyyy-mm-dd",
) as writer:
df.to_excel(writer, sheet_name="orders", index=False, freeze_panes=(1, 0))
workbook = writer.book
sheet = writer.sheets["orders"]
money = workbook.add_format({"num_format": "#,##0.00"})
sheet.set_column("A:A", 10)
sheet.set_column("B:B", 14)
sheet.set_column("C:C", 12, money)
sheet.set_column("D:D", 12)datetime_format sets how date cells display. freeze_panes=(1, 0) keeps the first row visible while scrolling. set_column takes an Excel column range, a width in characters, and an optional format.
With openpyxl, widths are set through the sheet object instead:
with pd.ExcelWriter("formatted_opx.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="orders", index=False)
writer.sheets["orders"].column_dimensions["B"].width = 14Common errors
ModuleNotFoundErrororImportErrornamingopenpyxlorxlsxwritermeans the engine is not installed in the active environment.- Formatting calls such as
set_columnfail withopenpyxl, andcolumn_dimensionsfails withxlsxwriter. The two engines have different sheet objects. - Formatting applied after the
withblock ends has no effect, because the file is already saved. Do all formatting inside the block. - Excel cells hold values, not dtypes. Reading the file back gives you what Excel inferred, so use Parquet when dtypes matter.
Exercise
A DataFrame has 2 million rows and you need to share it with a colleague. Can you save it as one .xlsx sheet? What do you do instead?
Show answer
No. A sheet holds at most 1,048,576 rows including the header. Save it as Parquet or CSV (compressed if large), or split the rows across several sheets or files if the colleague must use Excel.
Exercise
You need the first row frozen and column C shown with thousands separators in a new workbook. Which engine and which calls do you use?
Show answer
Use engine="xlsxwriter". Pass freeze_panes=(1, 0) to to_excel, create a format with workbook.add_format({"num_format": "#,##0.00"}), and apply it with sheet.set_column("C:C", 12, money), all inside the with pd.ExcelWriter(...) block.