Sub topic 8
Reading an Excel file
Prerequisites and scope
This chapter assumes you can run Python scripts or notebooks, install packages with pip, and know what a DataFrame is. It also assumes you have used read_csv from the earlier chapters. Here you learn what pandas.read_excel does, how it differs from read_csv, and which errors you will meet first. Choosing sheets, skipping rows, picking column ranges and Excel engines each get their own chapter, so they only appear briefly here.
What read_excel does
An .xlsx file is not text. It is a zip archive of XML files that describe sheets, cells, styles and shared strings. read_excel hands the file to a parser library (an engine), which returns the cell values for one sheet. pandas then turns those rows into a DataFrame using the same header, index and dtype logic that read_csv uses.
Three consequences follow from this design.
- Excel stores a type for each cell (number, text, boolean, date). pandas receives these types from the file. It does not guess them from text the way
read_csvdoes. - There is no
sep,encodingoron_bad_lines. A workbook has a fixed cell grid, so those problems do not exist. - The parser needs an extra package, which pandas does not install for you.
Installing the parser
For .xlsx files, pandas uses openpyxl. Install it once in your environment:
pip install pandas openpyxlWithout it, read_excel raises ImportError: Missing optional dependency 'openpyxl'. The fix is the install command above. Older .xls files need a different package, covered in the chapter on engines.
Your first read_excel call
The examples build a small workbook in memory so you can run them without a file on disk. In your own code you would pass a path such as "sales.xlsx".
import pandas as pd
from io import BytesIO
orders = pd.DataFrame({
"order_id": [101, 102, 103],
"customer": ["Ana", "Ben", None],
"amount": [19.5, 42.0, 7.25],
"ordered": pd.to_datetime(["2024-01-05", "2024-02-11", "2024-02-12"]),
})
buffer = BytesIO()
with pd.ExcelWriter(buffer, engine="openpyxl") as writer:
orders.to_excel(writer, sheet_name="Orders", index=False)
buffer.seek(0)
df = pd.read_excel(buffer)
print(df)
df.info()With default settings, read_excel does the following:
- It reads the first sheet (
sheet_name=0). - It uses the first row as the header (
header=0). - It creates a default
RangeIndex. - It converts date cells to
datetime64without anyparse_datesargument. - It turns empty cells into
NaN.
In the output, order_id is int64, amount is float64, ordered is a datetime type, and customer is object with one missing value. This is the same inspection step you used for CSV files. Run info() and head() after every load.
Accepted inputs
The first argument is flexible, as in read_csv:
- A local path string or
pathlib.Path. - A URL, such as
https://example.com/report.xlsx. - A binary file-like object, such as
BytesIOor a file opened withopen(path, "rb"). - An existing
pd.ExcelFile, which is useful when you read several sheets from one workbook. The next chapters cover it.
A text-mode file object does not work, because a workbook is binary.
Options you already know
Many read_csv arguments carry over with the same meaning. This table lists the most useful ones.
| Argument | Effect in read_excel | Notes |
|---|---|---|
| `header` | Row number used for column names | `header=None` gives integer column labels |
| `names` | Replace or supply column names | Combine with `header=None` when no header row exists |
| `index_col` | Column to use as the index | Accepts a position or a name |
| `usecols` | Columns to keep | Also accepts Excel letters such as `"A:C"` |
| `dtype` | Per-column or global types | Overrides the types from the file |
| `na_values` | Extra strings treated as missing | Added to the default markers |
| `nrows` | Number of rows to read | Applies after the header |
| `parse_dates` | Columns to parse as dates | Needed only for dates stored as text |
Here is a call that combines several of them.
import pandas as pd
from io import BytesIO
raw = pd.DataFrame({
"order_id": [101, 102, 103],
"customer": ["Ana", "unknown", "Cy"],
"amount": [19.5, 42.0, 7.25],
"internal_note": ["a", "b", "c"],
})
buffer = BytesIO()
with pd.ExcelWriter(buffer, engine="openpyxl") as writer:
raw.to_excel(writer, sheet_name="Orders", index=False)
buffer.seek(0)
df = pd.read_excel(
buffer,
sheet_name="Orders",
usecols=["order_id", "customer", "amount"],
index_col="order_id",
dtype={"customer": "string"},
na_values=["unknown"],
)
print(df)
print(df.dtypes)The internal_note column is dropped, order_id becomes the index, customer is stored as the nullable string type, and the text unknown becomes a missing value.
How types differ from CSV
Because the file carries cell types, read_excel avoids some read_csv problems and creates others.
Dates arrive as dates
A cell formatted as a date is returned as a datetime64 column. You do not need date_format. The catch is that a date typed as text, such as '05/01/2024 or a cell formatted as Text, stays a string. In that case use parse_dates or pd.to_datetime on the column.
Integers with blanks become floats
NumPy integers cannot hold NaN. A numeric column with an empty cell is therefore read as float64, even if every filled cell looks like a whole number. Request a nullable integer type to keep the integers:
import pandas as pd
from io import BytesIO
buffer = BytesIO()
with pd.ExcelWriter(buffer, engine="openpyxl") as writer:
pd.DataFrame({"qty": [1, None, 3]}).to_excel(writer, index=False)
buffer.seek(0)
print(pd.read_excel(buffer)["qty"].dtype)
buffer.seek(0)
print(pd.read_excel(buffer, dtype={"qty": "Int64"})["qty"].dtype)The first line prints float64 and the second prints Int64. The buffer.seek(0) calls matter. Each read consumes the buffer, so you must rewind it before the next one.
Mixed columns stay as object
If a column holds numbers in some cells and text in others, pandas keeps the original Python values in an object column. It does not coerce them. Arithmetic on that column then fails or misbehaves. Find the offending cells with df["col"].map(type).value_counts(), then clean them with pd.to_numeric(df["col"], errors="coerce").
Leading zeros are usually already lost
A ZIP code typed as 02134 in a numeric cell is stored by Excel as the number 2134. The zero was lost before pandas saw it, and dtype cannot recover it. Only cells formatted as Text keep the zero. Use dtype={"zip": "string"} to prevent pandas from converting text cells that look like numbers, and fix the source file for the rest.
Formulas and cached values
The same principle explains why you cannot get the formula text from read_excel. To inspect formulas, load the workbook with openpyxl directly.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `ImportError: Missing optional dependency 'openpyxl'` | Parser not installed | `pip install openpyxl` |
| `ValueError: Worksheet named 'Sales' not found` | Wrong or misspelled sheet name | List names with `pd.ExcelFile(path).sheet_names` |
| `FileNotFoundError` | Wrong path or working directory | Print `Path(path).resolve()` |
| `ValueError: Excel file format cannot be determined` | Unknown extension or a non-Excel file | Pass `engine="openpyxl"`, or check that the file is really a workbook |
| Headers show as `Unnamed: 0`, `Unnamed: 1` | Title rows or blank rows above the table | Use `skiprows` or `header`, covered in a later chapter |
Performance expectations
read_excel is much slower than read_csv for the same data, because every cell passes through XML parsing. There is no chunksize argument. The whole sheet is read into memory. For a large export, ask for a CSV if you can. If you must keep the workbook, restrict the load with usecols and nrows, and save a CSV or Parquet copy after the first successful load.
Checklist after loading
- Print
df.shapeand compare it with the number of rows you expect in the sheet. - Run
df.info()and look forobjectcolumns that should be numeric or datetime. - Check that integer columns with blanks have the dtype you want.
- Look at
df.head()anddf.tail(). Footer rows with totals are a common surprise.
Exercise
A sheet has a column units whose cells are 4, 7, an empty cell, and 12. pd.read_excel("stock.xlsx") gives it the dtype float64, and you want whole numbers with the gap kept as missing. Which argument do you add, and why is the default dtype a float?
Show answer
Add dtype={"units": "Int64"}. The default NumPy integer dtype cannot store NaN, so pandas reads a numeric column with an empty cell as float64. The nullable Int64 dtype can hold integers and a missing value together.
Exercise
You run pd.read_excel("data.xlsx") and get ImportError: Missing optional dependency 'openpyxl'. What does this tell you about how pandas reads Excel files, and what do you do?
Show answer
pandas delegates parsing of .xlsx files to a separate engine package and does not install it with pandas itself. Install it with pip install openpyxl in the same environment that runs your code, then run the script again.