Excel

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Spreadsheets are how a great deal of business data is stored and exchanged, and pandas can read and write them (.xlsx, .xlsm, .xlsb, .xls and OpenDocument .ods) through read_excel, DataFrame.to_excel and the ExcelFile and ExcelWriter classes. The format hides more traps than CSV: workbooks hold several sheets, cells have types and formatting, formulas have cached results, and every reader and writer is a separate third-party package with its own capabilities.

This page targets pandas 3.1 on Python 3.13 or 3.14 and was checked in October 2026. Every example was run with Python 3.13, pandas 3.1.0, openpyxl 3.1.5, XlsxWriter 3.3.1, python-calamine 0.9.0 and odfpy 1.4.1; the printed output is the real output. The related formats are in CSV and Text Files, JSON, HTML and XML and Parquet, Feather, ORC and Iceberg. For deciding whether a spreadsheet is the right exchange format at all, see Data Acquisition and Formats.

Install the engines

pandas does not read or write Excel by itself; it delegates to an engine, an optional package. Install the ones you need, or the excel extra (pip install "pandas[excel]"), which pulls in the common set.

Engine (package) Reads Writes

openpyxl

.xlsx, .xlsm

.xlsx, .xlsm

xlsxwriter

.xlsx (fast, rich formatting, write-only)

calamine (python-calamine)

.xlsx, .xlsm, .xlsb, .xls, .ods

pyxlsb

.xlsb

xlrd

.xls only

odf (odfpy)

.ods

.ods

Practical consequences: there is no way to write the old binary .xls format any more (convert to .xlsx); xlrd reads only .xls and not .xlsx; and calamine is a very fast Rust-based reader that returns values only (no formatting) and cannot write.

The default reader is changing

With no engine argument pandas currently reads .xlsx with openpyxl. pandas 3.1 warns that this default will move to calamine in a future version:

Pandas4Warning: The default engine for reading 'xlsx' files will change from 'openpyxl' to 'calamine' in a future
version. Pass engine='openpyxl' (or set the 'io.excel.xlsx.reader' option) to keep the current engine and silence
this warning.

Pass engine= explicitly in new code, or set the option once for the whole program:

import pandas as pd

pd.set_option("io.excel.xlsx.reader", "openpyxl")
print(pd.get_option("io.excel.xlsx.writer"), pd.get_option("io.excel.ods.writer"))

The examples below pass engine="openpyxl" or engine="calamine" for that reason. The two readers are separate implementations and can differ in details such as the dtypes they infer, so test your files with whichever engine you choose.

Writing a workbook

to_excel writes one DataFrame to one sheet. To write several sheets, open an ExcelWriter as a context manager so the file is saved and closed at the end.

import numpy as np
import pandas as pd

sales = pd.DataFrame({
    "region": ["N", "S", "N", "E"],
    "month": pd.to_datetime(["2024-01-01", "2024-01-01", "2024-02-01", "2024-02-01"]),
    "units": [10, 7, 12, None],
    "price": [2.5, 3.0, 2.5, 4.0],
})
targets = pd.DataFrame({"region": ["N", "S", "E"], "target": [20, 15, 12]})

with pd.ExcelWriter("report.xlsx", engine="openpyxl") as xw:
    sales.to_excel(xw, sheet_name="sales", index=False, freeze_panes=(1, 0), autofilter=True)
    targets.to_excel(xw, sheet_name="targets", index=False)
    sales.groupby("region")["units"].sum().to_excel(xw, sheet_name="summary", startrow=2, startcol=1)

with pd.ExcelFile("report.xlsx", engine="openpyxl") as xf:
    print(xf.sheet_names, xf.engine)

Output:

['sales', 'targets', 'summary'] openpyxl

The useful to_excel parameters:

  • sheet_name (default "Sheet1"), index and index_label, columns, header.

  • startrow and startcol place the table inside the sheet (zero-based), which is how you build a sheet with a title above the data or several tables side by side.

  • na_rep writes a string for missing values and inf_rep one for infinities, which Excel cannot store.

  • float_format such as "%.2f" rounds the stored number, not just its display.

  • freeze_panes=(1, 0) freezes the first row, and autofilter=True adds filter buttons over the table. Both exist in pandas 3.1 and were checked by reading the file back with openpyxl: the frozen cell was A2 and the filter range A1:D5.

  • merge_cells=True (default) merges the cells of a MultiIndex header or index into spans. Set it to False for a flat layout that other programs can read.

  • engine_kwargs passes options to the writer engine.

Limits and refusals

  • A worksheet holds at most 1,048,576 rows and 16,384 columns; writing more is an error. Split the data, or use a format built for it.

  • Excel has no time-zone-aware datetimes. pandas raises a ValueError rather than dropping the zone; remove it first with ser.dt.tz_localize(None) or convert to local wall-clock time.

  • Python objects other than numbers, strings, booleans, dates and times cannot be written; convert them to text.

