Sub topic 11
Excel engines and file formats
This chapter assumes you can run Python scripts or notebooks, install packages with pip, and know what a DataFrame is. You have already used read_excel on a workbook. Here you learn what happens underneath: pandas does not read Excel files itself. It hands the work to a separate library called an engine. Knowing which engine handles which format explains most "missing dependency" and "file format cannot be determined" errors.
What an engine is
An engine is a third-party Python package that knows how to parse one file format. read_excel picks one, asks it to open the file, and converts the cell data into a DataFrame. The engines are optional dependencies, so installing pandas alone does not install them.
| Format | Extension | Default engine | Install |
|---|---|---|---|
| Excel 2007 and later (Open XML) | `.xlsx`, `.xlsm` | `openpyxl` | `pip install openpyxl` |
| Excel 97 to 2003 (BIFF) | `.xls` | `xlrd` | `pip install xlrd` |
| Excel binary workbook | `.xlsb` | `pyxlsb` | `pip install pyxlsb` |
| OpenDocument spreadsheet | `.ods` | `odf` | `pip install odfpy` |
| Calamine (fast Rust reader) | `.xlsx`, `.xls`, `.xlsb`, `.ods` | none, opt in | `pip install python-calamine` |
Calamine is only used when you ask for it with engine="calamine". It needs pandas 2.2 or later.
How pandas picks an engine
When engine is None, pandas looks at the file. It checks the extension and, for file-like objects, the first bytes of the content to tell the formats apart. The rules are:
.xlsx,.xlsmand other Open XML files useopenpyxl..xlsfiles usexlrd..xlsbfiles usepyxlsb..odsfiles useodf.
You can override this with the engine argument. This is useful for speed (Calamine) or when a file has the wrong extension.
import pandas as pd
df = pd.read_excel("report.xlsx", engine="openpyxl")
print(df.shape)Installing the right engine
If the needed library is missing, pandas raises an ImportError that names the package. For example, reading a .xlsx file without openpyxl gives a message like Missing optional dependency 'openpyxl'. The fix is to install the package in the same environment that runs your code.
import importlib.util
for package in ["openpyxl", "xlrd", "pyxlsb", "odf", "python_calamine"]:
found = importlib.util.find_spec(package) is not None
print(f"{package:16} {'installed' if found else 'missing'}")Note that the import names differ from the pip names in two places: odfpy is imported as odf, and python-calamine is imported as python_calamine.
You can also install engines through pandas extras, which pins compatible versions:
# Run in a shell, not in Python:
# pip install "pandas[excel]"The excel extra installs openpyxl, xlrd, pyxlsb and python-calamine, plus odfpy-based support in current releases. If you are not sure, check with pip list.
Format differences that affect what you get
Engines differ in more than speed. Each format has limits that show up in your data.
.xlsx and .xlsm
This is the modern default. openpyxl reads cell values, not formulas. If a cell contains =A1+B1, pandas returns the last value Excel calculated and stored in the file. If the file was written by a program that never calculated formulas (for example, some libraries that generate workbooks), the cached value is missing and you get NaN. Opening and saving the file once in Excel stores the results.
.xlsm files contain macros. pandas reads the data and ignores the macros.
.xls
The old format needs xlrd. Since version 2.0, xlrd reads only .xls and no longer reads .xlsx. Older tutorials that suggest xlrd for every Excel file are out of date. A .xls file can also hold at most 65,536 rows, while .xlsx holds just over one million.
.xlsb
This is a compressed binary format. It can be faster to open than .xlsx for large workbooks, but pyxlsb returns dates as numbers, so you need to convert them yourself.
import pandas as pd
df = pd.read_excel("data.xlsb", engine="pyxlsb")
df["date"] = pd.to_datetime(df["date"], unit="D", origin="1899-12-30")The origin 1899-12-30 is how Excel's day-number system lines up with the calendar once you account for its historical leap-year quirk.
.ods
OpenDocument files from LibreOffice or Google Sheets exports are read with odf. Behavior matches .xlsx for plain values.
Files with the wrong extension
Files are often not what their extension claims. A ".xls" file exported by a web application may actually be an HTML table, and a ".xlsx" may be a CSV renamed. In that case you see errors such as Excel file format cannot be determined, you must specify an engine manually or Unsupported format, or corrupt file: Expected BOF record.
Look at the first bytes of the file to see what it really is:
from pathlib import Path
def sniff(path):
head = Path(path).read_bytes()[:8]
if head.startswith(b"PK"):
return "zip container (xlsx, xlsm, xlsb or ods)"
if head.startswith(b"\xd0\xcf\x11\xe0"):
return "legacy OLE2 (xls)"
if head.lstrip().lower().startswith((b"<html", b"<!doc", b"<table")):
return "HTML disguised as a spreadsheet"
return "probably plain text such as CSV"
print(sniff("report.xls"))Then use the matching reader: read_excel for the first two, pd.read_html for HTML, and pd.read_csv for text.
Choosing an engine: trade-offs
| Concern | openpyxl | calamine | xlrd | pyxlsb |
|---|---|---|---|---|
| Formats read | xlsx, xlsm | xlsx, xls, xlsb, ods | xls only | xlsb only |
| Speed on large files | Slow | Fast | Moderate | Moderate |
| Can also write | Yes | No | No | No |
| Pure Python | Yes | No (compiled) | Yes | Yes |
Choose openpyxl when you also write files or want the standard path. Choose calamine when load time matters or you need one engine for several formats. Choose xlrd only for legacy .xls files.
Engines for writing
Writing has a parallel set of engines. to_excel uses openpyxl by default for .xlsx, and xlsxwriter is a common alternative with richer formatting options.
import pandas as pd
from io import BytesIO
buffer = BytesIO()
pd.DataFrame({"a": [1, 2]}).to_excel(buffer, engine="openpyxl", index=False)
buffer.seek(0)
print(pd.read_excel(buffer, engine="openpyxl"))pandas cannot write .xls in current versions, because the xlwt writer was removed. Save as .xlsx instead.
Reading from buffers and URLs
read_excel accepts paths, URLs and file-like objects. With a file-like object, pandas has no extension to look at, so it inspects the content. If detection fails, pass engine explicitly.
import pandas as pd
from io import BytesIO
buffer = BytesIO()
pd.DataFrame({"x": [10, 20]}).to_excel(buffer, index=False)
buffer.seek(0)
df = pd.read_excel(buffer, engine="openpyxl")
print(df)Remember to call seek(0) after writing to a buffer. Without it, the read position is at the end and the engine sees an empty file.
Quick troubleshooting guide
| Symptom | Likely cause | Fix |
|---|---|---|
| `Missing optional dependency 'openpyxl'` | Engine not installed | `python -m pip install openpyxl` |
| `Excel file format cannot be determined` | File-like input or odd file | Pass `engine=` |
| `Expected BOF record` | File is not a real `.xls` | Sniff the bytes, then use `read_html` or `read_csv` |
| `NaN` where formulas should be | Formulas never calculated | Open and re-save in Excel |
| Dates are large numbers | `.xlsb` reading | Convert with `pd.to_datetime(..., unit="D", origin="1899-12-30")` |
Exercise
A colleague sends sales.xls and pd.read_excel("sales.xls") fails with "Expected BOF record". You already have xlrd installed. What is the most likely cause, and what is your first diagnostic step?
Show answer
The file is probably not a genuine legacy Excel file. Web exports often save HTML or CSV text under an .xls name. Read the first bytes of the file (for example with Path("sales.xls").read_bytes()[:8]). If it starts with <html or <table, use pd.read_html. If it is plain text, use pd.read_csv. Only a header of D0 CF 11 E0 means a real .xls.
Exercise
You must load a 400,000-row .xlsx file repeatedly, and load time is the bottleneck. Which engine argument would you try, what must you install, and which pandas version do you need?
Show answer
Use pd.read_excel(path, engine="calamine"). Install it with pip install python-calamine. It needs pandas 2.2 or later. Calamine is a compiled reader and is usually much faster than openpyxl on large files, but it cannot write files.