Skip to content

Reading

Fast value extraction with ExcelReader.

API reference · Guide

ExcelReader

ExcelReader(path: str | PathLike[str] | IO[bytes] | None = None, use_memory_stream_for_xlsb: bool = True, errors: str = 'legacy')

A fast reader of cell values from XLSX, XLSM and XLSB files.

Use it as a context manager::

with ExcelReader("report.xlsb") as reader:
    rows = reader.read_all(reader.get_sheet_names()[0])

Error cells come back as CellError strings ("error:#DIV/0!"); with errors="openpyxl" they are plain text such as "#DIV/0!". For styles, coordinates or editing use load_workbook.

Examples:

Stream values without building the workbook model:

from xlspy import ExcelReader

with ExcelReader("report.xlsb") as reader:
    print(reader.get_sheet_names())
    for row in reader.get_rows("Sales"):
        print(row)

Formula text instead of cached values:

with ExcelReader("report.xlsx") as reader:
    rows = reader.read_all("Sales", data_only=False)
See Also

load_workbook when you need coordinates, styles or edits; the tutorial page reading for a comparison of the three read modes.

Source code in src/xlspy/reader.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def __init__(
    self,
    path: str | os.PathLike[str] | IO[bytes] | None = None,
    use_memory_stream_for_xlsb: bool = True,
    errors: str = "legacy",
) -> None:
    if errors not in {"legacy", "openpyxl"}:
        raise ValueError("errors must be 'legacy' or 'openpyxl'")
    self._errors = errors
    self._archive: zipfile.ZipFile | None = None
    self._remote_stream: IO[bytes] | None = None
    self._is_xlsb = False
    self._worksheet_id_to_name: dict[str, str] = {}
    self._worksheet_name_to_id: dict[str, str] = {}
    self._worksheet_id_to_location: dict[str, str] = {}
    # Relationship ids of chartsheets and dialog sheets: sheets without cells.
    self._cellless_sheet_ids: set[str] = set()
    self._shared_string_array: list[str] = []
    self._styles_cell_xfs_array: list[dict] = []
    self._number_formats_type_dict: dict[int, type] = dict(_default_number_formats_type_dict)
    self._shared_strings_location: str | None = None
    self._styles_location: str | None = None
    self._date_1904 = False
    self._path = _source_reference(path)
    # The file last opened, named in InvalidFileError messages.
    self._opened_path = "" if self._path is None else _source_label(self._path)
    self.use_memory_stream_for_xlsb = use_memory_stream_for_xlsb

open

open(path: str | PathLike[str] | IO[bytes]) -> None

Open path and read its sheet list, shared strings and styles.

path is a file name, a scheme:// URI opened through fsspec, or a binary file object such as io.BytesIO. An XLSB package is detected by its xl/workbook.bin part, any other package is read as XLSX/XLSM. Raises InvalidFileError for a damaged file.

Source code in src/xlspy/reader.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def open(self, path: str | os.PathLike[str] | IO[bytes]) -> None:
    """Open ``path`` and read its sheet list, shared strings and styles.

    ``path`` is a file name, a ``scheme://`` URI opened through fsspec, or a
    binary file object such as ``io.BytesIO``. An XLSB package is detected
    by its ``xl/workbook.bin`` part, any other package is read as
    XLSX/XLSM. Raises InvalidFileError for a damaged file.
    """
    # Re-opening the same instance must not leak the previous archive nor
    # accumulate worksheet/style/shared-string state from the previous file.
    source = _source_reference(path)
    assert source is not None  # open() has no None form
    self.close()
    self._opened_path = _source_label(source)
    self._path = source
    self._worksheet_id_to_name = {}
    self._worksheet_name_to_id = {}
    self._worksheet_id_to_location = {}
    self._cellless_sheet_ids = set()
    self._shared_string_array = []
    self._styles_cell_xfs_array = []
    self._number_formats_type_dict = dict(_default_number_formats_type_dict)
    self._shared_strings_location = None
    self._styles_location = None
    self._date_1904 = False

    remote_stream: IO[bytes] | None = None
    if isinstance(source, str) and is_remote_uri(source):
        remote_stream = open_remote(source)
        source = remote_stream
    self._remote_stream = remote_stream
    self._is_xlsb = _is_xlsb_source(source)
    try:
        with reading(self._opened_path):
            if self._is_xlsb:
                self._open_xlsb(source)
            else:
                self._open_xlsx(source)
    except BaseException:
        # A file that fails to parse must not keep the archive (and, on
        # Windows, the file) open: `with` never reaches __exit__ here.
        self.close()
        raise