try:
    pd.DataFrame({"t": pd.to_datetime(["2024-01-01"]).tz_localize("UTC")}).to_excel("tz.xlsx", engine="openpyxl")
except ValueError as exc:
    print(type(exc).__name__, exc)

Output:

ValueError Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel.

Styling

pandas 3.0 stopped giving the header row and index of to_excel output a built-in style. A header written in pandas 3.1 is plain; earlier versions wrote it bold with borders. Reading the file back with openpyxl confirmed font.bold is False. If you want a bold header, style it yourself with the engine’s API or with a Styler.

With xlsxwriter you get the workbook and worksheet objects from the writer and can use the full XlsxWriter API:

with pd.ExcelWriter("styled.xlsx", engine="xlsxwriter") as xw:
    sales.to_excel(xw, sheet_name="s", index=False)
    book, sheet = xw.book, xw.sheets["s"]
    header = book.add_format({"bold": True, "bg_color": "#DBEAFE"})
    for col, name in enumerate(sales.columns):
        sheet.write(0, col, name, header)
    sheet.set_column("A:A", 12)
    sheet.set_column("B:B", 14, book.add_format({"num_format": "yyyy-mm-dd"}))

A Styler (see Table Styling) can export its colours with Styler.to_excel. It needs Jinja2, and only the style properties that map to Excel are exported:

styler = sales.style.background_gradient(subset=["units"], cmap="Blues")
styler.to_excel("styled2.xlsx", engine="openpyxl", index=False)

Date and datetime formats

ExcelWriter accepts date_format and datetime_format (Excel number-format strings, for example "yyyy-mm-dd hh:mm"). The pandas documentation demonstrates them with xlsxwriter. With pandas 3.1, openpyxl 3.1.5 and XlsxWriter 3.3.1, the xlsxwriter engine stores the requested formats, while the openpyxl engine stores its own defaults (YYYY-MM-DD HH:MM:SS for datetimes and YYYY-MM-DD for dates) and ignores the arguments. Reading the cell number formats back with openpyxl shows the difference:

import datetime as dt
import openpyxl

frame = pd.DataFrame({"t": [pd.Timestamp("2024-01-05 13:45")], "d": [dt.date(2024, 1, 5)]})
for engine in ("openpyxl", "xlsxwriter"):
    with pd.ExcelWriter(f"fmt_{engine}.xlsx", engine=engine,
                        datetime_format="yyyy-mm-dd hh:mm", date_format="dd/mm/yyyy") as xw:
        frame.to_excel(xw, index=False)
    sheet = openpyxl.load_workbook(f"fmt_{engine}.xlsx").active
    print(engine, sheet["A2"].number_format, sheet["B2"].number_format)

Output:

openpyxl YYYY-MM-DD HH:MM:SS YYYY-MM-DD
xlsxwriter yyyy-mm-dd hh:mm dd/mm/yyyy

Use xlsxwriter when exact cell formats matter.

Reading a workbook

read_excel returns a DataFrame for one sheet. Its parameters match those of read_csv where they overlap (header, names, index_col, usecols, dtype, converters, true_values, false_values, skiprows, nrows, na_values, keep_default_na, na_filter, parse_dates, date_format, thousands, decimal, comment, skipfooter, dtype_backend; see CSV and Text Files), plus sheet_name, a different usecols, and engine_kwargs.

Choosing sheets

  • sheet_name=0 (default) reads the first sheet; an integer is a zero-based position and a string is a sheet name.

  • A list ([0, "targets"]) or None returns a dictionary of DataFrames keyed by the requested names or positions (None means every sheet, keyed by sheet name).

print(pd.read_excel("report.xlsx", engine="openpyxl").dtypes.astype(str).tolist())
print(pd.read_excel("report.xlsx", sheet_name="targets", engine="openpyxl"))

every = pd.read_excel("report.xlsx", sheet_name=None, engine="openpyxl")
print(list(every), [frame.shape for frame in every.values()])
print(list(pd.read_excel("report.xlsx", sheet_name=[0, "targets"], engine="openpyxl")))

try:
    pd.read_excel("report.xlsx", sheet_name="nope", engine="openpyxl")
except ValueError as exc:
    print(type(exc).__name__, exc)

Output:

['str', 'datetime64[us]', 'float64', 'float64']
  region  target
0      N      20
1      S      15
2      E      12
['sales', 'targets', 'summary'] [(4, 4), (3, 2), (5, 3)]
[0, 'targets']
ValueError Worksheet named 'nope' not found

Source: pandas.ExcelFile.

