Recipe 11.4 · Python
Importing Excel Safely
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
Users upload spreadsheets for price lists, budgets and bulk updates. Import code reads cells by position, assumes every cell holds the expected type, and fails on row 4,000 with an InvalidCastException, after the first 3,999 rows have been saved. Or it trusts the file completely, and a 100 MB workbook with a million rows takes the web server down while it loads.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
The ACE OLE DB provider must be installed on the server and guesses column types from the first eight rows, so a column that starts with numbers turns later text values into DBNull.
Requirements: Python 3.12+. Install: pip install pyodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.
"""Excel price import via ACE OLE DB with positional, unchecked casts
Source: ImproveCode, Chapter 11, Recipe 11.4 "Importing Excel Safely"
Section: The way it's often written
Book page: 243 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
OleDbConnection/ACE provider -> pyodbc with the Excel ODBC driver; DataTable ->
fetchall(). Hard casts by column position crash on blanks or text.
"""
from collections.abc import Callable
from decimal import Decimal
import pyodbc
def import_prices(path: str, save_price: Callable[[str, Decimal], None]) -> None:
conn = pyodbc.connect(
"Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};"
"DBQ=" + path + ";ReadOnly=1", autocommit=True)
cursor = conn.cursor()
cursor.execute("SELECT * FROM [Sheet1$]")
dt = cursor.fetchall()
for r in dt:
save_price(str(r[0]), Decimal(float(r[2])))
The improved recipe
ClosedXML reads the workbook without any provider. The reader checks the file size before loading, finds columns by header name, reads typed values with per-row errors, and caps the number of rows. Nothing is saved until the whole file has been read and validated.
NuGet package: ClosedXML.
Requirements: Python 3.12+. Install: pip install openpyxl
"""Validated Excel price-list import: size/row limits, header lookup, per-cell errors
Source: ImproveCode, Chapter 11, Recipe 11.4 "Importing Excel Safely"
Section: The improved recipe
Book page: 243-245 -- original C# listing
Converted from C# to Python.
ClosedXML -> openpyxl with data_only=True (returns cached formula values, like
CachedValue); records -> frozen dataclasses; Math.Round -> Decimal.quantize
with banker's rounding (ROUND_HALF_EVEN, the .NET default).
"""
from __future__ import annotations
import datetime as dt
import os
from dataclasses import dataclass
from decimal import ROUND_HALF_EVEN, Decimal
from typing import Any, BinaryIO, Generic, TypeVar
from openpyxl import load_workbook
T = TypeVar("T")
@dataclass(frozen=True)
class ImportError_:
"""ImportError in the C#; renamed to avoid shadowing the Python builtin."""
row: int
column: str
message: str
@dataclass(frozen=True)
class PriceRow:
sku: str
price: Decimal
from_: dt.date
@dataclass(frozen=True)
class ImportResult(Generic[T]):
rows: list[T]
errors: list[ImportError_]
@property
def is_valid(self) -> bool:
return len(self.errors) == 0
REQUIRED = ["SKU", "Price", "Effective From"]
def read(stream: BinaryIO, max_bytes: int = 10_000_000,
max_rows: int = 50_000) -> ImportResult[PriceRow]:
if stream is None:
raise ValueError("stream is required")
rows: list[PriceRow] = []
errors: list[ImportError_] = []
if stream.seekable():
pos = stream.tell()
size = stream.seek(0, os.SEEK_END)
stream.seek(pos)
if size > max_bytes:
errors.append(ImportError_(0, "", "The file is too large."))
return ImportResult(rows, errors)
workbook = load_workbook(stream, read_only=True, data_only=True)
try:
sheet = workbook.worksheets[0]
all_rows = sheet.iter_rows(values_only=True)
header_row_number = 0
header: tuple[Any, ...] | None = None
for header_row_number, values in enumerate(all_rows, start=1):
if any(v not in (None, "") for v in values):
header = values
break
if header is None:
errors.append(ImportError_(0, "", "The worksheet is empty."))
return ImportResult(rows, errors)
columns: dict[str, int] = {}
for i, v in enumerate(header):
if v not in (None, ""):
columns[str(v).strip().casefold()] = i
for name in REQUIRED:
if name.casefold() not in columns:
errors.append(ImportError_(header_row_number, name, "Column missing."))
if errors:
return ImportResult(rows, errors)
data = list(all_rows)
while data and all(v in (None, "") for v in data[-1]):
data.pop() # trim to LastRowUsed
if len(data) > max_rows:
errors.append(ImportError_(0, "", f"More than {max_rows:,} rows."))
return ImportResult(rows, errors)
for offset, values in enumerate(data, start=1):
r = header_row_number + offset
if all(v in (None, "") for v in values):
continue
def cell(name: str) -> Any:
i = columns[name.casefold()]
return values[i] if i < len(values) else None
before = len(errors)
sku = cell("SKU")
price = cell("Price")
from_ = cell("Effective From")
sku_text = "" if sku is None else str(sku).strip()
if len(sku_text) == 0 or len(sku_text) > 20:
errors.append(ImportError_(r, "SKU", "Required, up to 20 chars."))
is_number = isinstance(price, (int, float)) and not isinstance(price, bool)
if not is_number or price <= 0:
errors.append(ImportError_(r, "Price", "Must be a positive number."))
if not isinstance(from_, (dt.datetime, dt.date)):
errors.append(ImportError_(r, "Effective From", "Must be a date."))
if len(errors) == before:
rows.append(PriceRow(
sku_text,
Decimal(str(price)).quantize(Decimal("0.01"), ROUND_HALF_EVEN),
from_.date() if isinstance(from_, dt.datetime) else from_,
))
finally:
workbook.close()
return ImportResult(rows, errors)
How it works
The size check runs before XLWorkbook loads anything. An .xlsx is a zip of XML files and expands several times in memory, so a limit on the upload is the cheapest protection you have. Combine it with the signature check from Recipe 8.4, which confirms the upload is at least a zip container.
Columns are found by header text, ignoring case and spaces at the ends. If any required column is missing, the import stops with one clear message per column instead of a stream of type errors. The row cap is checked from LastRowUsed before the loop starts.
Each cell is read as an XLCellValue, which knows its real type: IsNumber, IsDateTime, IsText, IsBlank. There is no guessing from the first eight rows. For cells with formulas, the code reads CachedValue, the result Excel saved with the file, instead of asking ClosedXML to recalculate. That is faster and avoids errors from functions ClosedXML does not implement.
Errors carry the row number as the user sees it in Excel and the column name, so the message "Row 214, Price: Must be a positive number" points the user straight at the cell. Valid rows are collected but not saved. The caller decides: reject the file if IsValid is false, or save the good rows and return the errors. I default to rejecting the file, because a half-applied price list is usually worse than none.
Variations and pitfalls
- Dates typed as text. If users type
30/06/2025into a cell formatted as text,IsDateTimeis false. Either reject it with a clear message, as the listing does, or tryDateOnly.TryParseExactwith the formats your users use. Never guess between day-first and month-first. - Old
.xlsfiles. ClosedXML reads only.xlsx. For legacy.xlsuploads, theExcelDataReaderpackage reads both formats; or ask users to save as.xlsx. - Provide a template. The import you never have to debug is the one where users fill in a template you generated with Recipe 11.3, with the right headers and a data validation list on coded columns.