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.
Source: pandas user guide: Excel files.
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 |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.
Source: pandas.read_excel.
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"),indexandindex_label,columns,header. -
startrowandstartcolplace 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_repwrites a string for missing values andinf_repone for infinities, which Excel cannot store. -
float_formatsuch as"%.2f"rounds the stored number, not just its display. -
freeze_panes=(1, 0)freezes the first row, andautofilter=Trueadds filter buttons over the table. Both exist in pandas 3.1 and were checked by reading the file back with openpyxl: the frozen cell wasA2and the filter rangeA1:D5. -
merge_cells=True(default) merges the cells of a MultiIndex header or index into spans. Set it toFalsefor a flat layout that other programs can read. -
engine_kwargspasses options to the writer engine.
Source: pandas.DataFrame.to_excel.
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
ValueErrorrather than dropping the zone; remove it first withser.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.
Source: pandas.DataFrame.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)
Source: pandas user guide: writing Excel files and Styler.to_excel.
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.
Source: pandas.ExcelWriter.
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"]) orNonereturns a dictionary of DataFrames keyed by the requested names or positions (Nonemeans 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
Source: pandas.read_excel.
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')]
Source: pandas.read_excel.
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:
-
Text that looks like a number is converted. A cell holding the text
01234came back as the integer1234. Declaredtype=str(ordtype={"zip": str}) to keep text exactly as stored. -
A column mixing dates and text stays as it is. Use
parse_datesorpd.to_datetime(errors="coerce")after reading. -
Whole-number floats become integers, so a column of
10.0and7.0may come back asint64.
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']
Source: pandas.read_excel.
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]
Source: pandas.ExcelWriter.
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.
Source: openpyxl documentation.
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)
Source: pandas.read_excel.
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)
Source: pandas.DataFrame.to_excel.
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): raiseValueError. -
"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 withstartroworstartcol.
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.
Source: pandas.ExcelWriter.
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=strfor identifier columns. -
Write with
index=Falseunless the index is data, and usestartrowto put a title above a table. -
Read one sheet at a time from large workbooks through
ExcelFile, and useusecolsto avoid parsing unused columns. -
After reading, check
df.dtypesanddf.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
usecolsandnrowswhile exploring.
Where older books and tutorials are outdated
| Older statement | pandas 3.1 reality | Changed |
|---|---|---|
|
|
|
|
The header is plain; style it yourself. |
3.0 |
|
|
Removed in 2.0 |
|
Removed; use |
Removed in 2.0 |
|
Deprecated; use |
3.1 |
|
Removed; use |
Long gone |
See What’s New in 3.x and Migrating for the rest.