When you need several sheets from one big workbook, open it once with pd.ExcelFile so the file is parsed once, then call pd.read_excel(xf, sheet_name=...) for each sheet. The older ExcelFile.parse method is deprecated in pandas 3.1 (Pandas4Warning: ExcelFile.parse is deprecated. Use pd.read_excel instead.).

with pd.ExcelFile("report.xlsx", engine="openpyxl") as xf:
    print(xf.sheet_names)
    print(pd.read_excel(xf, sheet_name="targets").shape)

Output:

['sales', 'targets', 'summary']
(3, 2)

Source: pandas.ExcelFile.

Choosing rows and columns

usecols accepts a string of Excel column letters and ranges ("A,C:D"), a list of names, a list of positions or a function. skiprows, nrows and skipfooter trim rows, which is how you read a table that sits below a title.

print(pd.read_excel("report.xlsx", sheet_name="sales", usecols="A,C:D", nrows=2, engine="openpyxl"))
print(pd.read_excel("report.xlsx", sheet_name="summary", skiprows=2, usecols="B:C", index_col=0, engine="openpyxl"))
print(pd.read_excel("report.xlsx", sheet_name="sales", header=None, nrows=2, engine="openpyxl"))

Output:

  region  units  price
0      N     10    2.5
1      S      7    3.0
        units
region
E           0
N          22
S           7
        0                    1      2      3
0  region                month  units  price
1       N  2024-01-01 00:00:00     10    2.5

The second result shows a subtlety of the round trip: the region E has a missing unit count, and groupby(...).sum() turned it into 0, so it came back as 0, not blank. The last result shows that with header=None the date column is returned as Python datetime objects inside an object column, because the column now mixes a text header cell with dates.

A MultiIndex header written with merge_cells=True is stored as merged cells, and reading it back needs both header and index_col:

mi = pd.DataFrame(np.arange(4).reshape(2, 2), columns=pd.MultiIndex.from_product([["a"], ["x", "y"]]))
mi.to_excel("mi.xlsx", engine="openpyxl")
print(pd.read_excel("mi.xlsx", header=[0, 1], index_col=0, engine="openpyxl").columns.tolist())

Output:

[('a', 'x'), ('a', 'y')]

Types

Excel stores each cell with a type (number, text, boolean, date, error), and read_excel converts numbers to int64 when every value is a whole number, to float64 otherwise, dates to datetime64, and text to str. Three pitfalls come up constantly:

  1. Text that looks like a number is converted. A cell holding the text 01234 came back as the integer 1234. Declare dtype=str (or dtype={"zip": str}) to keep text exactly as stored.

  2. A column mixing dates and text stays as it is. Use parse_dates or pd.to_datetime(errors="coerce") after reading.

  3. Whole-number floats become integers, so a column of 10.0 and 7.0 may come back as int64.

import openpyxl

wb = openpyxl.Workbook()
ws = wb.active
ws.append(["zip"])
ws.append(["01234"])
ws.append([1234])
wb.save("z.xlsx")
print(pd.read_excel("z.xlsx", engine="openpyxl")["zip"].tolist())
print(pd.read_excel("z.xlsx", engine="openpyxl", dtype=str)["zip"].tolist())

mixed = pd.DataFrame({"code": [1, 2, 3], "d": ["2024-01-05", "x", "2024-02-01"]})
mixed.to_excel("m.xlsx", index=False, engine="openpyxl")
print(pd.read_excel("m.xlsx", engine="openpyxl", parse_dates=["d"]).dtypes.astype(str).tolist())

Output:

[1234, 1234]
['01234', '1234']
['int64', 'str']

Missing cells become NaN. Strings that the writer put in for missing values (na_rep="missing") are ordinary text on the way back unless you list them in na_values, and the default missing-value strings (NA, n/a, null, the empty string and the rest of the list in the CSV page) apply in read_excel as well.

with pd.ExcelWriter("na.xlsx", engine="openpyxl") as xw:
    pd.DataFrame({"a": [1, None], "b": ["x", None]}).to_excel(xw, index=False, na_rep="missing")
print(pd.read_excel("na.xlsx", engine="openpyxl").values.tolist())
print(pd.read_excel("na.xlsx", engine="openpyxl", na_values=["missing"]).isna().sum().tolist())

Output:

[[1, 'x'], ['missing', 'missing']]
[1, 1]

Formulas and cached values

A cell with a formula stores both the formula and the value Excel last calculated. read_excel returns the cached value. A workbook that was produced by a program such as openpyxl and never opened in Excel has no cached value, so the cell is read as empty:

wb = openpyxl.Workbook()
ws = wb.active
ws["A1"] = 2
ws["A2"] = 3
ws["A3"] = "=A1+A2"
wb.save("f.xlsx")
print(pd.read_excel("f.xlsx", header=None, engine="openpyxl").iloc[:, 0].tolist())
print(pd.read_excel("f.xlsx", header=None, engine="calamine").iloc[:, 0].tolist())