close

close() -> None

Close the file; calling it again does nothing.

Source code in src/xlspy/reader.py
316
317
318
319
320
321
322
323
def close(self) -> None:
    """Close the file; calling it again does nothing."""
    if self._archive is not None:
        self._archive.close()
        self._archive = None
    if self._remote_stream is not None:
        self._remote_stream.close()
        self._remote_stream = None

get_sheet_names

get_sheet_names() -> list[str]

The sheet names, in workbook order, chartsheets included.

A chartsheet has no cells: get_rows yields nothing for it. See get_chartsheet_names.

Source code in src/xlspy/reader.py
342
343
344
345
346
347
348
def get_sheet_names(self) -> list[str]:
    """The sheet names, in workbook order, chartsheets included.

    A chartsheet has no cells: ``get_rows`` yields nothing for it. See
    ``get_chartsheet_names``.
    """
    return list(self._worksheet_name_to_id.keys())

get_chartsheet_names

get_chartsheet_names() -> list[str]

The names of the sheets without cells (chartsheets and dialog sheets), in workbook order.

Source code in src/xlspy/reader.py
350
351
352
def get_chartsheet_names(self) -> list[str]:
    """The names of the sheets without cells (chartsheets and dialog sheets), in workbook order."""
    return [name for name, rid in self._worksheet_name_to_id.items() if rid in self._cellless_sheet_ids]

read_part

read_part(path: str) -> bytes | None

The bytes of a package part, or None when the package has no such part.

Source code in src/xlspy/reader.py
373
374
375
376
377
378
def read_part(self, path: str) -> bytes | None:
    """The bytes of a package part, or None when the package has no such part."""
    try:
        return self._zip().read(path)
    except KeyError:
        return None

get_sheet_index

get_sheet_index(sheet_name: str) -> int

Return the 0-based position of sheet_name; raises ValueError when absent.

Source code in src/xlspy/reader.py
380
381
382
383
384
385
386
def get_sheet_index(self, sheet_name: str) -> int:
    """Return the 0-based position of ``sheet_name``; raises ValueError when absent."""
    names = self.get_sheet_names()
    for i, n in enumerate(names):
        if n == sheet_name:
            return i
    raise ValueError(f"Sheet '{sheet_name}' not found")

get_rows

get_rows(sheet_name: str, *, data_only: bool = True, streaming: bool = False) -> Generator[list[Any], None, None]

Yield values or formula text; streaming=True opts into incremental XLSB.

Source code in src/xlspy/reader.py
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
def get_rows(
    self, sheet_name: str, *, data_only: bool = True, streaming: bool = False
) -> Generator[list[Any], None, None]:
    """Yield values or formula text; streaming=True opts into incremental XLSB."""
    if not isinstance(data_only, bool):
        raise TypeError("data_only must be bool")
    if not isinstance(streaming, bool):
        raise TypeError("streaming must be bool")
    if self._sheet_part(sheet_name) is None:
        return  # a chartsheet: no cells
    if self._is_xlsb:
        if not data_only or streaming:
            from ._xlsb_read import read_xlsb_rows

            rows = read_xlsb_rows(self, sheet_name, data_only=data_only)
        else:
            rows = self._get_rows_xlsb(sheet_name)
    else:
        rows = self._get_rows_xlsx(sheet_name, data_only=data_only)
    rows = reading_rows(self._opened_path, rows)
    if self._errors == "legacy":
        yield from rows
    else:
        for row in rows:
            yield [str(value[6:]) if isinstance(value, CellError) else value for value in row]

read_all

read_all(sheet_name: str, *, data_only: bool = True, streaming: bool = False) -> list[list[Any]]

Return all rows of a sheet as a list; see get_rows.

