Sub topic 8
Excel limits, engines, and light formatting
This chapter assumes you can already write a DataFrame with to_excel and ExcelWriter, and that openpyxl is installed. Here you will learn what Excel cannot hold, which engine writes your file, and how to apply light formatting without leaving pandas.
Hard limits of the .xlsx format
An .xlsx worksheet has fixed size limits. They come from the file format and from Excel itself, not from pandas.
| Limit | Value |
|---|---|
| Rows per sheet | 1,048,576 |
| Columns per sheet | 16,384 |
| Characters per cell | 32,767 |
| Sheet name length | 31 characters |
The row limit includes the header row. A DataFrame with 1,048,576 data rows will not fit, because the header takes one row.
When a sheet is too large, pandas raises a ValueError and the write fails. Your options are:
- Write to CSV or Parquet instead, which have no row limit of this kind.
- Split the data across several sheets or workbooks.
- Aggregate the data first so that the Excel file holds only a summary.
The sheet name rules also cause errors. A name longer than 31 characters is rejected. Names cannot contain any of these characters: [ ] : * ? / \. Names cannot be empty, and cannot start or end with an apostrophe.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
# Raises an error because the sheet name is too long (more than 31 characters)
try:
df.to_excel("bad.xlsx", sheet_name="x" * 40, index=False)
except Exception as exc:
print(type(exc).__name__, exc)The exact exception type and message depend on the engine and version. If you build sheet names from data, such as one sheet per customer, 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 results: Germany"))Two different names can become the same name after cleaning or truncating. Sheet names are also compared without regard to case, so Sales and sales clash. Check for duplicates before writing.
What Excel does to your values
Excel stores each cell with a type, and some pandas values do not map cleanly.
- Timezone-aware datetimes. Excel has no timezone support. Writing a timezone-aware column raises an error. Remove the timezone first with
dt.tz_localize(None), or convert to UTC and then remove it. - Missing values.
NaN,None, andNaTare written as empty cells. Usena_repif you want a visible marker such as"NA". - Infinity.
infis written as an empty cell by default. Useinf_repto choose a different text. - Long numbers. Excel keeps about 15 significant digits. A 19-digit ID stored as an integer loses its last digits when someone opens the file. Convert such IDs to strings before writing.
- Text that looks like a formula. Some engines treat a string starting with
=as a formula. Do not write untrusted text that begins with=,+,-, or@without checking it. A spreadsheet can run it as a formula when a user opens the file.
import pandas as pd
df = pd.DataFrame({
"id": [1234567890123456789, 42],
"ordered_at": pd.to_datetime(["2026-01-05 10:00", "2026-01-06 11:30"]).tz_localize("Europe/Berlin"),
"amount": [19.99, float("nan")],
})
df["id"] = df["id"].astype(str)
df["ordered_at"] = df["ordered_at"].dt.tz_localize(None)
df.to_excel("clean.xlsx", index=False, na_rep="NA")Excel's datetime handling has one more catch. Dates are stored as numbers and shown through a number format. If you read the file back with pandas, a date column normally returns as datetime64. A column that has only a time part may come back as datetime.time objects.
Choosing an engine
An engine is the library that actually writes the file. pandas picks one from the file extension and from what is installed. You can set it with the engine argument.
| Engine | Writes | Notes |
|---|---|---|
| `openpyxl` | `.xlsx`, `.xlsm` | The default for `.xlsx` when installed. Can also edit existing files. |
| `xlsxwriter` | `.xlsx` | Writes new files only. Rich formatting and charts. Fast. |
| `odf` | `.ods` | For OpenDocument spreadsheets. |
The older .xls format is no longer supported for writing in current pandas. Write .xlsx instead.
Install the engines with pip:
# Run these in a terminal, not in Python:
# pip install openpyxl
# pip install xlsxwriterIf no suitable engine is installed, pandas raises an ImportError that names the missing package. Install the package it names.
You can choose an engine for one call, or for a whole session.
import pandas as pd
df = pd.DataFrame({"name": ["Ana", "Ben"], "score": [90, 85]})
df.to_excel("scores_xlsxwriter.xlsx", engine="xlsxwriter", index=False)
with pd.ExcelWriter("scores_openpyxl.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="scores", index=False)Which engine to choose
- Use
openpyxlif you need to append a sheet to an existing workbook, or if you want only one dependency. - Use
xlsxwriterif you create new files and want more formatting control, such as charts, conditional formats, or column formats.
The two engines differ in how you reach the underlying workbook objects, so formatting code written for one does not work on the other.
Appending to an existing workbook
Opening an ExcelWriter in write mode replaces the file. To add a sheet to a workbook that already exists, use append mode with openpyxl.
import pandas as pd
extra = pd.DataFrame({"x": [1, 2, 3]})
with pd.ExcelWriter(
"report.xlsx",
engine="openpyxl",
mode="a",
if_sheet_exists="replace",
) as writer:
extra.to_excel(writer, sheet_name="extra", index=False)The if_sheet_exists argument decides what happens if a sheet of that name is already there:
"error"raises an error. This is the default."replace"deletes the old sheet and writes a new one."new"writes to a new sheet with a changed name."overlay"writes over the existing cells and leaves the rest alone.
Append mode loads the whole workbook into memory and saves it again. Features that openpyxl does not support, such as some charts and images in the original file, can be lost.
Light formatting from pandas
You can do a fair amount without learning a spreadsheet library. to_excel has several arguments for layout.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3],
"customer": ["Ana", "Ben", "Chloe"],
"amount": [19.99, 5.5, 120.0],
"ordered_at": pd.to_datetime(["2026-01-05", "2026-01-06", "2026-01-07"]),
})
df.to_excel(
"orders_formatted.xlsx",
sheet_name="orders",
index=False,
freeze_panes=(1, 0),
float_format="%.2f",
na_rep="",
)freeze_panes=(1, 0)keeps the first row visible while scrolling. The tuple is the number of rows and columns to freeze.float_formatcontrols how floats are written. In Excel it becomes a number format, so the cell value keeps its precision.columnsselects and orders the columns to write.startrowandstartcolmove the table down or right, which leaves room for a title.
Number and date formats
To control how numbers and dates look, set datetime_format and date_format on the ExcelWriter.
import pandas as pd
df = pd.DataFrame({
"ordered_at": pd.to_datetime(["2026-01-05 09:30", "2026-01-06 14:45"]),
"day": pd.to_datetime(["2026-01-05", "2026-01-06"]),
})
with pd.ExcelWriter(
"dates.xlsx",
engine="openpyxl",
datetime_format="yyyy-mm-dd hh:mm",
date_format="yyyy-mm-dd",
) as writer:
df.to_excel(writer, index=False)These strings use Excel's format codes, not Python strftime codes. yyyy-mm-dd works here, but %Y-%m-%d does not.
Column widths and styles
pandas does not set column widths. You reach into the engine's worksheet object for that. This example uses openpyxl.
import pandas as pd
from openpyxl.styles import Font
df = pd.DataFrame({
"customer": ["Ana", "Ben", "Chloe"],
"amount": [19.99, 5.5, 120.0],
})
with pd.ExcelWriter("styled.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="orders", index=False)
ws = writer.sheets["orders"]
for cell in ws[1]:
cell.font = Font(bold=True)
for column_cells in ws.columns:
longest = max(len(str(c.value)) if c.value is not None else 0 for c in column_cells)
ws.column_dimensions[column_cells[0].column_letter].width = longest + 2Here writer.sheets maps sheet names to openpyxl worksheet objects. The loop makes the header bold and sets each column's width from its longest value.
With xlsxwriter the same job uses different calls.
import pandas as pd
df = pd.DataFrame({
"customer": ["Ana", "Ben", "Chloe"],
"amount": [19.99, 5.5, 120.0],
})
with pd.ExcelWriter("styled_xw.xlsx", engine="xlsxwriter") as writer:
df.to_excel(writer, sheet_name="orders", index=False)
workbook = writer.book
ws = writer.sheets["orders"]
money = workbook.add_format({"num_format": "#,##0.00"})
ws.set_column("A:A", 14)
ws.set_column("B:B", 12, money)
ws.autofilter(0, 0, len(df), len(df.columns) - 1)set_column sets a width and a default format for a range of columns. autofilter adds filter buttons to the header row.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ImportError` naming `openpyxl` or `xlsxwriter` | The engine package is not installed | `pip install` the named package |
| `ValueError` about timezones | A column has timezone-aware datetimes | Remove the timezone before writing |
| Error about the number of rows | More than 1,048,576 rows | Use CSV or Parquet, or split the data |
| Existing sheets vanish | The writer was opened in write mode | Use `mode="a"` with `openpyxl` |
| `ValueError` about the sheet existing | Append mode with the default `if_sheet_exists` | Set `if_sheet_exists` explicitly |
| Dates show as numbers | The cell has no date format | Set `datetime_format` or `date_format` |
| IDs end in zeros | Excel keeps about 15 digits | Write IDs as strings |
When to stop formatting in pandas
Light formatting covers frozen headers, number formats, widths, and filters. If you find yourself writing many cell-by-cell style rules, charts, or conditional formatting, consider whether Excel is the right target. A template workbook filled by a dedicated script, or a plain CSV that people import themselves, is easier to maintain. Keep the spreadsheet code short and put it in one function so you can change it in one place.
Exercise
You need to write a DataFrame with 2 million rows so that a colleague can open it in Excel. What are two reasonable approaches, and why can you not write it to one sheet?
Show answer
One sheet holds at most 1,048,576 rows, including the header, so 2 million rows do not fit. You can split the data across several sheets or workbooks, or aggregate it first so the Excel file holds a summary. Writing the full data to CSV or Parquet is also an option, because those formats have no such row limit.
Exercise
A to_excel call fails with an error about timezones. What do you change in the DataFrame, and what is the cause?
Show answer
Excel cannot store timezone information. Remove it from the datetime column before writing, for example with df["col"].dt.tz_localize(None). Convert to UTC first if you want all values in the same zone.
Exercise
You want to add a new sheet called "extra" to an existing report.xlsx without losing its other sheets. Which ExcelWriter arguments do you use, and which engine?
Show answer
Use engine="openpyxl" with mode="a", and set ifsheetexists to a value such as "replace" or "new" in case a sheet named "extra" already exists. The xlsxwriter engine cannot append to existing files.