Output:

[2, 3]
[2, 3]

pandas never returns the formula text. To inspect formulas, open the workbook with openpyxl.load_workbook(path) (without data_only=True) and read the cell values, which are then the formula strings. To get fresh results for a program-generated workbook, open and save it once in a spreadsheet application, or compute the values in pandas before writing.

The calamine reader and other engines

engine="calamine" is the fastest reader and the only one that reads .xlsx, .xlsb, .xls and .ods with a single package:

print(pd.read_excel("report.xlsx", sheet_name="sales", engine="calamine").dtypes.astype(str).tolist())

sales.to_excel("o.ods", engine="odf", index=False)
print(pd.read_excel("o.ods", engine="odf").shape)

Output:

['str', 'datetime64[us]', 'float64', 'float64']
(4, 4)

engine_kwargs forwards options to the reader, for example engine_kwargs={"read_only": True} for openpyxl, which streams a very large sheet instead of loading it whole.

Files, URLs and buffers

The first argument can be a path, a URL, a file-like object or an already created ExcelFile. In memory, write to io.BytesIO:

import io

buf = io.BytesIO()
sales.to_excel(buf, index=False, engine="openpyxl")
buf.seek(0)
print(pd.read_excel(buf, engine="openpyxl").shape)

Output:

(4, 4)

Remote paths use storage_options, as in the CSV readers.

Appending and replacing sheets

ExcelWriter(path, mode="a") opens an existing workbook for adding sheets. Append mode works with openpyxl and odf, not with xlsxwriter. if_sheet_exists says what happens when the sheet name is already present:

  • "error" (default): raise ValueError.

  • "new": write to a new sheet with a unique name.

  • "replace": delete the sheet and write the new one.

  • "overlay": write into the existing sheet, leaving the other cells untouched; combine with startrow or startcol.

with pd.ExcelWriter("report.xlsx", mode="a", engine="openpyxl", if_sheet_exists="replace") as xw:
    targets.assign(target=targets["target"] * 2).to_excel(xw, sheet_name="targets", index=False)
print(pd.read_excel("report.xlsx", sheet_name="targets", engine="openpyxl")["target"].tolist())

try:
    with pd.ExcelWriter("report.xlsx", mode="a", engine="openpyxl") as xw:
        targets.to_excel(xw, sheet_name="targets")
except ValueError as exc:
    print(type(exc).__name__, exc)

with pd.ExcelWriter("report.xlsx", mode="a", engine="openpyxl", if_sheet_exists="overlay") as xw:
    pd.DataFrame({"note": ["done"]}).to_excel(xw, sheet_name="targets", index=False, startcol=5)
print(pd.read_excel("report.xlsx", sheet_name="targets", engine="openpyxl").columns.tolist())

Output:

[40, 30, 24]
ValueError Sheet 'targets' already exists and if_sheet_exists is set to 'error'.
['region', 'target', 'Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4', 'note']

Appending reloads the workbook through the engine, so features it does not preserve (some charts, pivot tables, images or macros) can be lost. Keep a backup of workbooks that people have decorated by hand.

Practical advice

  • Prefer CSV or Parquet for data exchange between programs, and Excel for deliverables people will open. Excel silently reformats data on load (dates, long numbers, leading zeros, gene names such as SEPT2); reading a spreadsheet that humans edited needs validation.

  • Always pass engine= and pin the engine packages in your environment.

  • Declare dtype=str for identifier columns.

  • Write with index=False unless the index is data, and use startrow to put a title above a table.

  • Read one sheet at a time from large workbooks through ExcelFile, and use usecols to avoid parsing unused columns.

  • After reading, check df.dtypes and df.shape, and compare the row count with what the spreadsheet shows.

  • Treat workbooks from unknown sources as untrusted input: they can be malformed or very large, so read them in a restricted environment and with usecols and nrows while exploring.

Where older books and tutorials are outdated

Older statement pandas 3.1 reality Changed

pd.read_excel(path) uses xlrd for every Excel file.

xlrd reads only .xls; .xlsx uses openpyxl by default, with a warned move to calamine.

xlrd 2.0 (2020); warning in 3.1

DataFrame.to_excel writes a bold, bordered header.

The header is plain; style it yourself.

3.0

ExcelWriter(path, engine="xlwt") writes .xls.

xlwt support was removed; write .xlsx or .ods.

Removed in 2.0

writer.save() saves the file.

Removed; use with ExcelWriter(...) or writer.close().

Removed in 2.0

ExcelFile.parse(sheet) reads a sheet.

Deprecated; use pd.read_excel(xf, sheet_name=sheet).

3.1

read_excel(..., sheetname=...), skip_footer=, parse_cols=

Removed; use sheet_name, skipfooter, usecols.

Long gone