Source code in src/xlspy/reader.py
414
415
416
def read_all(self, sheet_name: str, *, data_only: bool = True, streaming: bool = False) -> list[list[Any]]:
    """Return all rows of a sheet as a list; see ``get_rows``."""
    return list(self.get_rows(sheet_name, data_only=data_only, streaming=streaming))

to_pandas

to_pandas(sheet_name: str | int | None = 0, **kwargs: Any) -> Any

Read a sheet into a pandas DataFrame; see read_dataframe.

The reader stays open; the returned frame owns its data.

Source code in src/xlspy/reader.py
424
425
426
427
428
429
def to_pandas(self, sheet_name: str | int | None = 0, **kwargs: Any) -> Any:
    """Read a sheet into a pandas DataFrame; see `read_dataframe`.

    The reader stays open; the returned frame owns its data.
    """
    return self._to_dataframe("pandas", sheet_name, **kwargs)

to_polars

to_polars(sheet_name: str | int | None = 0, **kwargs: Any) -> Any

Read a sheet into a polars DataFrame; see read_dataframe.

Source code in src/xlspy/reader.py
431
432
433
def to_polars(self, sheet_name: str | int | None = 0, **kwargs: Any) -> Any:
    """Read a sheet into a polars DataFrame; see `read_dataframe`."""
    return self._to_dataframe("polars", sheet_name, **kwargs)

get_comments

get_comments(sheet_name: str) -> dict[str, Comment]

Return classic note text and authors, without reading worksheet rows.

The compatibility notes that link Excel to a threaded conversation are not included; use get_threaded_comments for those conversations.

Source code in src/xlspy/reader.py
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
def get_comments(self, sheet_name: str) -> dict[str, Comment]:
    """Return classic note text and authors, without reading worksheet rows.

    The compatibility notes that link Excel to a threaded conversation are
    not included; use `get_threaded_comments` for those conversations.
    """
    path = self._sheet_part(sheet_name)
    if path is None:
        return {}
    if self._is_xlsb:
        _, _, parts = find_comment_parts(self._zip().read, self._zip().namelist(), path)
        return (
            classic_comments_only(parse_comments(self._zip().read(parts["comments"][0]))[0])
            if "comments" in parts
            else {}
        )
    _, _, parts = find_comment_parts(self._zip().read, self._zip().namelist(), path)
    return read_comments(self._zip().read(parts["comments"][0])) if "comments" in parts else {}

get_threaded_comments

get_threaded_comments(sheet_name: str) -> dict[str, ThreadedComment]

Return the sheet's Excel 365 conversations, keyed by cell reference.

Classic notes are read by get_comments; this method reads only the modern threaded part, so both kinds can be inspected separately.

Source code in src/xlspy/reader.py
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
def get_threaded_comments(self, sheet_name: str) -> dict[str, ThreadedComment]:
    """Return the sheet's Excel 365 conversations, keyed by cell reference.

    Classic notes are read by `get_comments`; this method reads only the
    modern threaded part, so both kinds can be inspected separately.
    """
    path = self._sheet_part(sheet_name)
    if path is None:
        return {}
    names = self._zip().namelist()
    workbook_part = "xl/workbook.bin" if self._is_xlsb else "xl/workbook.xml"
    persons = {}
    person_part = find_person_part(self._zip().read, names, workbook_part)
    if person_part is not None:
        persons = read_persons(self._zip().read(person_part[0]))
    threaded_part = find_threaded_part(self._zip().read, names, path)
    if threaded_part is None:
        return {}
    return read_threaded_comments(self._zip().read(threaded_part[0]), persons)

get_defined_names

get_defined_names() -> list[DefinedName]

Return global and worksheet-local user names (not built-in names).

Source code in src/xlspy/reader.py
474
475
476
477
478
479
480
481
482
483
def get_defined_names(self) -> list[DefinedName]:
    """Return global and worksheet-local user names (not built-in names)."""
    if self._is_xlsb:
        return FormulaContext(
            self.get_sheet_names(),
            self._zip().read("xl/workbook.bin"),
            self.read_part,
            tables=lambda: table_catalog(self._zip().namelist(), self.read_part),
        ).defined_names()
    return read_defined_names(self._zip().read("xl/workbook.xml"), self.get_sheet_names())