IC Improve Code Recipes

Recipe 11.3 · Python

Excel Export with ClosedXML

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 want a real spreadsheet: numbers that sum, dates that sort, a header row that stays in place. The legacy answers are an HTML table renamed to .xls, which triggers Excel's "format and extension don't match" warning, or Excel automation through COM on the server, which Microsoft explicitly does not support and which leaves EXCEL.EXE processes running until someone reboots.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Every value is text, so the balance column cannot be summed, leading zeros vanish from account numbers, and the user sees a security-sounding warning on every open.

Requirements: Python 3.12+. Install: pip install fastapi

Python Fake Excel export that sends rendered HTML with an .xls content type (p239_r11_3_html_grid_as_xls_before.py)
"""Fake Excel export that sends rendered HTML with an .xls content type

Source: ImproveCode, Chapter 11, Recipe 11.3 "Excel Export with ClosedXML"
Section: The way it's often written
Book page: 239  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
WebForms GridView.RenderControl + Response.Write -> FastAPI Response carrying an
HTML table string; Excel warns that the file format does not match the extension.
"""

from fastapi import Response


def export_grid(grid_html: str) -> Response:
    # grid_html stands in for gridView.RenderControl(hw)
    return Response(
        content=grid_html,
        media_type="application/vnd.ms-excel",
        headers={"Content-Disposition": "attachment; filename=report.xls"},
    )

The improved recipe

ClosedXML writes genuine .xlsx files with no Excel installation. The exporter reuses the ExportColumn<T> definitions from Recipe 11.1, writes typed cell values, applies number formats per column, formats the range as an Excel table with filters, freezes the header and sizes the columns.

NuGet package: ClosedXML.

A usage snippet for an ASP.NET Core minimal API endpoint:

Requirements: Python 3.12+. Install: pip install openpyxl

Python Export records to a real .xlsx table with typed cells, formats and frozen header (p239_r11_3_excel_table_export_openpyxl.py)
"""Export records to a real .xlsx table with typed cells, formats and frozen header

Source: ImproveCode, Chapter 11, Recipe 11.3 "Excel Export with ClosedXML"
Section: The improved recipe
Book page: 239-241  -- original C# listing
Converted from C# to Python.
ClosedXML -> openpyxl (Table + TableStyleInfo "TableStyleLight9", freeze_panes,
number_format). AdjustToContents is approximated from cell text length with
the same min/max widths (8..60) over the first 500 rows. ExportColumn from p231.
"""

from __future__ import annotations

import datetime as dt
import enum
from collections.abc import Iterable, Sequence
from decimal import Decimal
from typing import Any, BinaryIO, TypeVar

from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.table import Table, TableStyleInfo

from p231_r11_1_csv_writer_quoting_formula_guard import ExportColumn

T = TypeVar("T")

MAX_SHEET_NAME_LENGTH = 31


def export(
    destination: BinaryIO,
    sheet_name: str,
    records: Iterable[T],
    columns: Sequence[ExportColumn[T]],
) -> None:
    if destination is None or records is None or columns is None:
        raise ValueError("destination, records and columns are required")

    workbook = Workbook()
    sheet = workbook.active
    sheet.title = _safe_sheet_name(sheet_name)

    for c, column in enumerate(columns, start=1):
        sheet.cell(row=1, column=c, value=column.header)

    row = 1
    for record in records:
        row += 1
        for c, column in enumerate(columns, start=1):
            sheet.cell(row=row, column=c, value=to_cell_value(column.value(record)))

    for c, column in enumerate(columns, start=1):
        if column.format is not None:
            for r in range(2, row + 1):
                sheet.cell(row=r, column=c).number_format = column.format

    last_row = max(row, 2)
    ref = f"A1:{get_column_letter(len(columns))}{last_row}"
    table = Table(displayName="Table1", ref=ref)
    table.tableStyleInfo = TableStyleInfo(name="TableStyleLight9",
                                          showRowStripes=True)
    sheet.add_table(table)
    sheet.freeze_panes = "A2"

    for c in range(1, len(columns) + 1):
        width = max(
            (len(str(sheet.cell(row=r, column=c).value or ""))
             for r in range(1, min(row, 500) + 1)),
            default=0,
        )
        sheet.column_dimensions[get_column_letter(c)].width = min(max(width + 2, 8), 60)

    workbook.save(destination)


