Excel with Polars: read, explore, and query huge sheets without dying in the attempt
Practical guide to Excel with Polars: read sheets, inspect columns, paginate, search, sort, filter, and speed everything up with calamine and Parquet.
Table of Contents
Imagine an Excel file with twelve sheets, 300,000 rows per sheet, and columns that change names every month. Opening it in Excel takes two minutes. Filtering one column takes another three. And if you try to cross it with the product catalog, Excel thinks for so long that Windows asks if you want to close the program.
That file is not a rare case. It is the natural state of most companies: Excel is the de facto database. Polars does not replace Excel, but it reads it at a speed Excel cannot match, and it lets you do everything Excel does poorly: filter, sort, paginate, search across multiple sheets, and join tables without the machine crawling.
This guide is practical: each section solves a concrete operation you would do in Excel, but with Polars. By the end you have a flow to audit an entire workbook, from the first sheet to the exported report.
Excel is not a database (and that is why it hurts)
Excel is a spreadsheet, not a query engine. Every time you open a file, the program loads formatting, formulas, merged cells, styles, and charts. When you filter, it recalculates. When you sort, it moves rows. When you join two tables, it looks for matches cell by cell.
Polars does the opposite: it reads values, converts them into typed Apache Arrow columns, and runs operations in parallel over those columns. It does not keep formulas or styles: only data. That is why it can process in seconds what Excel takes minutes to do.
The practical rule: use Excel to capture data and Polars to analyze it. If the file will be used more than once, convert it to Parquet and leave Excel only for the final delivery.
What Polars needs to read Excel
Polars has no native Excel reader. It uses an external engine to convert the file into something it can read. Available engines:
- calamine (default): Rust-based, the fastest. Uses
fastexceland reads.xlsx,.xlsb, and.xls. - xlsx2csv: converts the sheet to CSV in memory and then uses Polars’ CSV reader. Slower.
- openpyxl: the slowest, but useful for weird structures that calamine cannot parse.
The recommendation is clear: use calamine unless it fails. To install with uv:
# New project
uv init excel-polars
cd excel-polars
uv add polars fastexcel
# Or in an existing environment
uv pip install polars fastexcel
If you use pip:
pip install polars fastexcel
To write Excel you need xlsxwriter:
uv add xlsxwriter
# or: pip install xlsxwriter
Open a workbook and see all sheets
Read a specific sheet
import polars as pl
df = pl.read_excel("sales.xlsx", sheet_name="January")
print(df)
If you do not specify sheet_name, Polars reads the first sheet. That is convenient for simple files, but dangerous for large workbooks: you may be loading the wrong sheet without realizing it. Always be explicit.
Read all sheets
sheet_id=0 loads all sheets and returns a dictionary {sheet_name: DataFrame}:
sheets = pl.read_excel("sales.xlsx", sheet_id=0)
print(sheets.keys())
You can also request a list of sheets by name:
sheets = pl.read_excel("sales.xlsx", sheet_name=["January", "February", "March"])
And if you want a sheet by index:
sheets = pl.read_excel("sales.xlsx", sheet_id=[1, 2, 3])
Careful: read options (read_options, schema_overrides, etc.) apply globally to all sheets. If you need different options per sheet, make separate calls.
See sheet names without loading data
pl.read_excel does not expose sheet names. For that you use fastexcel directly:
from fastexcel import read_excel as fx_read_excel
wb = fx_read_excel("sales.xlsx")
print(wb.sheet_names)
print(wb.table_names())
This opens the workbook and reads only metadata. It is the fastest way to know what is inside before loading a single row.
Read an Excel table (ListObject)
If the workbook uses named tables (Insert > Table), you can read them directly by name, without worrying about the sheet:
df = pl.read_excel("sales.xlsx", table_name="SalesTable")
Tables are more robust than ranges: if the range grows, the table grows with it. If your file has tables, use them.
Read multiple workbooks at once
Polars can read a list of files or a glob pattern:
df = pl.read_excel(
["sales_january.xlsx", "sales_february.xlsx"],
include_file_paths="file",
)
The file column tells you which workbook each row came from. It is the fastest way to consolidate monthly reports.
See columns, types, and structure without loading everything
The schema
print(df.schema)
Schema({'date': Date, 'customer': String, 'amount': Float64, 'region': String})
The schema tells you the name and type of each column. It is the first thing you should check: if customer_id appears as Int64, you lost the leading zeros. If date appears as String, date filters will not work as you expect.
Column names
print(df.columns)
Quick inspection
print(df.head(10))
print(df.tail(10))
print(df.glimpse()) # one line per column
print(df.describe()) # statistics
print(df.shape) # (rows, columns)
glimpse is the equivalent of “seeing the structure” in Excel, but without opening the file.
Fix types on read
If the file has IDs with leading zeros, force them to string:
df = pl.read_excel(
"sales.xlsx",
schema_overrides={
"customer_id": pl.String,
"date": pl.Date,
"amount": pl.Float64,
},
)
This avoids inference and speeds up reading: Polars does not have to guess as many types.
Read only some columns
df = pl.read_excel(
"sales.xlsx",
columns=["date", "customer", "amount"],
)
If the file has 50 columns and you use only 3, do not load all 50. In large files, this reduces time and memory noticeably.
You can also use indices:
df = pl.read_excel("sales.xlsx", columns=[0, 2, 5])
Headers that are not in the first row
Many reports have titles, logos, or notes before the table. Use read_options:
df = pl.read_excel(
"report.xlsx",
read_options={
"header_row": 3, # row 4 (index 3) has the names
"skip_rows": 1, # skip one row after the header
"n_rows": 1000, # read only 1000 rows
"use_columns": "A:E", # only columns A through E
},
)
header_row=None generates column_0, column_1, etc. Useful when the file has no headers.
Preview a sheet without loading it fully
pl.read_excel is eager: it loads the whole sheet. For a quick preview, limit rows at read time:
preview = pl.read_excel(
"sales.xlsx",
sheet_name="January",
read_options={"n_rows": 200},
)
print(preview)
Do not use df.head() for this: head runs after loading everything. n_rows is applied during reading.
Paginate and navigate rows
Polars has no row indexes like pandas. Pagination is a slicing operation: slice(offset, length).
page_size = 50
page = 3
start = (page - 1) * page_size
page_df = df.slice(start, page_size)
print(page_df)
You can also use head and tail:
df.head(20) # first 20
df.tail(20) # last 20
To bring specific rows by position:
df.gather([0, 5, 10, 15])
To sample random rows (what Excel would call “drawing lots”):
df.sample(n=20, seed=42)
df.sample(fraction=0.01, seed=42) # 1% of rows
seed makes the result reproducible. Without a seed, each run returns a different sample.
See a complete row
print(df.row(0, named=True))
row(0) returns a tuple; named=True returns a dictionary with column names. It is useful to inspect a record without printing the whole table.
Search and filter
Exact filter
df.filter(pl.col("region") == "North")
Multiple values
df.filter(pl.col("region").is_in(["North", "South", "Center"]))
Range
df.filter(pl.col("amount").is_between(1000, 5000))
Text contains
df.filter(pl.col("customer").str.contains("garcia", literal=True))
For case-insensitive search:
q = "garcia"
df.filter(pl.col("customer").str.to_lowercase().str.contains(q.lower(), literal=True))
Starts or ends with
df.filter(pl.col("product").str.starts_with("Laptop"))
df.filter(pl.col("email").str.ends_with("@company.com"))
Search across several columns at once
q = "garcia"
df.filter(
pl.any_horizontal(
pl.col("customer").str.to_lowercase().str.contains(q),
pl.col("email").str.to_lowercase().str.contains(q),
)
)
any_horizontal combines conditions with OR. For AND, use all_horizontal.
Nulls
df.filter(pl.col("amount").is_null())
df.filter(pl.col("amount").is_not_null())
Search all sheets
import polars as pl
sheets = pl.read_excel("sales.xlsx", sheet_id=0)
q = "garcia"
results = []
for name, sheet in sheets.items():
matches = sheet.filter(
pl.any_horizontal(
pl.col(pl.String).str.to_lowercase().str.contains(q)
)
)
if matches.height > 0:
results.append(matches.with_columns(pl.lit(name).alias("sheet")))
if results:
print(pl.concat(results, how="vertical_relaxed"))
pl.col(pl.String) selects all text columns in the sheet. It is a compact way to search any column without listing them.
Sort, rank, and draw samples
Simple sort
df.sort("amount", descending=True)
Multiple sort
df.sort(
["region", "amount"],
descending=[False, True],
nulls_last=True,
)
Top N and bottom N
df.top_k(10, by="amount")
df.bottom_k(10, by="amount")
top_k is more efficient than sort(...).head(10) because the engine does not sort the whole table: it keeps only the k best.
Rank
df.with_columns(
pl.col("amount").rank("dense", descending=True).alias("ranking")
)
Sort by several columns with priority
df.sort(
["priority", "date"],
descending=[True, False],
)
Draw random samples
df.sample(n=100, seed=42)
df.sample(fraction=0.05, seed=42)
To shuffle all rows:
df.sample(fraction=1.0, shuffle=True, seed=42)
See and consolidate several sheets or tables
Summary of all sheets
sheets = pl.read_excel("sales.xlsx", sheet_id=0)
for name, sheet in sheets.items():
print(f"{name}: {sheet.shape[0]} rows, {sheet.shape[1]} columns")
Consolidate all sheets into one DataFrame
frames = []
for name, sheet in sheets.items():
frames.append(sheet.with_columns(pl.lit(name).alias("sheet")))
consolidated = pl.concat(frames, how="vertical_relaxed")
print(consolidated.shape)
Use vertical_relaxed when sheets do not have exactly the same schema. If they do, vertical is stricter and warns you if something does not match.
Join two sheets by a key
sales = pl.read_excel("sales.xlsx", sheet_name="Sales")
products = pl.read_excel("sales.xlsx", sheet_name="Products")
result = sales.join(
products.select("product_id", "category", "price"),
on="product_id",
how="left",
)
See all tables in a workbook
wb = fx_read_excel("sales.xlsx")
print("Sheets:", wb.sheet_names)
print("Tables:", wb.table_names())
And read a specific table:
df = pl.read_excel("sales.xlsx", table_name="SalesTable")
Join several workbooks
df = pl.read_excel(
["sales_2024_01.xlsx", "sales_2024_02.xlsx", "sales_2024_03.xlsx"],
include_file_paths="file",
)
Then you can group by file or extract the month from the name.
Tips to make it fast, efficient, and powerful
1. Use calamine, not openpyxl
df = pl.read_excel("sales.xlsx", engine="calamine")
It is the default, but being explicit avoids surprises if someone changes global configuration. openpyxl is 5-20x slower on large files.
2. Read only the columns you need
df = pl.read_excel("sales.xlsx", columns=["date", "amount", "region"])
In a 50-column file, this can cut time in half.
3. Limit rows for exploration
preview = pl.read_excel(
"sales.xlsx",
read_options={"n_rows": 1000},
)
Do not load 300,000 rows to look at the first 10.
4. Avoid inference with schema_overrides
df = pl.read_excel(
"sales.xlsx",
schema_overrides={"customer_id": pl.String, "date": pl.Date},
)
Inference costs time and can be wrong. If you know the types, say so.
5. Convert to Parquet once
Excel is an input format, not a query format. If you will filter, sort, and search several times, convert:
df = pl.read_excel("sales.xlsx", sheet_name="January")
df.write_parquet("sales_january.parquet")
Then query with lazy:
lf = pl.scan_parquet("sales_january.parquet")
result = (
lf.filter(pl.col("amount") > 1000)
.group_by("region")
.agg(pl.col("amount").sum())
.collect()
)
This is the difference between 30 seconds and 30 milliseconds.
6. Do not use df.head() to preview a huge file
head runs after loading everything. Use read_options={"n_rows": N}.
7. Use top_k instead of sort().head()
df.top_k(10, by="amount") # more efficient
8. Avoid row-by-row loops
# Bad
for row in df.iter_rows():
...
# Good: expressions
df.with_columns((pl.col("quantity") * pl.col("price")).alias("total"))
9. Parallelize independent sheet reads
If you have 12 independent sheets, you can read them in parallel with concurrent.futures:
from concurrent.futures import ThreadPoolExecutor
def read_sheet(name):
return name, pl.read_excel("sales.xlsx", sheet_name=name)
with ThreadPoolExecutor(max_workers=4) as pool:
sheets = dict(pool.map(read_sheet, ["January", "February", "March", "April"]))
Careful: concurrent access to the same file may not be faster if the disk is the bottleneck. Measure before assuming.
10. Do not load all sheets if you only need one
sheet_id=0 is convenient, but it loads everything. If you are only going to analyze “January”, ask for “January”.
11. Export with style, but not in the analysis pipeline
Writing formatted Excel is slow. Do it at the end, once, not on every iteration.
Export results to Excel (bonus)
To write a DataFrame:
df.write_excel("result.xlsx", worksheet="Summary")
With formatting and autofit:
df.write_excel(
"result.xlsx",
worksheet="Summary",
table_style="Table Style Medium 9",
autofit=True,
column_totals=True,
freeze_panes="A2",
)
Multiple sheets in one workbook:
from xlsxwriter import Workbook
with Workbook("report.xlsx") as wb:
summary.write_excel(workbook=wb, worksheet="Summary", autofit=True)
detail.write_excel(workbook=wb, worksheet="Detail", autofit=True)
chart_data.write_excel(workbook=wb, worksheet="Data", autofit=True)
Polars can also create named tables, autofilters, conditional formats, sparklines, and formulas. It is a powerful way to deliver the result without going back to Excel to build it by hand.
Guided project: audit a sales workbook
Suppose a sales_2025.xlsx workbook with monthly sheets and a Products sheet. We want to:
- See which sheets it has.
- Consolidate all sales.
- Search for customers with “garcia”.
- Sort by amount.
- Join with products.
- Export a summary.
Step 1: inspect the workbook
from fastexcel import read_excel as fx_read_excel
import polars as pl
wb = fx_read_excel("sales_2025.xlsx")
print("Sheets:", wb.sheet_names)
print("Tables:", wb.table_names())
Step 2: consolidate
sheets = pl.read_excel("sales_2025.xlsx", sheet_id=0, engine="calamine")
sales = pl.concat(
[
sheet.with_columns(pl.lit(name).alias("month"))
for name, sheet in sheets.items()
if name != "Products"
],
how="vertical_relaxed",
)
Step 3: search
q = "garcia"
matches = sales.filter(
pl.any_horizontal(
pl.col(pl.String).str.to_lowercase().str.contains(q)
)
)
print(matches.shape)
Step 4: sort and rank
top = (
sales.sort("amount", descending=True, nulls_last=True)
.with_columns(
pl.col("amount").rank("dense", descending=True).alias("ranking")
)
.head(20)
)
print(top)
Step 5: join with products
products = pl.read_excel(
"sales_2025.xlsx",
sheet_name="Products",
columns=["product_id", "category", "price"],
)
enriched = sales.join(products, on="product_id", how="left")
Step 6: export
summary = (
enriched.group_by("month", "category")
.agg(
pl.col("amount").sum().alias("sales"),
pl.len().alias("transactions"),
)
.sort("month", "category")
)
summary.write_excel(
"sales_summary_2025.xlsx",
worksheet="Summary",
autofit=True,
column_totals=True,
)
Common mistakes
- Loading all sheets when you only need one. Use
sheet_nameorsheet_id. - Trusting type inference. A numeric ID loses leading zeros; a date may remain a string. Use
schema_overrides. - Using
openpyxlby default. It is the slowest engine; only use it if calamine fails. - Calling
df.head()to explore a large file. Useread_options={"n_rows": N}. - Not converting to Parquet. If you query the same Excel more than once, you pay the parsing cost again and again.
- Iterating rows with Python. Polars expressions are orders of magnitude faster.
- Joining sheets without checking the schema. Strict
verticalfails if types do not match;vertical_relaxedadjusts them, but can hide problems. - Exporting Excel on every iteration. Formatting is slow; do it at the end.
Checklist before working with a large Excel file
- I know which sheets and tables the workbook has (
sheet_names,table_names). - I read only the necessary columns.
- I force critical types with
schema_overrides. - To explore, I limit rows with
read_options={"n_rows": N}. - I use
engine="calamine". - If I will query several times, I convert to Parquet and use
scan_parquet. - I avoid
openpyxlunless necessary. - I do not iterate rows with Python; I use expressions.
- I verify the schema after every concatenation or join.
- I export to Excel only at the end, with formatting.
Excel lets you capture data. Polars lets you understand it. The file does not change: the tool you look at it with does. And when the tool stops being the bottleneck, analysis stops being a wait and starts being a conversation.
Related articles
By relevance
Polars from zero to expert: the complete guide to the Rust data framework
Complete Polars guide in Python: expressions, lazy API, streaming, IO, joins, window functions, and performance from zero to expert.
Large data analysis with Python: from pandas to Polars and DuckDB
How to analyze datasets that don't fit in memory with Python: Polars, DuckDB, chunking, and strategies that avoid OOM.
Full Stack Go: Notes and Todos App with HTMX, Templ and SQLite
Build a complete Notes and Todos app in Go: markdown notes with tags, todo checklists, full-text search, auth, HTMX reactivity, Templ templates, and SQLite.
Go 1.25 Medical API: DDD, TDD, BDD, PostgreSQL, Redis — Complete Clinical System
Build a production-ready medical records API in Go 1.25 with DDD, TDD, BDD, Gherkin scenarios, PostgreSQL, Redis. Full patient history, clinical boards, and every file explained.