def to_cell_value(value: Any) -> Any:
    match value:
        case None:
            return None
        case str() | bool():
            return value
        case dt.datetime():
            # Excel has no time zones; DateTimeOffset.DateTime drops the offset.
            return value.replace(tzinfo=None)
        case dt.date():
            return dt.datetime.combine(value, dt.time.min)
        case dt.timedelta():
            return value
        case Decimal() | float() | int():
            return value
        case enum.Enum():
            return value.name
        case _:
            return str(value)


def _safe_sheet_name(name: str) -> str:
    invalid = {":", "\\", "/", "?", "*", "[", "]"}
    cleaned = "".join("_" if ch in invalid else ch for ch in name).strip("'").strip()
    if len(cleaned) == 0:
        cleaned = "Sheet1"
    return cleaned[:MAX_SHEET_NAME_LENGTH]

Requirements: Python 3.12+. Install: pip install fastapi

Python Minimal API endpoint that streams a customers .xlsx download (p241_r11_3_excel_export_endpoint.py)
"""Minimal API endpoint that streams a customers .xlsx download

Source: ImproveCode, Chapter 11, Recipe 11.3 "Excel Export with ClosedXML"
Section: The improved recipe
Book page: 241  -- original C# listing
Converted from C# to Python.
app.MapGet -> FastAPI route; DI-injected CustomerRepository -> Depends;
MemoryStream + Results.File -> io.BytesIO + StreamingResponse.
`columns` is the customer column list defined as in p233.
"""

from __future__ import annotations

import io
from typing import Any

from fastapi import Depends, FastAPI
from fastapi.responses import StreamingResponse

from p239_r11_3_excel_table_export_openpyxl import export

app = FastAPI()
columns: list[Any] = []  # the ExportColumn list from the CSV recipe


class CustomerRepository:
    async def list_async(self) -> list[Any]:
        raise NotImplementedError


def get_repository() -> CustomerRepository:
    return CustomerRepository()


@app.get("/customers/export")
async def export_customers(
    repo: CustomerRepository = Depends(get_repository),
) -> StreamingResponse:
    customers = await repo.list_async()
    stream = io.BytesIO()
    export(stream, "Customers", customers, columns)
    stream.seek(0)
    return StreamingResponse(
        stream,
        media_type="application/vnd.openxmlformats-officedocument"
                   ".spreadsheetml.sheet",
        headers={"Content-Disposition": 'attachment; filename="customers.xlsx"'},
    )

How it works

ToCellValue maps .NET types to Excel's own: numbers stay numbers, dates become real Excel dates, booleans become TRUE and FALSE. That is what makes sums, sorting and filters work. Strings stay strings, so an account number such as 00123 keeps its leading zeros as long as you pass it as a string. A string that starts with = is stored as text, not a formula; ClosedXML only creates formulas through the FormulaA1 property, so the CSV injection problem from Recipe 11.1 does not apply here.

Number formats are set on whole columns, not on each cell, which keeps the file small and the export fast. Use Excel's format codes: #,##0.00 for money, yyyy-mm-dd for dates, 0% for percentages. Column formats apply to cells written in that column, while the header cells keep their text.

CreateTable turns the range into an Excel table, which gives users filter buttons, banded rows and a name they can refer to in formulas. The range always includes at least one data row, because Excel cannot open a file whose table has a header and no body. FreezeRows(1) keeps the header visible while scrolling.

AdjustToContents measures text to size columns. It is the slowest call in the method, so it looks at the first 500 rows only, and widths are clamped between 8 and 60 characters so one long comment field does not make a column three screens wide.

Sheet names have rules: no more than 31 characters and none of : \ / ? * [ ]. SafeSheetName enforces them, since report names often come from user input.

Variations and pitfalls

  • Memory. ClosedXML builds the whole workbook in memory. Up to a few hundred thousand cells it is fine. For millions of cells, write CSV, or use the lower-level DocumentFormat.OpenXml SDK with its streaming OpenXmlWriter.
  • Excel's row limit. A worksheet holds 1,048,576 rows. Check the count before exporting, and offer CSV above it.
  • DataTable sources. sheet.Cell(1, 1).InsertTable(dataTable) exports a DataTable in one line. Typed records with explicit columns give you control over headers and formats, which is why I prefer them for new code.
  • Don't automate Excel on a server. COM automation of Office in services or web applications is unsupported by Microsoft, slow, and leaks processes. No exceptions.