Skip to content

Workbook model

load_workbook and the openpyxl-like objects it returns.

API reference · Guide

load_workbook

load_workbook(filename: str | PathLike[str] | IO[bytes], *, read_only: bool = False, data_only: bool = False, keep_vba: bool = False, rich_text: bool = False, keep_links: bool = True) -> Workbook

Load an XLSX/XLSM workbook, or stream an XLSB/XLSX with read_only.

The fast ExcelReader remains the best choice for raw value extraction. This function adds coordinates, styles, merges, dimensions and editing.

Parameters:

Name Type Description Default
filename str | PathLike[str] | IO[bytes]

Path to an .xlsx, .xlsm or .xlsb file, a scheme:// URI opened through fsspec, or a binary file object such as io.BytesIO. The object is not closed.

required
read_only bool

Stream rows instead of building the full model. Read-only sheets cannot be edited or saved.

False
data_only bool

Return cached formula results instead of formula text.

False
keep_vba bool

Keep the VBA project of an .xlsm workbook.

False
rich_text bool

Preserve rich-text runs as CellRichText values.

False
keep_links bool

Keep external workbook links in the model.

True

Examples:

Read a value, edit it and save a copy:

from xlspy import load_workbook

workbook = load_workbook("report.xlsx")
sheet = workbook["Sales"]
print(sheet["A1"].value)
sheet["B2"] = 130
workbook.save("report-updated.xlsx")
workbook.close()

Stream a large sheet without loading it whole:

workbook = load_workbook("large.xlsb", read_only=True)
for row in workbook["Data"].iter_rows(min_row=1, max_row=5, values_only=True):
    print(row)
workbook.close()
See Also

ExcelReader for the fastest values-only path, and Workbook for the in-memory model this function returns.

Source code in src/xlspy/workbook/_reader.py
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
def load_workbook(
    filename: str | os.PathLike[str] | IO[bytes],
    *,
    read_only: bool = False,
    data_only: bool = False,
    keep_vba: bool = False,
    rich_text: bool = False,
    keep_links: bool = True,
) -> Workbook:
    """Load an XLSX/XLSM workbook, or stream an XLSB/XLSX with ``read_only``.

    The fast ``ExcelReader`` remains the best choice for raw value extraction.
    This function adds coordinates, styles, merges, dimensions and editing.

    Args:
        filename: Path to an ``.xlsx``, ``.xlsm`` or ``.xlsb`` file, a
            ``scheme://`` URI opened through fsspec, or a binary file object
            such as ``io.BytesIO``. The object is not closed.
        read_only: Stream rows instead of building the full model. Read-only
            sheets cannot be edited or saved.
        data_only: Return cached formula results instead of formula text.
        keep_vba: Keep the VBA project of an ``.xlsm`` workbook.
        rich_text: Preserve rich-text runs as `CellRichText` values.
        keep_links: Keep external workbook links in the model.

    Examples:
        Read a value, edit it and save a copy:

        ```python
        from xlspy import load_workbook

        workbook = load_workbook("report.xlsx")
        sheet = workbook["Sales"]
        print(sheet["A1"].value)
        sheet["B2"] = 130
        workbook.save("report-updated.xlsx")
        workbook.close()
        ```

        Stream a large sheet without loading it whole:

        ```python
        workbook = load_workbook("large.xlsb", read_only=True)
        for row in workbook["Data"].iter_rows(min_row=1, max_row=5, values_only=True):
            print(row)
        workbook.close()
        ```

    See Also:
        `ExcelReader` for the fastest values-only path, and `Workbook` for the
        in-memory model this function returns.
    """
    path = _source_reference(filename)
    staged_directory: str | None = None
    if path is None:
        raise TypeError("filename must be a path or a binary file object, not None")
    if is_remote_uri(path):
        # The updater and the reader each open the package by path: keep one
        # local copy for the life of the workbook, as for a file object.
        source_label = path
        staged_directory = tempfile.mkdtemp(prefix="xlspy-source-")
        staged = os.path.join(staged_directory, "workbook.xlsx")
        try:
            download_remote(path, staged)
        except BaseException:
            shutil.rmtree(staged_directory, ignore_errors=True)
            raise
        path = staged
    elif isinstance(path, str):
        source_label = path
    else:
        # A file object: copy it once into a private temporary file, because
        # the updater and the reader each open the package by path. The copy
        # lives as long as the workbook; close() removes it. openpyxl reads a
        # stream from its start, so rewind the caller's object first: a stream
        # left at EOF by save() is the normal way to hand a workbook over.
        source = path
        try:
            source.seek(0)
        except (AttributeError, OSError):
            pass
        staged_directory = tempfile.mkdtemp(prefix="xlspy-source-")
        staged = os.path.join(staged_directory, "workbook.xlsx")
        try:
            with open(staged, "wb") as target:
                shutil.copyfileobj(source, target)
        except BaseException:
            shutil.rmtree(staged_directory, ignore_errors=True)
            raise
        source_label, path = _source_label(filename), staged
    with reading(source_label):
        try:
            workbook = _load_workbook(
                path,
                read_only=read_only,
                data_only=data_only,
                keep_vba=keep_vba,
                rich_text=rich_text,
                keep_links=keep_links,
            )
        except BaseException:
            if staged_directory is not None:
                shutil.rmtree(staged_directory, ignore_errors=True)
            raise
    if staged_directory is not None:
        workbook._source_staging = weakref.finalize(workbook, shutil.rmtree, staged_directory, ignore_errors=True)
    return workbook

Workbook

Workbook(write_only: bool = False, iso_dates: bool = False)

An Excel workbook in memory, with openpyxl's interface.

Workbook() starts with one empty sheet; load_workbook opens a file. save writes a new workbook as XLSB or XLSX/XLSM by the file extension, and a loaded workbook in the format it was loaded from.

Examples:

Build a workbook cell by cell, like openpyxl:

from xlspy import Workbook

workbook = Workbook()
sheet = workbook.active
sheet.title = "Data"
sheet["A1"] = "Item"
sheet["A2"] = 1200
workbook.save("book.xlsx")
workbook.close()

save chooses the format from the extension, so "book.xlsb" writes a binary XLSB package from the same code.

See Also

load_workbook to open an existing file, and XlsxWriter / XlsbWriter for the faster row-oriented API.

Source code in src/xlspy/workbook/_workbook.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def __init__(self, write_only: bool = False, iso_dates: bool = False) -> None:
    self.write_only = bool(write_only)
    self.iso_dates = bool(iso_dates)
    self._sheets: list[Worksheet] = []
    self._chartsheets: list[Chartsheet] = []
    self._active_index = 0
    self._styles = XlsxStyleTable.empty()
    self._styles_dirty = False
    self._properties = DocumentProperties()
    self._saved_properties: tuple[str, str] | None = None
    self._defined_names = DefinedNameList(self)
    self._defined_names_dirty = False
    self.template = False
    self.is_template = False
    self.code_name: str | None = None
    self.encoding = "utf-8"
    self.epoch = _datetime.datetime(1899, 12, 30)
    self.vba_archive: zipfile.ZipFile | None = None
    self._vba_added = False
    self.security = WorkbookSecurity()
    self.calculation = CalcProperties()
    self.views = [BookView()]
    self.custom_doc_props = CustomPropertyList()
    self.external_links: list = []
    # openpyxl's read-only package views: xlspy keeps neither package
    # relationships nor the theme bytes in the model.
    self.rels: list = []
    self.shared_strings: list[str] = []
    self.loaded_theme: bytes | None = None
    self.named_styles = NamedStyleList(["Normal"])
    self._format = "xlsx"
    self._loaded = False
    self._data_only = False
    self._loaded_active_index = 0
    self._loaded_workbook_meta: tuple[Any, ...] | None = None
    self._read_only = False
    self._updater = None
    self._source_path: str | None = None
    # Removes the private copy load_workbook staged from a file object.
    self._source_staging: Any = None
    self._sheet_visibility: dict[str, str] = {}
    self._loaded_worksheet_names: set[str] = set()
    self._mark_loaded = False
    if not self.write_only:
        self.create_sheet("Sheet")

sheetnames property

sheetnames: list[str]

The worksheet names, in order.

Chartsheets are kept in chartsheets and are not listed here. This is deliberate: openpyxl's sheetnames includes chartsheets, so code that needs them must read chartsheets.

read_only property writable

read_only: bool

True for a workbook loaded with read_only=True, which cannot be saved.

data_only property

data_only: bool

True when the workbook was loaded with data_only=True.

excel_base_date property

excel_base_date: datetime

The base date of serial date numbers, as openpyxl names epoch.

path property

path: str

The workbook part name.

mime_type property

mime_type: str

The content type the workbook's extension stands for.

style_names property

style_names: list[str]

The names of the workbook's named styles, as openpyxl lists them.

worksheets property

worksheets: list[Worksheet]

The worksheets, in order (a new list).

chartsheets property

chartsheets: list[Chartsheet]

The chartsheets, in order (a new list).

active property writable

active: Worksheet

The active worksheet; set it with a worksheet or its index.

properties property writable

properties: DocumentProperties

The document properties: title, author, dates and so on.

defined_names property

defined_names: DefinedNameList

The workbook's defined names.

add_vba_project

add_vba_project(project: Any) -> None

Embed a VBA project (vbaProject.bin) in a new macro-enabled workbook.

project may be a path, bytes or a binary file object. Save the workbook as .xlsm or .xltm; another extension is refused rather than dropping the project silently.

Source code in src/xlspy/workbook/_workbook.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def add_vba_project(self, project: Any) -> None:
    """Embed a VBA project (``vbaProject.bin``) in a new macro-enabled workbook.

    ``project`` may be a path, bytes or a binary file object. Save the
    workbook as ``.xlsm`` or ``.xltm``; another extension is refused rather
    than dropping the project silently.
    """
    data = read_vba_project(project)
    buffer = io.BytesIO()
    with zipfile.ZipFile(buffer, "w") as archive:
        archive.writestr("xl/vbaProject.bin", data)
    buffer.seek(0)
    if self.vba_archive is not None:
        self.vba_archive.close()
    self.vba_archive = zipfile.ZipFile(buffer, "r")
    self._vba_added = True

set_vba_name

set_vba_name(name: str) -> None

Set the VBA project's code name (workbookPr/@codeName).

Source code in src/xlspy/workbook/_workbook.py
137
138
139
def set_vba_name(self, name: str) -> None:
    """Set the VBA project's code name (``workbookPr/@codeName``)."""
    self.code_name = check_vba_name(name)

get_sheet_by_name

get_sheet_by_name(name: str) -> Worksheet

Return the worksheet called name; the same as wb[name].

Source code in src/xlspy/workbook/_workbook.py
262
263
264
def get_sheet_by_name(self, name: str) -> Worksheet:
    """Return the worksheet called ``name``; the same as ``wb[name]``."""
    return self[name]

get_sheet_names

get_sheet_names() -> list[str]

The worksheet names, as openpyxl's deprecated alias for sheetnames.

Source code in src/xlspy/workbook/_workbook.py
266
267
268
def get_sheet_names(self) -> list[str]:
    """The worksheet names, as openpyxl's deprecated alias for ``sheetnames``."""
    return self.sheetnames

get_index

get_index(worksheet: Worksheet | str) -> int

Return the 0-based position of worksheet or its title, as openpyxl's alias for index.

Source code in src/xlspy/workbook/_workbook.py
270
271
272
def get_index(self, worksheet: Worksheet | str) -> int:
    """Return the 0-based position of ``worksheet`` or its title, as openpyxl's alias for ``index``."""
    return self.index(worksheet)

index

index(worksheet: Worksheet | str) -> int

Return the 0-based position of worksheet, or of a sheet title.

Source code in src/xlspy/workbook/_workbook.py
274
275
276
277
278
279
280
281
def index(self, worksheet: Worksheet | str) -> int:
    """Return the 0-based position of ``worksheet``, or of a sheet title."""
    if isinstance(worksheet, str):
        for position, sheet in enumerate(self._sheets):
            if sheet.title == worksheet:
                return position
        raise ValueError(f"Worksheet {worksheet!r} does not exist")
    return self._sheets.index(worksheet)

create_sheet

create_sheet(title: str | None = None, index: int | None = None) -> Worksheet

Add a worksheet and return it.

Without a title it is named like openpyxl names it: "Sheet", then "Sheet1", "Sheet2" and so on, skipping a name already taken. Without an index it is added last.

Source code in src/xlspy/workbook/_workbook.py
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def create_sheet(self, title: str | None = None, index: int | None = None) -> Worksheet:
    """Add a worksheet and return it.

    Without a title it is named like openpyxl names it: ``"Sheet"``, then
    ``"Sheet1"``, ``"Sheet2"`` and so on, skipping a name already taken.
    Without an index it is added last.
    """
    if title is None:
        title = self._default_sheet_title()
    self._check_title(title)
    cls = WriteOnlyWorksheet if self.write_only else Worksheet
    sheet = cls(self, title, index=index)
    if index is None:
        self._sheets.append(sheet)
    else:
        self._sheets.insert(index, sheet)
        for position, item in enumerate(self._sheets):
            item._index = position
    sheet._loaded = self._loaded
    return sheet

create_chartsheet

create_chartsheet(title: str | None = None, index: int | None = None) -> Chartsheet

Add a chartsheet after the other sheets (XLSX only), as openpyxl does.

Source code in src/xlspy/workbook/_workbook.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
def create_chartsheet(self, title: str | None = None, index: int | None = None) -> Chartsheet:
    """Add a chartsheet after the other sheets (XLSX only), as openpyxl does."""
    if self.write_only:
        raise TypeError("create_chartsheet is not available in write-only mode")
    if title is None:
        taken = {sheet.title.casefold() for sheet in self._all_sheets()}
        number = 1
        while f"chart{number}" in taken:
            number += 1
        title = f"Chart{number}"
    self._check_title(title)
    count = len(self._sheets) + len(self._chartsheets)
    if index is not None and index < count:
        raise UnsupportedFeatureError("new chartsheets are added after the other sheets")
    sheet = Chartsheet(self, title, index=count)
    self._chartsheets.append(sheet)
    return sheet

move_sheet

move_sheet(sheet: Worksheet | str, offset: int = 0) -> None

Move a sheet offset positions (negative: towards the front), as openpyxl does.

Source code in src/xlspy/workbook/_workbook.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
def move_sheet(self, sheet: Worksheet | str, offset: int = 0) -> None:
    """Move a sheet ``offset`` positions (negative: towards the front), as openpyxl does."""
    if isinstance(sheet, str):
        sheet = self[sheet]
    if sheet not in self._sheets:
        raise ValueError("worksheet is not part of this workbook")
    active = self._sheets[self._active_index] if self._sheets else None
    index = self._sheets.index(sheet)
    self._sheets.remove(sheet)
    self._sheets.insert(max(0, min(index + offset, len(self._sheets))), sheet)
    for position, item in enumerate(self._sheets):
        item._index = position
    if active is not None:
        self._active_index = self._sheets.index(active)

remove

remove(worksheet: Worksheet) -> None

Remove worksheet from the workbook.

Source code in src/xlspy/workbook/_workbook.py
341
342
343
344
345
346
347
348
349
def remove(self, worksheet: Worksheet) -> None:
    """Remove ``worksheet`` from the workbook."""
    if worksheet not in self._sheets:
        raise ValueError("worksheet is not part of this workbook")
    self._sheets.remove(worksheet)
    if self._active_index >= len(self._sheets):
        self._active_index = max(0, len(self._sheets) - 1)
    if self._loaded:
        self._mark_loaded = True

remove_sheet

remove_sheet(worksheet: Worksheet) -> None

Remove worksheet, as openpyxl's deprecated alias for remove.

Source code in src/xlspy/workbook/_workbook.py
351
352
353
def remove_sheet(self, worksheet: Worksheet) -> None:
    """Remove ``worksheet``, as openpyxl's deprecated alias for ``remove``."""
    self.remove(worksheet)

copy_worksheet

copy_worksheet(from_worksheet: Worksheet) -> Worksheet

Copy a worksheet to a new sheet named after it, and return the copy.

Cells with their styles, notes and links, merged ranges, row and column sizes, the view, filter and page settings are copied. Charts, images, tables, data validations and conditional formats are not.

Source code in src/xlspy/workbook/_workbook.py
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
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
413
def copy_worksheet(self, from_worksheet: Worksheet) -> Worksheet:
    """Copy a worksheet to a new sheet named after it, and return the copy.

    Cells with their styles, notes and links, merged ranges, row and column sizes,
    the view, filter and page settings are copied. Charts, images, tables, data
    validations and conditional formats are not.
    """
    if self.write_only:
        raise TypeError("copy_worksheet is not available in write-only mode")
    title = from_worksheet.title
    base = f"{title} Copy"
    counter = 1
    taken = {sheet.title.casefold() for sheet in self._all_sheets()}
    while title.casefold() in taken:
        title = base if counter == 1 else f"{base}{counter - 1}"
        counter += 1
    target = self.create_sheet(title)
    for row_number, row in from_worksheet._cells.items():
        for column, cell in row.items():
            new_cell = target.cell(row_number, column, cell.value)
            new_cell._style_id = cell._style_id
            # Own copies, as openpyxl makes: editing one sheet leaves the other alone.
            new_cell._comment = copy.copy(cell.comment)
            new_cell._hyperlink = copy.copy(cell.hyperlink)
            new_cell._named_style = cell._named_style
    target._merged_cells = MultiCellRange(from_worksheet._merged_cells.ranges)
    target._threaded_comments = copy.deepcopy(from_worksheet._threaded_comments)
    # A copy is a separate conversation: give its messages new ids when saved.
    for ref, thread in target._threaded_comments.items():
        thread.id = None
        for reply in thread.replies:
            reply.id = None
            reply._parent_id = None
        target._dirty_threaded_comments.add(ref)
    for name in ("_column_dimensions", "_row_dimensions"):
        getattr(target, name).update(copy.deepcopy(dict(getattr(from_worksheet, name))))
    target._row_heights = dict(from_worksheet._row_heights)
    target._hidden_rows = set(from_worksheet._hidden_rows)
    target._freeze_panes = from_worksheet.freeze_panes
    target._auto_filter = copy.deepcopy(from_worksheet.auto_filter)
    target._sheet_state = from_worksheet.sheet_state
    target._sheet_properties = copy.deepcopy(from_worksheet.sheet_properties)
    target._sheet_view = copy.deepcopy(from_worksheet.sheet_view)
    # The view list holds the object, not a copy; rebind it or ``views``
    # keeps reporting the default view the new sheet was created with.
    target._views = SheetViewList(target._sheet_view)
    for name in (
        "page_setup",
        "page_margins",
        "print_options",
        "HeaderFooter",
        "sheet_format",
        "row_breaks",
        "col_breaks",
        "ignored_errors",
    ):
        setattr(target, name, copy.deepcopy(getattr(from_worksheet, name)))
    target._mark_dirty("copy")
    return target

add_named_style

add_named_style(style: NamedStyle) -> None

Register a NamedStyle so that cells can use it by name.

Source code in src/xlspy/workbook/_workbook.py
426
427
428
429
430
431
432
def add_named_style(self, style: NamedStyle) -> None:
    """Register a NamedStyle so that cells can use it by name."""
    if not isinstance(style, NamedStyle):
        raise TypeError("style must be a NamedStyle")
    self._styles.add_named_style(style)
    self.named_styles.add(style)
    self._styles_dirty = True

create_named_range

create_named_range(name: str, worksheet: Worksheet | None = None, value: str | None = None, scope: str | None = None) -> None

Add a defined name, as openpyxl's deprecated create_named_range.

Prefer workbook.defined_names[name] = DefinedName(...).

Source code in src/xlspy/workbook/_workbook.py
434
435
436
437
438
439
440
441
442
443
444
445
def create_named_range(
    self, name: str, worksheet: Worksheet | None = None, value: str | None = None, scope: str | None = None
) -> None:
    """Add a defined name, as openpyxl's deprecated ``create_named_range``.

    Prefer ``workbook.defined_names[name] = DefinedName(...)``.
    """
    if value is None:
        raise ValueError("a named range needs a value")
    if worksheet is not None:
        value = f"{quote_sheet_name(worksheet.title)}!{value}"
    self.defined_names.add(DefinedName(name, value, scope))

save

save(filename: WriteTarget) -> None

Write the workbook to filename, a path, a scheme:// URI or a writable binary file.

A URI is uploaded through fsspec; the extension of its path chooses the format. Raises ValueError for a workbook loaded with read_only=True.

Source code in src/xlspy/workbook/_workbook.py
517
518
519
520
521
522
523
524
525
526
527
528
def save(self, filename: WriteTarget) -> None:
    """Write the workbook to ``filename``, a path, a ``scheme://`` URI or a
    writable binary file.

    A URI is uploaded through fsspec; the extension of its path chooses the
    format. Raises ValueError for a workbook loaded with ``read_only=True``.
    """
    if self._read_only:
        raise ValueError("a read-only workbook cannot be saved")
    from ._writer import save_workbook

    save_workbook(self, filename)

close

close() -> None

Release the files held by a loaded or read-only workbook.

Source code in src/xlspy/workbook/_workbook.py
530
531
532
533
534
535
536
537
538
539
540
541
542
def close(self) -> None:
    """Release the files held by a loaded or read-only workbook."""
    if self._updater is not None:
        self._updater.close()
        self._updater = None
    for sheet in self._sheets:
        reader = getattr(sheet, "_reader", None)
        if reader is not None:
            reader.close()
            sheet._reader = None
    if self._source_staging is not None:
        self._source_staging()  # removes the staged copy now, not at collection
        self._source_staging = None

Worksheet

Worksheet(workbook: Workbook, title: str, *, index: int | None = None)

A worksheet of a Workbook, with openpyxl's interface.

Get one from wb.active, wb["Name"] or Workbook.create_sheet. Address cells with ws["A1"], ws["A1:C3"] or cell; add rows with append.

Source code in src/xlspy/workbook/_worksheet.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def __init__(self, workbook: Workbook, title: str, *, index: int | None = None) -> None:
    self._workbook = workbook
    self._title = title
    self._index = index
    self._cells: dict[int, dict[int, Cell]] = {}
    self._max_row = 0
    self._max_column = 0
    self._merged_cells = MultiCellRange()
    self._column_dimensions = DimensionHolder(ColumnDimension, _column_key)
    self._row_dimensions = DimensionHolder(RowDimension, _row_key)
    self._freeze_panes: str | None = None
    self._auto_filter = AutoFilter()
    self._sheet_state = "visible"
    self._sheet_properties = SheetProperties()
    self._sheet_view = SheetView(showGridLines=True)
    self._views = SheetViewList(self._sheet_view)
    # Scenarios and legacy VML are preserved, not modelled; openpyxl reports them.
    self._scenarios: Any = None
    self._legacy_drawing: str | None = None
    self._dirty = False
    self._dirty_cells: set[tuple[int, int]] = set()
    self._dirty_styles: set[str] = set()
    self._dirty_comments: set[str] = set()
    self._dirty_threaded_comments: set[str] = set()
    self._dirty_hyperlinks: set[str] = set()
    self._dirty_meta: set[str] = set()
    self._loaded = False
    self._original_title = title
    self._meta_signature: tuple[Any, ...] | None = None
    self._original_protection_hash: tuple[str | None, str | None, str | None, int | None] | None = None
    self._path: str | None = None
    self._row_heights: dict[int, float] = {}
    self._hidden_rows: set[int] = set()
    self._data_validations = DataValidationList()
    self._tables = TableList()
    self._charts: list[Chart] = []
    self._images: list[Image] = []
    self._drawing_sources: list[tuple[str, int, Any]] = []
    self._saved_drawing_objects: list[Any] | None = None
    self._saved_merges: Any = None
    self._saved_object_signatures: dict[str, Any] | None = None
    self._saved_table_objects: list[Any] = []
    self._saved_layout: Any = None
    self._protection_iso: bytes | None = None
    self._protection_iso_algorithm: str | None = None
    self._conditional_formats = ConditionalFormattingList()
    # For a loaded workbook: how many objects of each list a save already
    # put into the package (see _objects.pending_objects).
    self._saved_object_counts: dict[str, int] = {}
    # The print setup a loaded sheet already has in the package, so saving
    # does not rewrite a sheet whose print settings were not edited.
    self._saved_print_settings = None
    self._print_settings = None
    self.page_setup = PageSetup()
    self.page_margins = WorksheetPageMargins()
    self.print_options = PrintOptions()
    self.HeaderFooter = HeaderFooter()
    self.sheet_format = SheetFormatProperties()
    self.protection = WorksheetProtection()
    self.row_breaks = RowBreak()
    self.col_breaks = ColBreak()
    self.ignored_errors: list = []
    self._print_area: str | None = None
    self._print_title_rows: str | None = None
    self._print_title_cols: str | None = None
    self._comments: dict[str, Comment] = {}
    self._threaded_comments: dict[str, ThreadedComment] = {}

parent property

parent: Workbook

The workbook that holds the sheet, as openpyxl names it.

encoding property

encoding: str

Always "utf-8", for openpyxl compatibility.

mime_type property

mime_type: str

The content type of a worksheet part.

path property

path: str

The worksheet part name, such as /xl/worksheets/sheet1.xml.

title property writable

title: str

The sheet name.

Setting it renames the sheet and points formulas, validations, conditional formats, internal links and defined names at the new name, as Excel does.

sheet_state property writable

sheet_state: str

"visible", "hidden" or "veryHidden".

merged_cells property

merged_cells: MultiCellRange

The merged ranges of the sheet.

merged_cell_ranges property

merged_cell_ranges: list[str]

A copy of the merged range strings, as openpyxl's deprecated alias.

array_formulae property

array_formulae: dict[str, str]

Array formula anchors and the range each one fills, as openpyxl maps them.

column_groups property

column_groups: list[str]

The column ranges that span more than one column, such as "A:C".

column_dimensions property

column_dimensions: DimensionHolder

Column widths, visibility and outline levels, keyed by column letter.

Looking up a column that has no entry creates one.

row_dimensions property

row_dimensions: DimensionHolder

Row heights, visibility and outline levels, keyed by 1-based row number.

Looking up a row that has no entry creates one.

freeze_panes property writable

freeze_panes: str | None

The top-left cell of the scrolling pane, or None.

"B2" freezes row 1 and column A. Read from sheet_view.pane, as openpyxl does, so a pane set through the view is visible here.

auto_filter property writable

auto_filter: AutoFilter

The sheet's AutoFilter: its range, filter columns and sort state.

sheet_properties property

sheet_properties: SheetProperties

Sheet properties such as the tab colour and outline settings.

sheet_view property

sheet_view: SheetView

The first sheet view: zoom, grid lines, selection and panes.

views property

views: SheetViewList

Every sheet view, as openpyxl's ws.views.

defined_names property

defined_names: MutableMapping[str, Any]

The defined names scoped to this sheet, keyed by name, as openpyxl's map.

Assigning an entry stores it on the workbook with this sheet as its scope, so it is written on save. Deleting one removes only this sheet's entry.

scenarios property writable

scenarios: Any

The sheet's scenarios: always None, because xlspy preserves but does not model them.

openpyxl reports an empty ScenarioList on a sheet without scenarios.

legacy_drawing property

legacy_drawing: str | None

The relationship id of the sheet's legacy VML drawing.

Always None: the loaders preserve the part but do not expose its id, so this is a placeholder for openpyxl's attribute.

active_cell property

active_cell: str | None

The active cell of the first selection, or None when the view has none.

selected_cell property

selected_cell: str | None

The selected range of the first selection, or None when the view has none.

show_gridlines property writable

show_gridlines: bool | None

Whether the sheet view shows grid lines; None leaves Excel's default.

protection property writable

protection: WorksheetProtection

Sheet protection settings.

page_margins property writable

page_margins: WorksheetPageMargins

Page margins for printing, in inches.

max_row property

max_row: int

The last row that holds a cell; 0 for an empty sheet.

max_column property

max_column: int

The last column that holds a cell; 0 for an empty sheet.

min_row property

min_row: int

Always 1: the used range is reported from A1, as openpyxl does for new sheets.

min_column property

min_column: int

Always 1: the used range is reported from A1, as openpyxl does for new sheets.

dimensions property

dimensions: str

The used range from A1, such as "A1:D20"; "A1:A1" for an empty sheet.

rows property

rows: Iterator[tuple[Cell, ...]]

The rows of the used range as tuples of cells (see iter_rows).

columns property

columns: Iterator[tuple[Cell, ...]]

The columns of the used range as tuples of cells (see iter_cols).

values property

values: Iterator[tuple[Any, ...]]

The rows of the used range as tuples of values.

data_validations property

data_validations: DataValidationList

The sheet's data validation rules.

tables property

tables: TableList

The sheet's tables; a table name also works as a lookup key.

charts property

charts: list[Chart]

The charts on the sheet, new and loaded.

images property

images: list[Image]

The images on the sheet.

conditional_formatting property

conditional_formatting: ConditionalFormattingList

The sheet's conditional formatting, grouped by range.

oddHeader property

oddHeader: HeaderFooterItem

The header of odd pages (all pages unless odd and even pages differ).

oddFooter property

oddFooter: HeaderFooterItem

The footer of odd pages (all pages unless odd and even pages differ).

evenHeader property

evenHeader: HeaderFooterItem

The header of even pages, when odd and even pages differ.

evenFooter property

evenFooter: HeaderFooterItem

The footer of even pages, when odd and even pages differ.

firstHeader property

firstHeader: HeaderFooterItem

The header of the first page, when the first page differs.

firstFooter property

firstFooter: HeaderFooterItem

The footer of the first page, when the first page differs.

print_area property writable

print_area: str | None

The print area as a range string, or None.

print_title_rows property writable

print_title_rows: str | None

Rows repeated at the top of every printed page, such as "1:2".

print_title_cols property writable

print_title_cols: str | None

Columns repeated at the left of every printed page, such as "A:B".

print_titles property

print_titles: str

The print titles as openpyxl formats them, e.g. 'Sheet'!$1:$2.

calculate_dimension

calculate_dimension(force: bool = False) -> str

Return dimensions. force is accepted for openpyxl compatibility.

Source code in src/xlspy/workbook/_worksheet.py
451
452
453
def calculate_dimension(self, force: bool = False) -> str:
    """Return ``dimensions``. ``force`` is accepted for openpyxl compatibility."""
    return self.dimensions

insert_rows

insert_rows(idx: int, amount: int = 1) -> None

Insert amount empty rows before row idx.

Source code in src/xlspy/workbook/_worksheet.py
568
569
570
def insert_rows(self, idx: int, amount: int = 1) -> None:
    """Insert ``amount`` empty rows before row ``idx``."""
    _shift.shift_rows(self, idx, amount, delete=False)

delete_rows

delete_rows(idx: int, amount: int = 1) -> None

Delete amount rows starting at row idx; the rows below move up.

Source code in src/xlspy/workbook/_worksheet.py
572
573
574
def delete_rows(self, idx: int, amount: int = 1) -> None:
    """Delete ``amount`` rows starting at row ``idx``; the rows below move up."""
    _shift.shift_rows(self, idx, amount, delete=True)

insert_cols

insert_cols(idx: int, amount: int = 1) -> None

Insert amount empty columns before column idx (1-based).

Source code in src/xlspy/workbook/_worksheet.py
576
577
578
def insert_cols(self, idx: int, amount: int = 1) -> None:
    """Insert ``amount`` empty columns before column ``idx`` (1-based)."""
    _shift.shift_cols(self, idx, amount, delete=False)

delete_cols

delete_cols(idx: int, amount: int = 1) -> None

Delete amount columns starting at column idx; the rest move left.

Source code in src/xlspy/workbook/_worksheet.py
580
581
582
def delete_cols(self, idx: int, amount: int = 1) -> None:
    """Delete ``amount`` columns starting at column ``idx``; the rest move left."""
    _shift.shift_cols(self, idx, amount, delete=True)

move_range

move_range(cell_range: str, rows: int = 0, cols: int = 0, translate: bool = False) -> None

Move the cells of cell_range; cells at the destination are replaced. translate=True shifts the relative references of moved formulas.

Source code in src/xlspy/workbook/_worksheet.py
584
585
586
587
def move_range(self, cell_range: str, rows: int = 0, cols: int = 0, translate: bool = False) -> None:
    """Move the cells of ``cell_range``; cells at the destination are replaced.
    ``translate=True`` shifts the relative references of moved formulas."""
    _shift.move_range(self, cell_range, rows, cols, translate)

add_chart

add_chart(chart: Chart, anchor: str | None = None) -> None

Place chart on the sheet, at anchor (a cell such as "E2") when given.

Source code in src/xlspy/workbook/_worksheet.py
590
591
592
593
594
595
def add_chart(self, chart: Chart, anchor: str | None = None) -> None:
    """Place ``chart`` on the sheet, at ``anchor`` (a cell such as ``"E2"``) when given."""
    _expect(chart, Chart, "chart", "an xlspy Chart")
    if anchor is not None:
        chart = replace(chart, anchor=anchor)
    self._charts.append(chart)

add_image

add_image(img: Image, anchor: str | None = None) -> None

Place img on the sheet, at anchor (a cell such as "E2") when given.

Source code in src/xlspy/workbook/_worksheet.py
597
598
599
600
601
602
603
def add_image(self, img: Image, anchor: str | None = None) -> None:
    """Place ``img`` on the sheet, at ``anchor`` (a cell such as ``"E2"``) when given."""
    _expect(img, Image, "image", "an xlspy Image")
    if anchor is not None:
        # The bytes already read: a file object source is used up.
        img = replace(img, path=img.data, anchor=anchor)
    self._images.append(img)

add_table

add_table(table: ExcelTable | Table) -> None

Add a table: an ExcelTable or an openpyxl-style Table.

Source code in src/xlspy/workbook/_worksheet.py
605
606
607
608
def add_table(self, table: ExcelTable | Table) -> None:
    """Add a table: an ``ExcelTable`` or an openpyxl-style ``Table``."""
    _expect(table, (ExcelTable, Table), "table", "an xlspy ExcelTable or Table")
    self._tables.append(table)

add_data_validation

add_data_validation(data_validation: DataValidation) -> None

Add a data validation rule.

Source code in src/xlspy/workbook/_worksheet.py
610
611
612
613
def add_data_validation(self, data_validation: DataValidation) -> None:
    """Add a data validation rule."""
    _expect(data_validation, DataValidation, "data_validation", "an xlspy DataValidation")
    self._data_validations.append(data_validation)

cell

cell(row: int, column: int | str, value: Any = None) -> Cell

Return the cell at row and column, creating it when needed.

Both are 1-based; the column may also be a letter. A value other than None is assigned to the cell. A cell inside a merged range, other than its top-left one, is a read-only MergedCell.

Source code in src/xlspy/workbook/_worksheet.py
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
def cell(self, row: int, column: int | str, value: Any = None) -> Cell:
    """Return the cell at ``row`` and ``column``, creating it when needed.

    Both are 1-based; the column may also be a letter. A ``value`` other than None is
    assigned to the cell. A cell inside a merged range, other than its top-left one,
    is a read-only ``MergedCell``.
    """
    row = _coerce_row(row)
    column = _coerce_column(column)
    if self._is_merged_subcell(row, column):
        merged = MergedCell(self, row, column, style_id=0)
        if value is not None:
            raise AttributeError("read-only cell (merged range)")
        return merged
    cell = self._cells.get(row, {}).get(column)
    if cell is None:
        cell = Cell(self, row, column, style_id=0)
        self._cells.setdefault(row, {})[column] = cell
        self._max_row = max(self._max_row, row)
        self._max_column = max(self._max_column, column)
    if value is not None:
        cell.value = value
    return cell

append

append(iterable: Iterable[Any]) -> int

Write a row after the last used row and return its row number.

iterable holds the values from column A on; a mapping places its values by column letter or 1-based column number instead.

Source code in src/xlspy/workbook/_worksheet.py
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
def append(self, iterable: Iterable[Any]) -> int:
    """Write a row after the last used row and return its row number.

    ``iterable`` holds the values from column A on; a mapping places its values by
    column letter or 1-based column number instead.
    """
    if isinstance(iterable, Mapping):
        row = self._max_row + 1
        for key, value in iterable.items():
            if isinstance(key, str):
                column = _coerce_column(key)
            elif isinstance(key, int) and not isinstance(key, bool):
                if not 1 <= key <= 16384:
                    raise ValueError("column index must be 1..16384")
                column = key
            else:
                raise TypeError("dict keys must be column letters or 1-based ints")
            if isinstance(value, WriteOnlyCell):
                value = value.value
            self.cell(row, column, value)
        if iterable:
            self._max_row = max(self._max_row, row)
            self._max_column = max(
                self._max_column,
                max(_coerce_column(key) for key in iterable),
            )
        return row
    if isinstance(iterable, (str, bytes, bytearray)):
        raise TypeError("a row must be an iterable of cells, not text")
    values = [value.value if isinstance(value, WriteOnlyCell) else value for value in iterable]
    row = self._max_row + 1
    if values and row <= 1048576 and len(values) <= 16384 and not self._merged_cells and row not in self._cells:
        self._append_new_row(row, values)
        return row
    for column, value in enumerate(values, 1):
        if value is not None:
            self.cell(row, column, value)
        else:
            # An explicit empty cell still expands the used range, matching
            # openpyxl when a row is appended with a trailing None.
            self._max_column = max(self._max_column, column)
    if values:
        self._max_row = max(self._max_row, row)
    return row

iter_rows

iter_rows(min_row: int | None = None, max_row: int | None = None, min_col: int | None = None, max_col: int | None = None, values_only: Literal[False] = False) -> Iterator[tuple[Cell, ...]]
iter_rows(min_row: int | None = None, max_row: int | None = None, min_col: int | None = None, max_col: int | None = None, *, values_only: Literal[True]) -> Iterator[tuple[Any, ...]]
iter_rows(min_row: int | None = None, max_row: int | None = None, min_col: int | None = None, max_col: int | None = None, values_only: bool = False) -> Iterator[tuple[Any, ...]]
iter_rows(min_row: int | None = None, max_row: int | None = None, min_col: int | None = None, max_col: int | None = None, values_only: bool = False) -> Iterator[tuple[Any, ...]]

Yield the rows of a range as tuples of cells, or of values with values_only.

Bounds are 1-based and inclusive; each one left out defaults to the used range.

Source code in src/xlspy/workbook/_worksheet.py
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
def iter_rows(
    self,
    min_row: int | None = None,
    max_row: int | None = None,
    min_col: int | None = None,
    max_col: int | None = None,
    values_only: bool = False,
) -> Iterator[tuple[Any, ...]]:
    """Yield the rows of a range as tuples of cells, or of values with ``values_only``.

    Bounds are 1-based and inclusive; each one left out defaults to the used range.
    """
    min_row = 1 if min_row is None else _coerce_row(min_row)
    max_row = self._max_row if max_row is None else _coerce_row(max_row)
    min_col = 1 if min_col is None else _coerce_column(min_col)
    max_col = self._max_column if max_col is None else _coerce_column(max_col)
    for row in range(min_row, max_row + 1):
        if values_only:
            yield tuple(self._value_at(row, col) for col in range(min_col, max_col + 1))
        else:
            yield tuple(self.cell(row, col) for col in range(min_col, max_col + 1))

iter_cols

iter_cols(min_col: int | None = None, max_col: int | None = None, min_row: int | None = None, max_row: int | None = None, values_only: Literal[False] = False) -> Iterator[tuple[Cell, ...]]
iter_cols(min_col: int | None = None, max_col: int | None = None, min_row: int | None = None, max_row: int | None = None, *, values_only: Literal[True]) -> Iterator[tuple[Any, ...]]
iter_cols(min_col: int | None = None, max_col: int | None = None, min_row: int | None = None, max_row: int | None = None, values_only: bool = False) -> Iterator[tuple[Any, ...]]
iter_cols(min_col: int | None = None, max_col: int | None = None, min_row: int | None = None, max_row: int | None = None, values_only: bool = False) -> Iterator[tuple[Any, ...]]

Yield the columns of a range as tuples of cells, or of values with values_only.

Bounds are 1-based and inclusive; each one left out defaults to the used range.

Source code in src/xlspy/workbook/_worksheet.py
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
def iter_cols(
    self,
    min_col: int | None = None,
    max_col: int | None = None,
    min_row: int | None = None,
    max_row: int | None = None,
    values_only: bool = False,
) -> Iterator[tuple[Any, ...]]:
    """Yield the columns of a range as tuples of cells, or of values with ``values_only``.

    Bounds are 1-based and inclusive; each one left out defaults to the used range.
    """
    min_col = 1 if min_col is None else _coerce_column(min_col)
    max_col = self._max_column if max_col is None else _coerce_column(max_col)
    min_row = 1 if min_row is None else _coerce_row(min_row)
    max_row = self._max_row if max_row is None else _coerce_row(max_row)
    for col in range(min_col, max_col + 1):
        if values_only:
            yield tuple(self._value_at(row, col) for row in range(min_row, max_row + 1))
        else:
            yield tuple(self.cell(row, col) for row in range(min_row, max_row + 1))

merge_cells

merge_cells(range_string: str | None = None, start_row: int | None = None, start_column: int | None = None, end_row: int | None = None, end_column: int | None = None) -> None

Merge a range, given as text such as "A1:B2" or as four 1-based boundaries.

Source code in src/xlspy/workbook/_worksheet.py
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
def merge_cells(
    self,
    range_string: str | None = None,
    start_row: int | None = None,
    start_column: int | None = None,
    end_row: int | None = None,
    end_column: int | None = None,
) -> None:
    """Merge a range, given as text such as ``"A1:B2"`` or as four 1-based boundaries."""
    if range_string is None:
        if start_row is None or start_column is None or end_row is None or end_column is None:
            raise TypeError("merge_cells needs a range or all four boundaries")
        range_string = (
            f"{_coordinate(start_row, _coerce_column(start_column))}:"
            f"{_coordinate(end_row, _coerce_column(end_column))}"
        )
    reference = _normalize_range(range_string)
    existing = self._merged_cells.first_overlapping(parse_cell_range(reference))
    if existing is not None:
        raise ValueError(f"merge range {reference!r} overlaps {existing!r}")
    self._merged_cells.add(reference)
    # Excel keeps only the top-left value: a merged range's other cells are
    # removed, with their notes and links scheduled for deletion on save.
    c1, r1, c2, r2 = parse_cell_range(reference)
    for row in range(r1 + 1, r2 + 2):
        for column in range(c1 + 1, c2 + 2):
            if (row, column) == (r1 + 1, c1 + 1):
                continue
            hidden = self._existing_cell(row, column)
            if hidden is None:
                continue
            # Keep the cell for the save path so its old value can be
            # cleared from the package; notes and links are removed too.
            hidden._value = None
            hidden._formula = None
            hidden._data_type = "n"
            hidden._comment = None
            hidden._hyperlink = None
            self._dirty_cells.add((row, column))
            self._dirty_comments.add(hidden.coordinate)
            if self._threaded_comments.pop(hidden.coordinate, None) is not None:
                self._dirty_threaded_comments.add(hidden.coordinate)
            self._dirty_hyperlinks.add(hidden.coordinate)
    self._mark_dirty("merges")

unmerge_cells

unmerge_cells(range_string: str | None = None, start_row: int | None = None, start_column: int | None = None, end_row: int | None = None, end_column: int | None = None) -> None

Unmerge a range, given as text such as "A1:B2" or as four 1-based boundaries.

Source code in src/xlspy/workbook/_worksheet.py
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
def unmerge_cells(
    self,
    range_string: str | None = None,
    start_row: int | None = None,
    start_column: int | None = None,
    end_row: int | None = None,
    end_column: int | None = None,
) -> None:
    """Unmerge a range, given as text such as ``"A1:B2"`` or as four 1-based boundaries."""
    if range_string is None:
        if start_row is None or start_column is None or end_row is None or end_column is None:
            raise TypeError("unmerge_cells needs a range or all four boundaries")
        range_string = (
            f"{_coordinate(start_row, _coerce_column(start_column))}:"
            f"{_coordinate(end_row, _coerce_column(end_column))}"
        )
    self._merged_cells.remove(range_string)
    self._mark_dirty("merges")

ReadOnlyWorksheet

ReadOnlyWorksheet(workbook: Workbook, title: str, *, reader: ExcelReader, data_only: bool, index: int | None = None)

Bases: Worksheet

Streams rows on demand with openpyxl's read-only semantics.

Rows and columns use worksheet coordinates: rows missing from the file are yielded as empty rows and columns start at min_col (default 1). Bounds come from the stored dimension; without one, max_row and max_column are None and rows are as wide as their last cell.

Source code in src/xlspy/workbook/_reader.py
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
def __init__(
    self, workbook: Workbook, title: str, *, reader: ExcelReader, data_only: bool, index: int | None = None
) -> None:
    super().__init__(workbook, title, index=index)
    self._reader = reader
    self._data_only = data_only
    self._loaded = True
    self._min_row = self._min_column = 1
    # Unknown until the bounds are read; the class docstring says so.
    self._max_row = self._max_column = None  # type: ignore[assignment]

min_row property

min_row: int

The first row of the sheet's dimension.

min_column property

min_column: int

The first column of the sheet's dimension.

max_row property

max_row: int | None

The last row of the dimension stored in the file, or None when it stores none.

See calculate_dimension.

max_column property

max_column: int | None

The last column of the dimension stored in the file, or None when it stores none.

See calculate_dimension.

dimensions property

dimensions: str

The used range; raises ValueError when the file stores no dimension.

page_margins property writable

page_margins: WorksheetPageMargins

Page margins for printing, in inches.

protection property writable

protection: WorksheetProtection

Sheet protection settings.

parent property

parent: Workbook

The workbook that holds the sheet, as openpyxl names it.

encoding property

encoding: str

Always "utf-8", for openpyxl compatibility.

mime_type property

mime_type: str

The content type of a worksheet part.

path property

path: str

The worksheet part name, such as /xl/worksheets/sheet1.xml.

title property writable

title: str

The sheet name.

Setting it renames the sheet and points formulas, validations, conditional formats, internal links and defined names at the new name, as Excel does.

sheet_state property writable

sheet_state: str

"visible", "hidden" or "veryHidden".

merged_cells property

merged_cells: MultiCellRange

The merged ranges of the sheet.

merged_cell_ranges property

merged_cell_ranges: list[str]

A copy of the merged range strings, as openpyxl's deprecated alias.

array_formulae property

array_formulae: dict[str, str]

Array formula anchors and the range each one fills, as openpyxl maps them.

column_groups property

column_groups: list[str]

The column ranges that span more than one column, such as "A:C".

column_dimensions property

column_dimensions: DimensionHolder

Column widths, visibility and outline levels, keyed by column letter.

Looking up a column that has no entry creates one.

row_dimensions property

row_dimensions: DimensionHolder

Row heights, visibility and outline levels, keyed by 1-based row number.

Looking up a row that has no entry creates one.

freeze_panes property writable

freeze_panes: str | None

The top-left cell of the scrolling pane, or None.

"B2" freezes row 1 and column A. Read from sheet_view.pane, as openpyxl does, so a pane set through the view is visible here.

auto_filter property writable

auto_filter: AutoFilter

The sheet's AutoFilter: its range, filter columns and sort state.

sheet_properties property

sheet_properties: SheetProperties

Sheet properties such as the tab colour and outline settings.

sheet_view property

sheet_view: SheetView

The first sheet view: zoom, grid lines, selection and panes.

views property

views: SheetViewList

Every sheet view, as openpyxl's ws.views.

defined_names property

defined_names: MutableMapping[str, Any]

The defined names scoped to this sheet, keyed by name, as openpyxl's map.

Assigning an entry stores it on the workbook with this sheet as its scope, so it is written on save. Deleting one removes only this sheet's entry.

scenarios property writable

scenarios: Any

The sheet's scenarios: always None, because xlspy preserves but does not model them.

openpyxl reports an empty ScenarioList on a sheet without scenarios.

legacy_drawing property

legacy_drawing: str | None

The relationship id of the sheet's legacy VML drawing.

Always None: the loaders preserve the part but do not expose its id, so this is a placeholder for openpyxl's attribute.

active_cell property

active_cell: str | None

The active cell of the first selection, or None when the view has none.

selected_cell property

selected_cell: str | None

The selected range of the first selection, or None when the view has none.

show_gridlines property writable

show_gridlines: bool | None

Whether the sheet view shows grid lines; None leaves Excel's default.

rows property

rows: Iterator[tuple[Cell, ...]]

The rows of the used range as tuples of cells (see iter_rows).

columns property

columns: Iterator[tuple[Cell, ...]]

The columns of the used range as tuples of cells (see iter_cols).

values property

values: Iterator[tuple[Any, ...]]

The rows of the used range as tuples of values.

data_validations property

data_validations: DataValidationList

The sheet's data validation rules.

tables property

tables: TableList

The sheet's tables; a table name also works as a lookup key.

charts property

charts: list[Chart]

The charts on the sheet, new and loaded.

images property

images: list[Image]

The images on the sheet.

conditional_formatting property

conditional_formatting: ConditionalFormattingList

The sheet's conditional formatting, grouped by range.

oddHeader property

oddHeader: HeaderFooterItem

The header of odd pages (all pages unless odd and even pages differ).

oddFooter property

oddFooter: HeaderFooterItem

The footer of odd pages (all pages unless odd and even pages differ).

evenHeader property

evenHeader: HeaderFooterItem

The header of even pages, when odd and even pages differ.

evenFooter property

evenFooter: HeaderFooterItem

The footer of even pages, when odd and even pages differ.

firstHeader property

firstHeader: HeaderFooterItem

The header of the first page, when the first page differs.

firstFooter property

firstFooter: HeaderFooterItem

The footer of the first page, when the first page differs.

print_area property writable

print_area: str | None

The print area as a range string, or None.

print_title_rows property writable

print_title_rows: str | None

Rows repeated at the top of every printed page, such as "1:2".

print_title_cols property writable

print_title_cols: str | None

Columns repeated at the left of every printed page, such as "A:B".

print_titles property

print_titles: str

The print titles as openpyxl formats them, e.g. 'Sheet'!$1:$2.

calculate_dimension

calculate_dimension(force: bool = False) -> str

Return the used range.

A sheet whose file stores no dimension raises ValueError, unless force=True scans its rows to find the range.

Source code in src/xlspy/workbook/_reader.py
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
def calculate_dimension(self, force: bool = False) -> str:
    """Return the used range.

    A sheet whose file stores no dimension raises ValueError, unless ``force=True``
    scans its rows to find the range.
    """
    if not (self._max_row and self._max_column):
        if not force:
            raise ValueError("Worksheet is unsized, use calculate_dimension(force=True)")
        self._calculate_dimension()
    return f"{_coordinate(self._min_row, self._min_column)}:{_coordinate(self._max_row, self._max_column)}"

reset_dimensions

reset_dimensions() -> None

Ignore a wrong stored dimension, as openpyxl's reset_dimensions().

Source code in src/xlspy/workbook/_reader.py
1521
1522
1523
def reset_dimensions(self) -> None:
    """Ignore a wrong stored dimension, as openpyxl's reset_dimensions()."""
    self._max_row = self._max_column = None  # type: ignore[assignment]  # unknown until the bounds are read

iter_rows

iter_rows(min_row: int | None = None, max_row: int | None = None, min_col: int | str | None = None, max_col: int | str | None = None, values_only: Literal[False] = False) -> Iterator[tuple[Any, ...]]
iter_rows(min_row: int | None = None, max_row: int | None = None, min_col: int | str | None = None, max_col: int | str | None = None, *, values_only: Literal[True]) -> Iterator[tuple[Any, ...]]
iter_rows(min_row: int | None = None, max_row: int | None = None, min_col: int | str | None = None, max_col: int | str | None = None, values_only: bool = False) -> Iterator[tuple[Any, ...]]
iter_rows(min_row: int | None = None, max_row: int | None = None, min_col: int | str | None = None, max_col: int | str | None = None, values_only: bool = False) -> Iterator[tuple[Any, ...]]

Stream the rows of a range as tuples of read-only cells, or of values with values_only.

Rows missing from the file come back empty.

Source code in src/xlspy/workbook/_reader.py
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
def iter_rows(
    self,
    min_row: int | None = None,
    max_row: int | None = None,
    min_col: int | str | None = None,
    max_col: int | str | None = None,
    values_only: bool = False,
) -> Iterator[tuple[Any, ...]]:
    """Stream the rows of a range as tuples of read-only cells, or of values with
    ``values_only``.

    Rows missing from the file come back empty.
    """
    min_col = _coerce_column(min_col) if min_col else 1
    min_row = int(min_row) if min_row else 1
    max_col = (_coerce_column(max_col) if max_col else None) or self._max_column
    max_row = int(max_row) if max_row else self._max_row
    return self._cells_by_row(min_col, min_row, max_col, max_row, values_only)

iter_cols

iter_cols(*args: Any, **kwargs: Any) -> NoReturn

Not available in read-only mode: raises AttributeError.

Source code in src/xlspy/workbook/_reader.py
1624
1625
1626
def iter_cols(self, *args: Any, **kwargs: Any) -> NoReturn:
    """Not available in read-only mode: raises AttributeError."""
    raise AttributeError("iter_cols is not available in read-only mode")

cell

cell(row: int, column: int | str, value: Any = None) -> ReadOnlyCell | EmptyCell

Return the read-only cell at row and column, or an empty cell.

Each call scans the sheet; use iter_rows to read many cells.

Source code in src/xlspy/workbook/_reader.py
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
def cell(  # type: ignore[override]  # read-only cells
    self,
    row: int,
    column: int | str,
    value: Any = None,
) -> ReadOnlyCell | EmptyCell:
    """Return the read-only cell at ``row`` and ``column``, or an empty cell.

    Each call scans the sheet; use ``iter_rows`` to read many cells.
    """
    if value is not None:
        raise AttributeError("read-only worksheets cannot be modified")
    column = _coerce_column(column)
    for cells in self._cells_by_row(column, int(row), column, int(row), False):
        if cells:
            first: ReadOnlyCell | EmptyCell = cells[0]
            return first
    return EMPTY_CELL

append

append(iterable: Iterable[Any]) -> NoReturn

Not available: read-only worksheets cannot be modified.

Source code in src/xlspy/workbook/_reader.py
1692
1693
1694
def append(self, iterable: Iterable[Any]) -> NoReturn:
    """Not available: read-only worksheets cannot be modified."""
    raise AttributeError("read-only worksheets cannot be modified")

insert_rows

insert_rows(idx: int, amount: int = 1) -> None

Insert amount empty rows before row idx.

Source code in src/xlspy/workbook/_worksheet.py
568
569
570
def insert_rows(self, idx: int, amount: int = 1) -> None:
    """Insert ``amount`` empty rows before row ``idx``."""
    _shift.shift_rows(self, idx, amount, delete=False)

delete_rows

delete_rows(idx: int, amount: int = 1) -> None

Delete amount rows starting at row idx; the rows below move up.

Source code in src/xlspy/workbook/_worksheet.py
572
573
574
def delete_rows(self, idx: int, amount: int = 1) -> None:
    """Delete ``amount`` rows starting at row ``idx``; the rows below move up."""
    _shift.shift_rows(self, idx, amount, delete=True)

insert_cols

insert_cols(idx: int, amount: int = 1) -> None

Insert amount empty columns before column idx (1-based).

Source code in src/xlspy/workbook/_worksheet.py
576
577
578
def insert_cols(self, idx: int, amount: int = 1) -> None:
    """Insert ``amount`` empty columns before column ``idx`` (1-based)."""
    _shift.shift_cols(self, idx, amount, delete=False)

delete_cols

delete_cols(idx: int, amount: int = 1) -> None

Delete amount columns starting at column idx; the rest move left.

Source code in src/xlspy/workbook/_worksheet.py
580
581
582
def delete_cols(self, idx: int, amount: int = 1) -> None:
    """Delete ``amount`` columns starting at column ``idx``; the rest move left."""
    _shift.shift_cols(self, idx, amount, delete=True)

move_range

move_range(cell_range: str, rows: int = 0, cols: int = 0, translate: bool = False) -> None

Move the cells of cell_range; cells at the destination are replaced. translate=True shifts the relative references of moved formulas.

Source code in src/xlspy/workbook/_worksheet.py
584
585
586
587
def move_range(self, cell_range: str, rows: int = 0, cols: int = 0, translate: bool = False) -> None:
    """Move the cells of ``cell_range``; cells at the destination are replaced.
    ``translate=True`` shifts the relative references of moved formulas."""
    _shift.move_range(self, cell_range, rows, cols, translate)

add_chart

add_chart(chart: Chart, anchor: str | None = None) -> None

Place chart on the sheet, at anchor (a cell such as "E2") when given.

Source code in src/xlspy/workbook/_worksheet.py
590
591
592
593
594
595
def add_chart(self, chart: Chart, anchor: str | None = None) -> None:
    """Place ``chart`` on the sheet, at ``anchor`` (a cell such as ``"E2"``) when given."""
    _expect(chart, Chart, "chart", "an xlspy Chart")
    if anchor is not None:
        chart = replace(chart, anchor=anchor)
    self._charts.append(chart)

add_image

add_image(img: Image, anchor: str | None = None) -> None

Place img on the sheet, at anchor (a cell such as "E2") when given.

Source code in src/xlspy/workbook/_worksheet.py
597
598
599
600
601
602
603
def add_image(self, img: Image, anchor: str | None = None) -> None:
    """Place ``img`` on the sheet, at ``anchor`` (a cell such as ``"E2"``) when given."""
    _expect(img, Image, "image", "an xlspy Image")
    if anchor is not None:
        # The bytes already read: a file object source is used up.
        img = replace(img, path=img.data, anchor=anchor)
    self._images.append(img)

add_table

add_table(table: ExcelTable | Table) -> None

Add a table: an ExcelTable or an openpyxl-style Table.

Source code in src/xlspy/workbook/_worksheet.py
605
606
607
608
def add_table(self, table: ExcelTable | Table) -> None:
    """Add a table: an ``ExcelTable`` or an openpyxl-style ``Table``."""
    _expect(table, (ExcelTable, Table), "table", "an xlspy ExcelTable or Table")
    self._tables.append(table)

add_data_validation

add_data_validation(data_validation: DataValidation) -> None

Add a data validation rule.

Source code in src/xlspy/workbook/_worksheet.py
610
611
612
613
def add_data_validation(self, data_validation: DataValidation) -> None:
    """Add a data validation rule."""
    _expect(data_validation, DataValidation, "data_validation", "an xlspy DataValidation")
    self._data_validations.append(data_validation)

merge_cells

merge_cells(range_string: str | None = None, start_row: int | None = None, start_column: int | None = None, end_row: int | None = None, end_column: int | None = None) -> None

Merge a range, given as text such as "A1:B2" or as four 1-based boundaries.

Source code in src/xlspy/workbook/_worksheet.py
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
def merge_cells(
    self,
    range_string: str | None = None,
    start_row: int | None = None,
    start_column: int | None = None,
    end_row: int | None = None,
    end_column: int | None = None,
) -> None:
    """Merge a range, given as text such as ``"A1:B2"`` or as four 1-based boundaries."""
    if range_string is None:
        if start_row is None or start_column is None or end_row is None or end_column is None:
            raise TypeError("merge_cells needs a range or all four boundaries")
        range_string = (
            f"{_coordinate(start_row, _coerce_column(start_column))}:"
            f"{_coordinate(end_row, _coerce_column(end_column))}"
        )
    reference = _normalize_range(range_string)
    existing = self._merged_cells.first_overlapping(parse_cell_range(reference))
    if existing is not None:
        raise ValueError(f"merge range {reference!r} overlaps {existing!r}")
    self._merged_cells.add(reference)
    # Excel keeps only the top-left value: a merged range's other cells are
    # removed, with their notes and links scheduled for deletion on save.
    c1, r1, c2, r2 = parse_cell_range(reference)
    for row in range(r1 + 1, r2 + 2):
        for column in range(c1 + 1, c2 + 2):
            if (row, column) == (r1 + 1, c1 + 1):
                continue
            hidden = self._existing_cell(row, column)
            if hidden is None:
                continue
            # Keep the cell for the save path so its old value can be
            # cleared from the package; notes and links are removed too.
            hidden._value = None
            hidden._formula = None
            hidden._data_type = "n"
            hidden._comment = None
            hidden._hyperlink = None
            self._dirty_cells.add((row, column))
            self._dirty_comments.add(hidden.coordinate)
            if self._threaded_comments.pop(hidden.coordinate, None) is not None:
                self._dirty_threaded_comments.add(hidden.coordinate)
            self._dirty_hyperlinks.add(hidden.coordinate)
    self._mark_dirty("merges")

unmerge_cells

unmerge_cells(range_string: str | None = None, start_row: int | None = None, start_column: int | None = None, end_row: int | None = None, end_column: int | None = None) -> None

Unmerge a range, given as text such as "A1:B2" or as four 1-based boundaries.

Source code in src/xlspy/workbook/_worksheet.py
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
def unmerge_cells(
    self,
    range_string: str | None = None,
    start_row: int | None = None,
    start_column: int | None = None,
    end_row: int | None = None,
    end_column: int | None = None,
) -> None:
    """Unmerge a range, given as text such as ``"A1:B2"`` or as four 1-based boundaries."""
    if range_string is None:
        if start_row is None or start_column is None or end_row is None or end_column is None:
            raise TypeError("unmerge_cells needs a range or all four boundaries")
        range_string = (
            f"{_coordinate(start_row, _coerce_column(start_column))}:"
            f"{_coordinate(end_row, _coerce_column(end_column))}"
        )
    self._merged_cells.remove(range_string)
    self._mark_dirty("merges")

WriteOnlyWorksheet

WriteOnlyWorksheet(workbook: Workbook, title: str, *, index: int | None = None)

Bases: Worksheet

Streaming-friendly sheet that stores rows rather than Cell objects.

Source code in src/xlspy/workbook/_worksheet.py
1106
1107
1108
1109
1110
1111
def __init__(self, workbook: Workbook, title: str, *, index: int | None = None) -> None:
    super().__init__(workbook, title, index=index)
    self._rows: list[list[Any]] = []
    # Per row, the columns whose WriteOnlyCell carried a style; the writer
    # turns them into (value, Style) cells.
    self._row_styles: list[dict[int, Style]] = []

page_margins property writable

page_margins: WorksheetPageMargins

Page margins for printing, in inches.

protection property writable

protection: WorksheetProtection

Sheet protection settings.

parent property

parent: Workbook

The workbook that holds the sheet, as openpyxl names it.

encoding property

encoding: str

Always "utf-8", for openpyxl compatibility.

mime_type property

mime_type: str

The content type of a worksheet part.

path property

path: str

The worksheet part name, such as /xl/worksheets/sheet1.xml.

title property writable

title: str

The sheet name.

Setting it renames the sheet and points formulas, validations, conditional formats, internal links and defined names at the new name, as Excel does.

sheet_state property writable

sheet_state: str

"visible", "hidden" or "veryHidden".

merged_cells property

merged_cells: MultiCellRange

The merged ranges of the sheet.

merged_cell_ranges property

merged_cell_ranges: list[str]

A copy of the merged range strings, as openpyxl's deprecated alias.

array_formulae property

array_formulae: dict[str, str]

Array formula anchors and the range each one fills, as openpyxl maps them.

column_groups property

column_groups: list[str]

The column ranges that span more than one column, such as "A:C".

column_dimensions property

column_dimensions: DimensionHolder

Column widths, visibility and outline levels, keyed by column letter.

Looking up a column that has no entry creates one.

row_dimensions property

row_dimensions: DimensionHolder

Row heights, visibility and outline levels, keyed by 1-based row number.

Looking up a row that has no entry creates one.

freeze_panes property writable

freeze_panes: str | None

The top-left cell of the scrolling pane, or None.

"B2" freezes row 1 and column A. Read from sheet_view.pane, as openpyxl does, so a pane set through the view is visible here.

auto_filter property writable

auto_filter: AutoFilter

The sheet's AutoFilter: its range, filter columns and sort state.

sheet_properties property

sheet_properties: SheetProperties

Sheet properties such as the tab colour and outline settings.

sheet_view property

sheet_view: SheetView

The first sheet view: zoom, grid lines, selection and panes.

views property

views: SheetViewList

Every sheet view, as openpyxl's ws.views.

defined_names property

defined_names: MutableMapping[str, Any]

The defined names scoped to this sheet, keyed by name, as openpyxl's map.

Assigning an entry stores it on the workbook with this sheet as its scope, so it is written on save. Deleting one removes only this sheet's entry.

scenarios property writable

scenarios: Any

The sheet's scenarios: always None, because xlspy preserves but does not model them.

openpyxl reports an empty ScenarioList on a sheet without scenarios.

legacy_drawing property

legacy_drawing: str | None

The relationship id of the sheet's legacy VML drawing.

Always None: the loaders preserve the part but do not expose its id, so this is a placeholder for openpyxl's attribute.

active_cell property

active_cell: str | None

The active cell of the first selection, or None when the view has none.

selected_cell property

selected_cell: str | None

The selected range of the first selection, or None when the view has none.

show_gridlines property writable

show_gridlines: bool | None

Whether the sheet view shows grid lines; None leaves Excel's default.

max_row property

max_row: int

The last row that holds a cell; 0 for an empty sheet.

max_column property

max_column: int

The last column that holds a cell; 0 for an empty sheet.

min_row property

min_row: int

Always 1: the used range is reported from A1, as openpyxl does for new sheets.

min_column property

min_column: int

Always 1: the used range is reported from A1, as openpyxl does for new sheets.

dimensions property

dimensions: str

The used range from A1, such as "A1:D20"; "A1:A1" for an empty sheet.

rows property

rows: Iterator[tuple[Cell, ...]]

The rows of the used range as tuples of cells (see iter_rows).

columns property

columns: Iterator[tuple[Cell, ...]]

The columns of the used range as tuples of cells (see iter_cols).

values property

values: Iterator[tuple[Any, ...]]

The rows of the used range as tuples of values.

data_validations property

data_validations: DataValidationList

The sheet's data validation rules.

tables property

tables: TableList

The sheet's tables; a table name also works as a lookup key.

charts property

charts: list[Chart]

The charts on the sheet, new and loaded.

images property

images: list[Image]

The images on the sheet.

conditional_formatting property

conditional_formatting: ConditionalFormattingList

The sheet's conditional formatting, grouped by range.

oddHeader property

oddHeader: HeaderFooterItem

The header of odd pages (all pages unless odd and even pages differ).

oddFooter property

oddFooter: HeaderFooterItem

The footer of odd pages (all pages unless odd and even pages differ).

evenHeader property

evenHeader: HeaderFooterItem

The header of even pages, when odd and even pages differ.

evenFooter property

evenFooter: HeaderFooterItem

The footer of even pages, when odd and even pages differ.

firstHeader property

firstHeader: HeaderFooterItem

The header of the first page, when the first page differs.

firstFooter property

firstFooter: HeaderFooterItem

The footer of the first page, when the first page differs.

print_area property writable

print_area: str | None

The print area as a range string, or None.

print_title_rows property writable

print_title_rows: str | None

Rows repeated at the top of every printed page, such as "1:2".

print_title_cols property writable

print_title_cols: str | None

Columns repeated at the left of every printed page, such as "A:B".

print_titles property

print_titles: str

The print titles as openpyxl formats them, e.g. 'Sheet'!$1:$2.

append

append(iterable: Iterable[Any]) -> int

Queue a row for writing and return its row number.

A mapping places its values by column letter or 1-based column number. A WriteOnlyCell contributes its value and, when it has one, its style; the writer then writes the cell with that style.

Source code in src/xlspy/workbook/_worksheet.py
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
def append(self, iterable: Iterable[Any]) -> int:
    """Queue a row for writing and return its row number.

    A mapping places its values by column letter or 1-based column number.
    A ``WriteOnlyCell`` contributes its value and, when it has one, its
    style; the writer then writes the cell with that style.
    """
    styles: dict[int, Style] = {}
    if isinstance(iterable, Mapping):
        entries = []
        for key, value in iterable.items():
            if isinstance(key, str):
                column = _coerce_column(key)
            elif isinstance(key, int) and not isinstance(key, bool):
                if not 1 <= key <= 16384:
                    raise ValueError("column index must be 1..16384")
                column = key
            else:
                raise TypeError("dict keys must be column letters or 1-based ints")
            if isinstance(value, WriteOnlyCell):
                style = _write_only_style(value)
                if style is not None:
                    styles[column - 1] = style
                value = value.value
            entries.append((column, value))
        row = [None] * (max((column for column, _ in entries), default=0))
        for column, value in entries:
            row[column - 1] = value
        self._rows.append(row)
    else:
        if isinstance(iterable, (str, bytes, bytearray)):
            raise TypeError("a row must be an iterable of cells, not text")
        values = []
        for column, value in enumerate(iterable):
            if isinstance(value, WriteOnlyCell):
                style = _write_only_style(value)
                if style is not None:
                    styles[column] = style
                value = value.value
            values.append(value)
        self._rows.append(values)
    self._row_styles.append(styles)
    self._max_row = len(self._rows)
    self._max_column = max((len(row) for row in self._rows), default=0)
    self._mark_dirty("rows")
    return self._max_row

cell

cell(row: int, column: int | str, value: Any = None) -> Cell

Not available in write-only mode: raises ValueError. Use append.

Source code in src/xlspy/workbook/_worksheet.py
1160
1161
1162
def cell(self, row: int, column: int | str, value: Any = None) -> Cell:
    """Not available in write-only mode: raises ValueError. Use ``append``."""
    raise ValueError("cannot access a cell in a write-only worksheet; use append()")

iter_rows

iter_rows(*args: Any, **kwargs: Any) -> Iterator[tuple[Any, ...]]

Yield the queued rows as tuples of values; only values_only=True is supported.

Source code in src/xlspy/workbook/_worksheet.py
1164
1165
1166
1167
1168
1169
1170
def iter_rows(self, *args: Any, **kwargs: Any) -> Iterator[tuple[Any, ...]]:
    """Yield the queued rows as tuples of values; only ``values_only=True`` is supported."""
    for row in self._rows:
        if kwargs.get("values_only"):
            yield tuple(row)
        else:
            raise ValueError("write-only worksheets only support values_only rows")

calculate_dimension

calculate_dimension(force: bool = False) -> str

Return dimensions. force is accepted for openpyxl compatibility.

Source code in src/xlspy/workbook/_worksheet.py
451
452
453
def calculate_dimension(self, force: bool = False) -> str:
    """Return ``dimensions``. ``force`` is accepted for openpyxl compatibility."""
    return self.dimensions

insert_rows

insert_rows(idx: int, amount: int = 1) -> None

Insert amount empty rows before row idx.

Source code in src/xlspy/workbook/_worksheet.py
568
569
570
def insert_rows(self, idx: int, amount: int = 1) -> None:
    """Insert ``amount`` empty rows before row ``idx``."""
    _shift.shift_rows(self, idx, amount, delete=False)

delete_rows

delete_rows(idx: int, amount: int = 1) -> None

Delete amount rows starting at row idx; the rows below move up.

Source code in src/xlspy/workbook/_worksheet.py
572
573
574
def delete_rows(self, idx: int, amount: int = 1) -> None:
    """Delete ``amount`` rows starting at row ``idx``; the rows below move up."""
    _shift.shift_rows(self, idx, amount, delete=True)

insert_cols

insert_cols(idx: int, amount: int = 1) -> None

Insert amount empty columns before column idx (1-based).

Source code in src/xlspy/workbook/_worksheet.py
576
577
578
def insert_cols(self, idx: int, amount: int = 1) -> None:
    """Insert ``amount`` empty columns before column ``idx`` (1-based)."""
    _shift.shift_cols(self, idx, amount, delete=False)

delete_cols

delete_cols(idx: int, amount: int = 1) -> None

Delete amount columns starting at column idx; the rest move left.

Source code in src/xlspy/workbook/_worksheet.py
580
581
582
def delete_cols(self, idx: int, amount: int = 1) -> None:
    """Delete ``amount`` columns starting at column ``idx``; the rest move left."""
    _shift.shift_cols(self, idx, amount, delete=True)

move_range

move_range(cell_range: str, rows: int = 0, cols: int = 0, translate: bool = False) -> None

Move the cells of cell_range; cells at the destination are replaced. translate=True shifts the relative references of moved formulas.

Source code in src/xlspy/workbook/_worksheet.py
584
585
586
587
def move_range(self, cell_range: str, rows: int = 0, cols: int = 0, translate: bool = False) -> None:
    """Move the cells of ``cell_range``; cells at the destination are replaced.
    ``translate=True`` shifts the relative references of moved formulas."""
    _shift.move_range(self, cell_range, rows, cols, translate)

add_chart

add_chart(chart: Chart, anchor: str | None = None) -> None

Place chart on the sheet, at anchor (a cell such as "E2") when given.

Source code in src/xlspy/workbook/_worksheet.py
590
591
592
593
594
595
def add_chart(self, chart: Chart, anchor: str | None = None) -> None:
    """Place ``chart`` on the sheet, at ``anchor`` (a cell such as ``"E2"``) when given."""
    _expect(chart, Chart, "chart", "an xlspy Chart")
    if anchor is not None:
        chart = replace(chart, anchor=anchor)
    self._charts.append(chart)

add_image

add_image(img: Image, anchor: str | None = None) -> None

Place img on the sheet, at anchor (a cell such as "E2") when given.

Source code in src/xlspy/workbook/_worksheet.py
597
598
599
600
601
602
603
def add_image(self, img: Image, anchor: str | None = None) -> None:
    """Place ``img`` on the sheet, at ``anchor`` (a cell such as ``"E2"``) when given."""
    _expect(img, Image, "image", "an xlspy Image")
    if anchor is not None:
        # The bytes already read: a file object source is used up.
        img = replace(img, path=img.data, anchor=anchor)
    self._images.append(img)

add_table

add_table(table: ExcelTable | Table) -> None

Add a table: an ExcelTable or an openpyxl-style Table.

Source code in src/xlspy/workbook/_worksheet.py
605
606
607
608
def add_table(self, table: ExcelTable | Table) -> None:
    """Add a table: an ``ExcelTable`` or an openpyxl-style ``Table``."""
    _expect(table, (ExcelTable, Table), "table", "an xlspy ExcelTable or Table")
    self._tables.append(table)

add_data_validation

add_data_validation(data_validation: DataValidation) -> None

Add a data validation rule.

Source code in src/xlspy/workbook/_worksheet.py
610
611
612
613
def add_data_validation(self, data_validation: DataValidation) -> None:
    """Add a data validation rule."""
    _expect(data_validation, DataValidation, "data_validation", "an xlspy DataValidation")
    self._data_validations.append(data_validation)

iter_cols

iter_cols(min_col: int | None = None, max_col: int | None = None, min_row: int | None = None, max_row: int | None = None, values_only: Literal[False] = False) -> Iterator[tuple[Cell, ...]]
iter_cols(min_col: int | None = None, max_col: int | None = None, min_row: int | None = None, max_row: int | None = None, *, values_only: Literal[True]) -> Iterator[tuple[Any, ...]]
iter_cols(min_col: int | None = None, max_col: int | None = None, min_row: int | None = None, max_row: int | None = None, values_only: bool = False) -> Iterator[tuple[Any, ...]]
iter_cols(min_col: int | None = None, max_col: int | None = None, min_row: int | None = None, max_row: int | None = None, values_only: bool = False) -> Iterator[tuple[Any, ...]]

Yield the columns of a range as tuples of cells, or of values with values_only.

Bounds are 1-based and inclusive; each one left out defaults to the used range.

Source code in src/xlspy/workbook/_worksheet.py
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
def iter_cols(
    self,
    min_col: int | None = None,
    max_col: int | None = None,
    min_row: int | None = None,
    max_row: int | None = None,
    values_only: bool = False,
) -> Iterator[tuple[Any, ...]]:
    """Yield the columns of a range as tuples of cells, or of values with ``values_only``.

    Bounds are 1-based and inclusive; each one left out defaults to the used range.
    """
    min_col = 1 if min_col is None else _coerce_column(min_col)
    max_col = self._max_column if max_col is None else _coerce_column(max_col)
    min_row = 1 if min_row is None else _coerce_row(min_row)
    max_row = self._max_row if max_row is None else _coerce_row(max_row)
    for col in range(min_col, max_col + 1):
        if values_only:
            yield tuple(self._value_at(row, col) for row in range(min_row, max_row + 1))
        else:
            yield tuple(self.cell(row, col) for row in range(min_row, max_row + 1))

merge_cells

merge_cells(range_string: str | None = None, start_row: int | None = None, start_column: int | None = None, end_row: int | None = None, end_column: int | None = None) -> None

Merge a range, given as text such as "A1:B2" or as four 1-based boundaries.

Source code in src/xlspy/workbook/_worksheet.py
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
def merge_cells(
    self,
    range_string: str | None = None,
    start_row: int | None = None,
    start_column: int | None = None,
    end_row: int | None = None,
    end_column: int | None = None,
) -> None:
    """Merge a range, given as text such as ``"A1:B2"`` or as four 1-based boundaries."""
    if range_string is None:
        if start_row is None or start_column is None or end_row is None or end_column is None:
            raise TypeError("merge_cells needs a range or all four boundaries")
        range_string = (
            f"{_coordinate(start_row, _coerce_column(start_column))}:"
            f"{_coordinate(end_row, _coerce_column(end_column))}"
        )
    reference = _normalize_range(range_string)
    existing = self._merged_cells.first_overlapping(parse_cell_range(reference))
    if existing is not None:
        raise ValueError(f"merge range {reference!r} overlaps {existing!r}")
    self._merged_cells.add(reference)
    # Excel keeps only the top-left value: a merged range's other cells are
    # removed, with their notes and links scheduled for deletion on save.
    c1, r1, c2, r2 = parse_cell_range(reference)
    for row in range(r1 + 1, r2 + 2):
        for column in range(c1 + 1, c2 + 2):
            if (row, column) == (r1 + 1, c1 + 1):
                continue
            hidden = self._existing_cell(row, column)
            if hidden is None:
                continue
            # Keep the cell for the save path so its old value can be
            # cleared from the package; notes and links are removed too.
            hidden._value = None
            hidden._formula = None
            hidden._data_type = "n"
            hidden._comment = None
            hidden._hyperlink = None
            self._dirty_cells.add((row, column))
            self._dirty_comments.add(hidden.coordinate)
            if self._threaded_comments.pop(hidden.coordinate, None) is not None:
                self._dirty_threaded_comments.add(hidden.coordinate)
            self._dirty_hyperlinks.add(hidden.coordinate)
    self._mark_dirty("merges")

unmerge_cells

unmerge_cells(range_string: str | None = None, start_row: int | None = None, start_column: int | None = None, end_row: int | None = None, end_column: int | None = None) -> None

Unmerge a range, given as text such as "A1:B2" or as four 1-based boundaries.

Source code in src/xlspy/workbook/_worksheet.py
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
def unmerge_cells(
    self,
    range_string: str | None = None,
    start_row: int | None = None,
    start_column: int | None = None,
    end_row: int | None = None,
    end_column: int | None = None,
) -> None:
    """Unmerge a range, given as text such as ``"A1:B2"`` or as four 1-based boundaries."""
    if range_string is None:
        if start_row is None or start_column is None or end_row is None or end_column is None:
            raise TypeError("unmerge_cells needs a range or all four boundaries")
        range_string = (
            f"{_coordinate(start_row, _coerce_column(start_column))}:"
            f"{_coordinate(end_row, _coerce_column(end_column))}"
        )
    self._merged_cells.remove(range_string)
    self._mark_dirty("merges")

Chartsheet

Chartsheet(workbook: Workbook, title: str, index: int | None = None)

A chartsheet: a sheet that shows one chart.

A new chartsheet's chart reads its ranges from source (a worksheet or its title; by default the workbook's first worksheet).

Source code in src/xlspy/workbook/_worksheet.py
1180
1181
1182
1183
1184
1185
1186
1187
def __init__(self, workbook: Workbook, title: str, index: int | None = None) -> None:
    self._workbook = workbook
    self._title = title  # the caller checks the name
    self.sheet_state = "visible"
    self._index = index
    self._charts: list[Chart] = []
    self._part: str | None = None  # the package part, once in a file
    self._source: Worksheet | str | None = None

title property writable

title: str

The sheet name. A loaded chartsheet cannot be renamed.

charts property

charts: list[Chart]

The chart of the sheet, as a list of at most one for a new chartsheet.

add_chart

add_chart(chart: Chart, source: Worksheet | str | None = None) -> None

Set the chart of a new chartsheet.

A chartsheet holds one chart; it reads its ranges from source (a worksheet or its title; by default the workbook's first worksheet).

Source code in src/xlspy/workbook/_worksheet.py
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
def add_chart(self, chart: Chart, source: Worksheet | str | None = None) -> None:
    """Set the chart of a new chartsheet.

    A chartsheet holds one chart; it reads its ranges from ``source`` (a worksheet or its
    title; by default the workbook's first worksheet).
    """
    if self._part is None:
        _expect(chart, Chart, "chart", "an xlspy Chart")
        if self._charts:
            raise ValueError("a chartsheet holds one chart")
        if source is not None:
            self._source = source
    self._charts.append(chart)

Cell

Cell(sheet: Worksheet, row: int, column: int, value: Any = None, style_id: int = 0)

One cell of a worksheet: its value, formula, style, note and hyperlink.

Get cells from the worksheet (ws["A1"], Worksheet.cell); they are not created directly.

Source code in src/xlspy/workbook/_cell.py
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(self, sheet: Worksheet, row: int, column: int, value: Any = None, style_id: int = 0) -> None:
    self._sheet = sheet
    self._row = _coerce_row(row)
    self._column = _coerce_column(column)
    self._value: Any = None
    self._formula: Formula | ArrayFormula | DataTableFormula | str | None = None
    self._data_type = "n"
    self._style_id = int(style_id)
    self._comment: Comment | None = None
    self._hyperlink: Hyperlink | None = None
    self._named_style: str | None = None
    if value is not None:
        self.value = value

row property

row: int

The 1-based row number.

column property

column: int

The 1-based column number.

column_letter property

column_letter: str

The column letter, such as "C".

col_idx property

col_idx: int

The 1-based column number, as openpyxl names it.

coordinate property

coordinate: str

The cell reference, such as "C5".

parent property

parent: Worksheet

The worksheet that holds the cell.

value property writable

value: Any

The cell value; a scalar formula reads back as "=..." text.

An ArrayFormula or DataTableFormula reads back as that object, as in openpyxl. Assigning text that starts with = or a Formula sets a formula; an ArrayFormula or DataTableFormula sets that formula object, and a Hyperlink sets the link and shows its text; any other value keeps the cell's link, as in Excel (hyperlink = None removes it). A date, time or timedelta gets a default number format when the cell's format is General.

formula property

formula: Formula | ArrayFormula | DataTableFormula | str | None

The formula object or text without its leading =, or None.

data_type property

data_type: str

openpyxl's type code: n number or empty, s text, b boolean, d date or time, f formula, e error.

internal_value property

internal_value: Any

The stored value; None for a formula cell that holds no cached result.

is_date property

is_date: bool

True when the value is a date, datetime, time or timedelta.

encoding property

encoding: str

Always "utf-8", for openpyxl compatibility.

base_date property

base_date: datetime

The workbook's epoch, the base date of serial date numbers (1899-12-30).

hyperlink: Hyperlink | None

The cell's Hyperlink, or None.

comment property writable

comment: Comment | None

The cell's note (a Comment), or None.

threaded_comment property writable

threaded_comment: ThreadedComment | None

The cell's Excel 365 conversation, or None.

Assigning a ThreadedComment starts a conversation; assigning None removes the whole conversation, replies included.

style_id property

style_id: int

The index of the cell's style in the workbook's style table.

has_style property

has_style: bool

True when the cell has a style other than the workbook default.

font property writable

font: Font | None

The cell font, or None when its style sets no font.

Assigning one replaces the font of the cell's style.

fill property writable

fill: str | PatternFill | GradientFill

The cell fill: a colour, a PatternFill or a GradientFill.

A cell without a fill reports openpyxl's empty pattern fill.

border property writable

border: Border

The cell border; a cell without one reports openpyxl's empty border.

alignment property writable

alignment: Alignment

The cell alignment; a cell without one reports openpyxl's default.

protection property writable

protection: Protection

The cell protection (locked, hidden).

A cell without explicit protection reports openpyxl's locked, visible default.

quotePrefix property

quotePrefix: bool

True when the cell's format sets Excel's quote prefix, as openpyxl's.

pivotButton property

pivotButton: bool

True when the cell's format sets Excel's pivot-button flag.

number_format property writable

number_format: str

The number format code; "General" when none is set.

style property writable

style: Style

The cell's Style.

Assign a Style, or the name of a named style registered with Workbook.add_named_style.

check_error

check_error(value: Any) -> str

The text openpyxl stores for an error value: str(value) or "#N/A".

Source code in src/xlspy/workbook/_cell.py
411
412
413
414
415
416
def check_error(self, value: Any) -> str:
    """The text openpyxl stores for an error value: ``str(value)`` or ``"#N/A"``."""
    try:
        return str(value)
    except UnicodeDecodeError:
        return "#N/A"

check_string

check_string(value: Any) -> Any

The stored text for value, as openpyxl stores it.

Text is truncated to 32,767 characters and illegal control characters in what remains raise IllegalCharacterError with openpyxl's message. A non-string is decoded with the cell's UTF-8 encoding, as openpyxl decodes it.

Source code in src/xlspy/workbook/_cell.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def check_string(self, value: Any) -> Any:
    """The stored text for ``value``, as openpyxl stores it.

    Text is truncated to 32,767 characters and illegal control characters
    in what remains raise ``IllegalCharacterError`` with openpyxl's
    message. A non-string is decoded with the cell's UTF-8 encoding, as
    openpyxl decodes it.
    """
    if value is None:
        return None
    if not isinstance(value, str):
        value = str(value, self.encoding)
    value = str(value)[:32767]
    if _ILLEGAL_CHARACTERS.search(value) is not None:
        raise IllegalCharacterError(f"{value} cannot be used in worksheets.")
    return value

offset

offset(row: int = 0, column: int = 0) -> Cell

The cell row rows below and column columns right of this one.

Negative offsets go up and left.

Source code in src/xlspy/workbook/_cell.py
516
517
518
519
520
521
def offset(self, row: int = 0, column: int = 0) -> Cell:
    """The cell ``row`` rows below and ``column`` columns right of this one.

    Negative offsets go up and left.
    """
    return self._sheet.cell(self._row + row, self._column + column)

MergedCell

MergedCell(sheet: Worksheet, row: int, column: int, value: Any = None, style_id: int = 0)

Bases: Cell

A cell inside a merged range other than its top-left anchor.

Source code in src/xlspy/workbook/_cell.py
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(self, sheet: Worksheet, row: int, column: int, value: Any = None, style_id: int = 0) -> None:
    self._sheet = sheet
    self._row = _coerce_row(row)
    self._column = _coerce_column(column)
    self._value: Any = None
    self._formula: Formula | ArrayFormula | DataTableFormula | str | None = None
    self._data_type = "n"
    self._style_id = int(style_id)
    self._comment: Comment | None = None
    self._hyperlink: Hyperlink | None = None
    self._named_style: str | None = None
    if value is not None:
        self.value = value

row property

row: int

The 1-based row number.

column property

column: int

The 1-based column number.

column_letter property

column_letter: str

The column letter, such as "C".

col_idx property

col_idx: int

The 1-based column number, as openpyxl names it.

coordinate property

coordinate: str

The cell reference, such as "C5".

parent property

parent: Worksheet

The worksheet that holds the cell.

formula property

formula: Formula | ArrayFormula | DataTableFormula | str | None

The formula object or text without its leading =, or None.

data_type property

data_type: str

openpyxl's type code: n number or empty, s text, b boolean, d date or time, f formula, e error.

internal_value property

internal_value: Any

The stored value; None for a formula cell that holds no cached result.

is_date property

is_date: bool

True when the value is a date, datetime, time or timedelta.

encoding property

encoding: str

Always "utf-8", for openpyxl compatibility.

base_date property

base_date: datetime

The workbook's epoch, the base date of serial date numbers (1899-12-30).

hyperlink: Hyperlink | None

The cell's Hyperlink, or None.

comment property writable

comment: Comment | None

The cell's note (a Comment), or None.

threaded_comment property writable

threaded_comment: ThreadedComment | None

The cell's Excel 365 conversation, or None.

Assigning a ThreadedComment starts a conversation; assigning None removes the whole conversation, replies included.

style_id property

style_id: int

The index of the cell's style in the workbook's style table.

has_style property

has_style: bool

True when the cell has a style other than the workbook default.

font property writable

font: Font | None

The cell font, or None when its style sets no font.

Assigning one replaces the font of the cell's style.

fill property writable

fill: str | PatternFill | GradientFill

The cell fill: a colour, a PatternFill or a GradientFill.

A cell without a fill reports openpyxl's empty pattern fill.

border property writable

border: Border

The cell border; a cell without one reports openpyxl's empty border.

alignment property writable

alignment: Alignment

The cell alignment; a cell without one reports openpyxl's default.

protection property writable

protection: Protection

The cell protection (locked, hidden).

A cell without explicit protection reports openpyxl's locked, visible default.

quotePrefix property

quotePrefix: bool

True when the cell's format sets Excel's quote prefix, as openpyxl's.

pivotButton property

pivotButton: bool

True when the cell's format sets Excel's pivot-button flag.

number_format property writable

number_format: str

The number format code; "General" when none is set.

style property writable

style: Style

The cell's Style.

Assign a Style, or the name of a named style registered with Workbook.add_named_style.

check_error

check_error(value: Any) -> str

The text openpyxl stores for an error value: str(value) or "#N/A".

Source code in src/xlspy/workbook/_cell.py
411
412
413
414
415
416
def check_error(self, value: Any) -> str:
    """The text openpyxl stores for an error value: ``str(value)`` or ``"#N/A"``."""
    try:
        return str(value)
    except UnicodeDecodeError:
        return "#N/A"

check_string

check_string(value: Any) -> Any

The stored text for value, as openpyxl stores it.

Text is truncated to 32,767 characters and illegal control characters in what remains raise IllegalCharacterError with openpyxl's message. A non-string is decoded with the cell's UTF-8 encoding, as openpyxl decodes it.

Source code in src/xlspy/workbook/_cell.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def check_string(self, value: Any) -> Any:
    """The stored text for ``value``, as openpyxl stores it.

    Text is truncated to 32,767 characters and illegal control characters
    in what remains raise ``IllegalCharacterError`` with openpyxl's
    message. A non-string is decoded with the cell's UTF-8 encoding, as
    openpyxl decodes it.
    """
    if value is None:
        return None
    if not isinstance(value, str):
        value = str(value, self.encoding)
    value = str(value)[:32767]
    if _ILLEGAL_CHARACTERS.search(value) is not None:
        raise IllegalCharacterError(f"{value} cannot be used in worksheets.")
    return value

offset

offset(row: int = 0, column: int = 0) -> Cell

The cell row rows below and column columns right of this one.

Negative offsets go up and left.

Source code in src/xlspy/workbook/_cell.py
516
517
518
519
520
521
def offset(self, row: int = 0, column: int = 0) -> Cell:
    """The cell ``row`` rows below and ``column`` columns right of this one.

    Negative offsets go up and left.
    """
    return self._sheet.cell(self._row + row, self._column + column)

ReadOnlyCell

ReadOnlyCell(row: int, column: int, value: Any, number_format: str = 'General')

A cell value streamed from a read-only worksheet (as openpyxl's).

Source code in src/xlspy/workbook/_reader.py
1392
1393
1394
1395
1396
def __init__(self, row: int, column: int, value: Any, number_format: str = "General") -> None:
    self.row = row
    self.column = column
    self.value = value
    self.number_format = number_format

coordinate property

coordinate: str

The cell reference, such as "C5".

column_letter property

column_letter: str

The column letter, such as "C".

data_type property

data_type: str

openpyxl's type code for the value; f for formula text.

is_date property

is_date: bool

True when the value is a date, datetime, time or timedelta.

WriteOnlyCell

WriteOnlyCell(worksheet: Any, value: Any = None)

A value with optional style, used with WriteOnlyWorksheet.append.

Source code in src/xlspy/workbook/_cell.py
555
556
557
558
559
560
561
562
563
564
565
def __init__(self, worksheet: Any, value: Any = None) -> None:
    self.parent = worksheet
    self.value = value
    self.font = None
    self.fill = None
    self.border = None
    self.alignment = None
    self.protection = None
    self.number_format = "General"
    self.comment = None
    self.hyperlink = None

CellRange

Bases: str

An A1 range string with openpyxl-style boundary properties.

min_col property

min_col: int

The first column, 1-based.

min_row property

min_row: int

The first row, 1-based.

max_col property

max_col: int

The last column, 1-based.

max_row property

max_row: int

The last row, 1-based.

coord property

coord: str

The range as text, such as "A1:C3".

bounds property

bounds: tuple[int, int, int, int]

(min_col, min_row, max_col, max_row), 1-based.

size property

size: dict[str, int]

The size as {"columns": n, "rows": m}.

shift

shift(col_shift: int = 0, row_shift: int = 0) -> CellRange

Return the range moved right by col_shift and down by row_shift.

Raises ValueError when the result leaves the worksheet.

Source code in src/xlspy/workbook/_coords.py
130
131
132
133
134
135
136
137
138
139
140
141
def shift(self, col_shift: int = 0, row_shift: int = 0) -> CellRange:
    """Return the range moved right by ``col_shift`` and down by ``row_shift``.

    Raises ValueError when the result leaves the worksheet.
    """
    min_col = self.min_col + col_shift
    min_row = self.min_row + row_shift
    max_col = self.max_col + col_shift
    max_row = self.max_row + row_shift
    if min_col < 1 or min_row < 1 or max_col > 16384 or max_row > 1048576:
        raise ValueError(f"Invalid shift value: col_shift={col_shift}, row_shift={row_shift}")
    return CellRange(f"{column_label(min_col - 1)}{min_row}:{column_label(max_col - 1)}{max_row}")

expand

expand(right: int = 0, down: int = 0, left: int = 0, up: int = 0) -> CellRange

Return the range grown by the given number of cells on each side.

Raises ValueError when the result leaves the worksheet.

Source code in src/xlspy/workbook/_coords.py
143
144
145
146
147
148
149
150
151
152
153
154
def expand(self, right: int = 0, down: int = 0, left: int = 0, up: int = 0) -> CellRange:
    """Return the range grown by the given number of cells on each side.

    Raises ValueError when the result leaves the worksheet.
    """
    min_col = self.min_col - left
    min_row = self.min_row - up
    max_col = self.max_col + right
    max_row = self.max_row + down
    if min_col < 1 or min_row < 1 or max_col > 16384 or max_row > 1048576:
        raise ValueError("expanded range is outside the worksheet")
    return CellRange(f"{column_label(min_col - 1)}{min_row}:{column_label(max_col - 1)}{max_row}")

shrink

shrink(right: int = 0, bottom: int = 0, left: int = 0, top: int = 0) -> CellRange

Return the range made smaller by the given number of cells on each side.

Source code in src/xlspy/workbook/_coords.py
156
157
158
def shrink(self, right: int = 0, bottom: int = 0, left: int = 0, top: int = 0) -> CellRange:
    """Return the range made smaller by the given number of cells on each side."""
    return self.expand(right=-right, down=-bottom, left=-left, up=-top)

union

union(other: CellRange | str) -> CellRange

Return the smallest range that covers this range and other.

Source code in src/xlspy/workbook/_coords.py
160
161
162
163
164
165
166
167
168
def union(self, other: CellRange | str) -> CellRange:
    """Return the smallest range that covers this range and ``other``."""
    other = other if isinstance(other, CellRange) else CellRange(str(other))
    return CellRange(
        f"{column_label(min(self.min_col, other.min_col) - 1)}"
        f"{min(self.min_row, other.min_row)}:"
        f"{column_label(max(self.max_col, other.max_col) - 1)}"
        f"{max(self.max_row, other.max_row)}"
    )

intersection

intersection(other: CellRange | str) -> CellRange

Return the cells this range shares with other.

Raises ValueError when the ranges do not overlap.

Source code in src/xlspy/workbook/_coords.py
170
171
172
173
174
175
176
177
178
179
180
181
182
def intersection(self, other: CellRange | str) -> CellRange:
    """Return the cells this range shares with ``other``.

    Raises ValueError when the ranges do not overlap.
    """
    other = other if isinstance(other, CellRange) else CellRange(str(other))
    min_col = max(self.min_col, other.min_col)
    min_row = max(self.min_row, other.min_row)
    max_col = min(self.max_col, other.max_col)
    max_row = min(self.max_row, other.max_row)
    if min_col > max_col or min_row > max_row:
        raise ValueError(f"Range {self} doesn't intersect {other}")
    return CellRange(f"{column_label(min_col - 1)}{min_row}:{column_label(max_col - 1)}{max_row}")

isdisjoint

isdisjoint(other: CellRange | str) -> bool

True when this range and other share no cell.

Source code in src/xlspy/workbook/_coords.py
184
185
186
187
188
189
190
191
192
def isdisjoint(self, other: CellRange | str) -> bool:
    """True when this range and ``other`` share no cell."""
    other = other if isinstance(other, CellRange) else CellRange(str(other))
    return (
        self.max_col < other.min_col
        or other.max_col < self.min_col
        or self.max_row < other.min_row
        or other.max_row < self.min_row
    )

issubset

issubset(other: CellRange | str) -> bool

True when every cell of this range is in other.

Source code in src/xlspy/workbook/_coords.py
194
195
196
197
198
199
200
def issubset(self, other: CellRange | str) -> bool:
    """True when every cell of this range is in ``other``."""
    other = other if isinstance(other, CellRange) else CellRange(str(other))
    return (
        other.min_col <= self.min_col <= self.max_col <= other.max_col
        and other.min_row <= self.min_row <= self.max_row <= other.max_row
    )

issuperset

issuperset(other: CellRange | str) -> bool

True when every cell of other is in this range.

Source code in src/xlspy/workbook/_coords.py
202
203
204
205
def issuperset(self, other: CellRange | str) -> bool:
    """True when every cell of ``other`` is in this range."""
    other = other if isinstance(other, CellRange) else CellRange(str(other))
    return other.issubset(self)

MultiCellRange

MultiCellRange(ranges: Iterable[str] | None = None)

Several cell ranges, such as a sheet's merged cells, in the order added.

Source code in src/xlspy/workbook/_coords.py
277
278
279
280
281
282
283
284
def __init__(self, ranges: Iterable[str] | None = None) -> None:
    self._ranges = _RangeList()
    self._index = RangeIndex()
    self._present: set[str] = set()
    self._synced = -1
    if ranges is not None:
        for value in ranges:
            self.add(value)

ranges property writable

ranges: list[CellRange]

The ranges in the order added. Code may change the list; the index follows it.

add

add(value: str) -> None

Add a range unless it is already present.

Source code in src/xlspy/workbook/_coords.py
306
307
308
309
310
311
312
313
314
def add(self, value: str) -> None:
    """Add a range unless it is already present."""
    cell_range = CellRange(value)
    self._sync()
    if cell_range not in self._present:
        self._ranges.append(cell_range)
        self._present.add(cell_range)
        self._index.add(parse_cell_range(cell_range), cell_range)
        self._synced = self._ranges.version

remove

remove(value: str) -> None

Remove a range; raises ValueError when it is not present.

Source code in src/xlspy/workbook/_coords.py
316
317
318
319
320
321
322
323
324
325
def remove(self, value: str) -> None:
    """Remove a range; raises ValueError when it is not present."""
    cell_range = CellRange(value)
    self._sync()
    if cell_range not in self._present:
        raise ValueError(f"range {value!r} is not merged")
    self._ranges.remove(cell_range)
    self._present.discard(cell_range)
    self._index.remove(parse_cell_range(cell_range), cell_range)
    self._synced = self._ranges.version

first_overlapping

first_overlapping(bounds: tuple[int, int, int, int]) -> CellRange | None

The first range added that shares a cell with zero-based bounds, or None.

Source code in src/xlspy/workbook/_coords.py
327
328
329
330
331
def first_overlapping(self, bounds: tuple[int, int, int, int]) -> CellRange | None:
    """The first range added that shares a cell with zero-based ``bounds``, or None."""
    self._sync()
    found = self._index.overlapping(bounds)
    return found[0][4] if found else None

Dimension

Dimension(index: str | int)

The size, visibility and outline settings of a row or column, with openpyxl's attribute names.

Source code in src/xlspy/workbook/_dimensions.py
15
16
17
18
19
20
21
22
23
24
25
26
def __init__(self, index: str | int) -> None:
    self.index = index
    self.min: int | None = None
    self.max: int | None = None
    self.width: float | None = None
    self.height: float | None = None
    self.hidden: bool = False
    self.bestFit: bool | None = None
    self.autoSize: bool | None = None
    self.outlineLevel: int = 0
    self.collapsed: bool = False
    self.style: int | None = None

customWidth property

customWidth: bool

True when a width is set.

customHeight property

customHeight: bool

True when a height is set.

outline_level property writable

outline_level: int

The outline (group) level; the same as outlineLevel.

ColumnDimension

ColumnDimension(index: str | int)

Bases: Dimension

A column's width, visibility and outline level: ws.column_dimensions["B"].

Source code in src/xlspy/workbook/_dimensions.py
15
16
17
18
19
20
21
22
23
24
25
26
def __init__(self, index: str | int) -> None:
    self.index = index
    self.min: int | None = None
    self.max: int | None = None
    self.width: float | None = None
    self.height: float | None = None
    self.hidden: bool = False
    self.bestFit: bool | None = None
    self.autoSize: bool | None = None
    self.outlineLevel: int = 0
    self.collapsed: bool = False
    self.style: int | None = None

range property

range: str

The columns covered, such as "A:C", as openpyxl names it.

customWidth property

customWidth: bool

True when a width is set.

customHeight property

customHeight: bool

True when a height is set.

outline_level property writable

outline_level: int

The outline (group) level; the same as outlineLevel.

RowDimension

RowDimension(index: str | int)

Bases: Dimension

A row's height, visibility and outline level: ws.row_dimensions[3].

Source code in src/xlspy/workbook/_dimensions.py
15
16
17
18
19
20
21
22
23
24
25
26
def __init__(self, index: str | int) -> None:
    self.index = index
    self.min: int | None = None
    self.max: int | None = None
    self.width: float | None = None
    self.height: float | None = None
    self.hidden: bool = False
    self.bestFit: bool | None = None
    self.autoSize: bool | None = None
    self.outlineLevel: int = 0
    self.collapsed: bool = False
    self.style: int | None = None

customWidth property

customWidth: bool

True when a width is set.

customHeight property

customHeight: bool

True when a height is set.

outline_level property writable

outline_level: int

The outline (group) level; the same as outlineLevel.

DimensionHolder

DimensionHolder(factory: Callable[[Any], Dimension], transform: Callable[[Any], Any])

Bases: dict[Any, Any]

Source code in src/xlspy/workbook/_dimensions.py
64
65
66
67
def __init__(self, factory: Callable[[Any], Dimension], transform: Callable[[Any], Any]) -> None:
    super().__init__()
    self._factory = factory
    self._transform = transform

get

get(key: Any, default: Any = None) -> Any

Like dict.get, without creating an entry; the key may be a letter or a number.

Source code in src/xlspy/workbook/_dimensions.py
78
79
80
def get(self, key: Any, default: Any = None) -> Any:
    """Like ``dict.get``, without creating an entry; the key may be a letter or a number."""
    return super().get(self._transform(key), default)

group

group(start: int | str, end: int | str | None = None, outline_level: int = 1, hidden: bool = False) -> None

Group consecutive rows or columns, as openpyxl does.

Source code in src/xlspy/workbook/_dimensions.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def group(
    self, start: int | str, end: int | str | None = None, outline_level: int = 1, hidden: bool = False
) -> None:
    """Group consecutive rows or columns, as openpyxl does."""
    if end is None:
        end = start
    if self._factory is ColumnDimension:
        first = _coerce_column(start)
        last = _coerce_column(end)
        for index in range(first, last + 1):
            dimension = self[column_label(index - 1)]
            dimension.outlineLevel = outline_level
            dimension.hidden = hidden
            dimension.min = first
            dimension.max = last
    else:
        for index in range(int(start), int(end) + 1):
            dimension = self[index]
            dimension.outlineLevel = outline_level
            dimension.hidden = hidden

Table

Table(id: int = 1, displayName: str | None = None, ref: str | None = None, name: str | None = None, comment: str | None = None, tableType: str | None = None, headerRowCount: int = 1, insertRow: bool | None = None, insertRowShift: bool | None = None, totalsRowCount: int | None = None, totalsRowShown: bool | None = None, published: bool | None = None, autoFilter: AutoFilter | None = None, sortState: SortState | None = None, tableColumns: Iterable[TableColumn] = (), tableStyleInfo: TableStyleInfo | None = None)

An openpyxl-style table: a named range with a header row, columns and a style.

Add it with Worksheet.add_table. ExcelTable is the equivalent for the writers.

Source code in src/xlspy/workbook/_tables.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def __init__(
    self,
    id: int = 1,
    displayName: str | None = None,
    ref: str | None = None,
    name: str | None = None,
    comment: str | None = None,
    tableType: str | None = None,
    headerRowCount: int = 1,
    insertRow: bool | None = None,
    insertRowShift: bool | None = None,
    totalsRowCount: int | None = None,
    totalsRowShown: bool | None = None,
    published: bool | None = None,
    autoFilter: AutoFilter | None = None,
    sortState: SortState | None = None,
    tableColumns: Iterable[TableColumn] = (),
    tableStyleInfo: TableStyleInfo | None = None,
) -> None:
    self.id = id
    self.displayName = displayName
    self.ref = ref
    self.name = name or displayName
    self.comment = comment
    self.tableType = tableType
    self.headerRowCount = headerRowCount
    self.insertRow = insertRow
    self.insertRowShift = insertRowShift
    self.totalsRowCount = totalsRowCount
    self.totalsRowShown = totalsRowShown
    self.published = published
    self.autoFilter = autoFilter
    self.sortState = sortState
    self.tableColumns = list(tableColumns)
    self.tableStyleInfo = tableStyleInfo

display_name property

display_name: str | None

The table name shown in Excel; the same as displayName.

header_row property

header_row: bool

True when the table has a header row.

totals_row property

totals_row: bool

True when the table has a totals row.

columns property

columns: list[str | None]

The column names.

style_name property

style_name: str | None

The table style name, or None.

TableColumn

TableColumn(id: int | None = None, name: str | None = None, totalsRowFunction: str | None = None, totalsRowLabel: str | None = None, calculatedColumnFormula: str | None = None, totalsRowFormula: str | None = None, xmlColumnPr: object = None)

A column of a Table: its name and totals row settings.

Source code in src/xlspy/workbook/_tables.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def __init__(
    self,
    id: int | None = None,
    name: str | None = None,
    totalsRowFunction: str | None = None,
    totalsRowLabel: str | None = None,
    calculatedColumnFormula: str | None = None,
    totalsRowFormula: str | None = None,
    xmlColumnPr: object = None,
) -> None:
    self.id = id
    self.name = name
    self.totalsRowFunction = totalsRowFunction
    self.totalsRowLabel = totalsRowLabel
    self.calculatedColumnFormula = calculatedColumnFormula
    self.totalsRowFormula = totalsRowFormula
    self.xmlColumnPr = xmlColumnPr

TableStyleInfo

TableStyleInfo(name: str | None = None, showFirstColumn: bool | None = None, showLastColumn: bool | None = None, showRowStripes: bool | None = None, showColumnStripes: bool | None = None)

A table's style name and banding options.

Source code in src/xlspy/workbook/_tables.py
119
120
121
122
123
124
125
126
127
128
129
130
131
def __init__(
    self,
    name: str | None = None,
    showFirstColumn: bool | None = None,
    showLastColumn: bool | None = None,
    showRowStripes: bool | None = None,
    showColumnStripes: bool | None = None,
) -> None:
    self.name = name
    self.showFirstColumn = showFirstColumn
    self.showLastColumn = showLastColumn
    self.showRowStripes = showRowStripes
    self.showColumnStripes = showColumnStripes

AutoFilter dataclass

AutoFilter(ref: str | None = None, filterColumn: list[FilterColumn] = list(), sortState: SortState | None = None)

add_filter_column

add_filter_column(col_id: int, vals: Iterable[Any] | None, blank: bool = False) -> None

Filter column col_id (0-based within the filter range) to vals.

blank=True also shows blank cells.

Source code in src/xlspy/workbook/_properties.py
417
418
419
420
421
422
def add_filter_column(self, col_id: int, vals: Iterable[Any] | None, blank: bool = False) -> None:
    """Filter column ``col_id`` (0-based within the filter range) to ``vals``.

    ``blank=True`` also shows blank cells.
    """
    self.filterColumn.append(FilterColumn(colId=col_id, vals=list(vals or []), blank=bool(blank)))

add_sort_condition

add_sort_condition(ref: str, descending: bool = False) -> None

Sort by the cells of ref, descending when asked.

Source code in src/xlspy/workbook/_properties.py
424
425
426
427
428
def add_sort_condition(self, ref: str, descending: bool = False) -> None:
    """Sort by the cells of ``ref``, descending when asked."""
    if self.sortState is None:
        self.sortState = SortState(ref=self.ref)
    self.sortState.sortCondition.append(SortCondition(ref=ref, descending=bool(descending)))

DefinedNameList

DefinedNameList(workbook: Workbook | None = None, definitions: Iterable[DefinedName] | None = None)

A list/dict hybrid of DefinedName entries.

Source code in src/xlspy/workbook/_properties.py
88
89
90
91
92
def __init__(self, workbook: Workbook | None = None, definitions: Iterable[DefinedName] | None = None) -> None:
    self._workbook = workbook
    self._items: list[DefinedName] = []
    for definition in definitions or []:
        self.add(definition, stage=False)

names property

names: list[str]

The defined names, in order.

keys

keys() -> list[str]

The defined names' names, as a dict-like view over the list.

Source code in src/xlspy/workbook/_properties.py
135
136
137
def keys(self) -> list[str]:
    """The defined names' names, as a dict-like view over the list."""
    return self.names

values

values() -> list[DefinedName]

The defined names, as a dict-like view over the list.

Source code in src/xlspy/workbook/_properties.py
139
140
141
def values(self) -> list[DefinedName]:
    """The defined names, as a dict-like view over the list."""
    return list(self._items)

items

items() -> list[tuple[str, DefinedName]]

The names and their definitions, as a dict-like view over the list.

Source code in src/xlspy/workbook/_properties.py
143
144
145
def items(self) -> list[tuple[str, DefinedName]]:
    """The names and their definitions, as a dict-like view over the list."""
    return [(definition.name, definition) for definition in self._items]

get

get(name: str, default: object = None) -> object

The definition called name, or default when there is none.

Source code in src/xlspy/workbook/_properties.py
147
148
149
150
151
152
def get(self, name: str, default: object = None) -> object:
    """The definition called ``name``, or ``default`` when there is none."""
    try:
        return self[name]
    except KeyError:
        return default

add

add(definition: DefinedName, *, stage: bool = True) -> None

Add a defined name, replacing one with the same name and scope.

Source code in src/xlspy/workbook/_properties.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def add(self, definition: DefinedName, *, stage: bool = True) -> None:
    """Add a defined name, replacing one with the same name and scope."""
    if not isinstance(definition, DefinedName):
        raise TypeError("defined names must be DefinedName instances")
    self._items = [
        item
        for item in self._items
        if not (item.name.casefold() == definition.name.casefold() and item.scope == definition.scope)
    ]
    self._items.append(definition)
    if stage and self._workbook is not None:
        # Staged: flushed once at save (single workbook rewrite) instead of
        # once per add, which was quadratic for bulk inserts.
        self._workbook._defined_names_dirty = True

remove

remove(name: str, scope: str | None = None) -> DefinedName

Remove a defined name and return it.

Without scope the first entry with the name goes. Raises KeyError when absent.

Source code in src/xlspy/workbook/_properties.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def remove(self, name: str, scope: str | None = None) -> DefinedName:
    """Remove a defined name and return it.

    Without ``scope`` the first entry with the name goes. Raises KeyError when absent.
    """
    if not isinstance(name, str):
        raise TypeError("defined name must be a string")
    folded = name.casefold()
    target = None
    for definition in self._items:
        if definition.name.casefold() == folded and (scope is None or definition.scope == scope):
            target = definition
            break
    if target is None:
        raise KeyError(name)
    self._items.remove(target)
    if self._workbook is not None:
        self._workbook._defined_names_dirty = True
    return target

DocumentProperties dataclass

DocumentProperties(creator: str = 'xlspy', title: str | None = None, subject: str | None = None, description: str | None = None, keywords: str | None = None, category: str | None = None, lastModifiedBy: str | None = None, created: datetime = now(), modified: datetime = now(), revision: str | None = None, contentStatus: str | None = None, identifier: str | None = None, language: str | None = None, version: str | None = None, lastPrinted: datetime | None = None)

CustomProperty dataclass

CustomProperty(name: str, value: object)

CustomPropertyList

Bases: list

A list of custom document properties, keyed by name for convenience.

names property

names: list[str]

The property names.

CalcProperties dataclass

CalcProperties(calcId: int = 124519, calcMode: str | None = None, fullCalcOnLoad: bool = True, refMode: str | None = None, iterate: bool | None = None, iterateCount: int | None = None, iterateDelta: float | None = None, fullPrecision: bool | None = None, calcCompleted: bool | None = None, calcOnSave: bool | None = None, concurrentCalc: bool | None = None, concurrentManualCount: int | None = None, forceFullCalc: bool | None = None)

BookView dataclass

BookView(visibility: str = 'visible', minimized: bool = False, showHorizontalScroll: bool = True, showVerticalScroll: bool = True, showSheetTabs: bool = True, xWindow: int | None = None, yWindow: int | None = None, windowWidth: int | None = None, windowHeight: int | None = None, tabRatio: int = 600, firstSheet: int = 0, activeTab: int = 0, autoFilterDateGrouping: bool = True)

WorkbookSecurity dataclass

WorkbookSecurity(workbookPassword: str | None = None, workbookPasswordCharacterSet: str | None = None, revisionsPassword: str | None = None, revisionsPasswordCharacterSet: str | None = None, lockStructure: bool | None = None, lockWindows: bool | None = None, lockRevision: bool | None = None, revisionsAlgorithmName: str | None = None, revisionsHashValue: str | None = None, revisionsSaltValue: str | None = None, revisionsSpinCount: int | None = None, workbookAlgorithmName: str | None = None, workbookHashValue: str | None = None, workbookSaltValue: str | None = None, workbookSpinCount: int | None = None)

SheetProperties dataclass

SheetProperties(tabColor: Color | str | None = None, codeName: str | None = None, pageSetUpPr: PageSetupProperties = PageSetupProperties(), outlinePr: Outline = Outline(), enableFormatConditionsCalculation: bool | None = None, filterMode: bool | None = None, published: bool | None = None, syncHorizontal: bool | None = None, syncRef: str | None = None, syncVertical: bool | None = None, transitionEvaluation: bool | None = None, transitionEntry: bool | None = None)

SheetFormatProperties dataclass

SheetFormatProperties(baseColWidth: int = 8, defaultColWidth: float | None = None, defaultRowHeight: float = 15, customHeight: bool | None = None, zeroHeight: bool | None = None, thickTop: bool | None = None, thickBottom: bool | None = None, outlineLevelRow: int | None = None, outlineLevelCol: int | None = None)

SheetView dataclass

SheetView(windowProtection: bool | None = None, showFormulas: bool | None = None, showGridLines: bool | None = None, showRowColHeaders: bool | None = None, showZeros: bool | None = None, rightToLeft: bool | None = None, tabSelected: bool | None = None, showRuler: bool | None = None, showOutlineSymbols: bool | None = None, defaultGridColor: bool | None = None, showWhiteSpace: bool | None = None, view: str | None = None, topLeftCell: str | None = None, colorId: int | None = None, zoomScale: int | None = None, zoomScaleNormal: int | None = None, zoomScaleSheetLayoutView: int | None = None, zoomScalePageLayoutView: int | None = None, zoomToFit: bool | None = None, workbookViewId: int = 0, selection: list[Selection] = list(), pane: Pane | None = None)

Pane dataclass

Pane(xSplit: float | int | None = None, ySplit: float | int | None = None, topLeftCell: str | None = None, activePane: str = 'topLeft', state: str = 'split')

Selection dataclass

Selection(pane: str | None = None, activeCell: str = 'A1', activeCellId: int | None = None, sqref: str = 'A1')

Outline dataclass

Outline(applyStyles: bool | None = None, summaryBelow: bool | None = None, summaryRight: bool | None = None, showOutlineSymbols: bool | None = None)

WorksheetProtection dataclass

WorksheetProtection(sheet: bool = False, objects: bool = False, scenarios: bool = False, formatCells: bool = True, formatRows: bool = True, formatColumns: bool = True, insertColumns: bool = True, insertRows: bool = True, insertHyperlinks: bool = True, deleteColumns: bool = True, deleteRows: bool = True, selectLockedCells: bool = False, selectUnlockedCells: bool = False, sort: bool = True, autoFilter: bool = True, pivotTables: bool = True, password: str | None = None, algorithmName: str | None = None, saltValue: str | None = None, spinCount: int | None = None, hashValue: str | None = None)

set_password

set_password(value: str | None = '', already_hashed: bool = False) -> None

Set the password, stored as its legacy hash unless already_hashed.

Source code in src/xlspy/workbook/_properties.py
498
499
500
501
502
def set_password(self, value: str | None = "", already_hashed: bool = False) -> None:
    """Set the password, stored as its legacy hash unless ``already_hashed``."""
    if value is not None and not already_hashed:
        value = password_hash(value)
    object.__setattr__(self, "password", value)

enable

enable() -> None

Turn sheet protection on.

Source code in src/xlspy/workbook/_properties.py
504
505
506
def enable(self) -> None:
    """Turn sheet protection on."""
    self.sheet = True

disable

disable() -> None

Turn sheet protection off.

Source code in src/xlspy/workbook/_properties.py
508
509
510
def disable(self) -> None:
    """Turn sheet protection off."""
    self.sheet = False

WorksheetPageMargins dataclass

WorksheetPageMargins(left: float = 0.7, right: float = 0.7, top: float = 0.75, bottom: float = 0.75, header: float = 0.3, footer: float = 0.3)

ws.page_margins in inches (openpyxl's defaults).

XlsxStyleTable

XlsxStyleTable()

A parsed xl/styles.xml table with append-only style creation.

Source code in src/xlspy/workbook/_styles.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def __init__(self) -> None:
    self._root: ET.Element | None = None
    self.fonts: list[Font | None] = []
    self.fills: list[PatternFill | GradientFill | None] = []
    self.borders: list[Border | None] = []
    self.num_formats: dict[int, str] = dict(BUILTIN_NUM_FORMATS)
    self.custom_num_formats: set[int] = set()
    self.xfs: list[_Xf] = []
    self.styles: list[Style] = []
    self.dxfs: list[DifferentialStyle | None] = []
    self.named_styles: list[str] = []
    self.cell_style_xfs: list[Style] = []
    self.named_style_defs: dict[str, NamedStyle] = {}
    self._font_keys: list[object | None] = []
    self._fill_keys: list[object | None] = []
    self._border_keys: list[object | None] = []
    self._font_index: dict[object, int] = {}
    self._fill_index: dict[object, int] = {}
    self._border_index: dict[object, int] = {}
    self._numfmt_by_code: dict[str, int] = {}
    self._xf_index: dict[tuple, int] = {}
    self._next_numfmt_id = 164
    # Cell.number_format memo: (style id, format) -> style id with that format.
    self._number_format_ids: dict[tuple[int, str], int] = {}
    self._font_xml: list[str] = []
    self._fill_xml: list[str] = []
    self._border_xml: list[str] = []
    self._xf_xml: list[str] = []

empty classmethod

empty() -> XlsxStyleTable

A style table with Excel's default font, fills, border and cell format.

Source code in src/xlspy/workbook/_styles.py
396
397
398
399
400
401
@classmethod
def empty(cls) -> XlsxStyleTable:
    """A style table with Excel's default font, fills, border and cell format."""
    table = cls()
    table._add_default_components()
    return table

from_xml classmethod

from_xml(xml: bytes | str | None) -> XlsxStyleTable

Parse xl/styles.xml; empty input gives empty.

Source code in src/xlspy/workbook/_styles.py
403
404
405
406
407
408
409
410
411
412
413
414
415
@classmethod
def from_xml(cls, xml: bytes | str | None) -> XlsxStyleTable:
    """Parse ``xl/styles.xml``; empty input gives ``empty``."""
    if not xml:
        return cls.empty()
    table = cls()
    root = safe_fromstring(xml)
    table._root = root
    table._source = xml
    table._parse(root)
    if not table.xfs:
        table._add_default_components()
    return table

add_named_style

add_named_style(style: NamedStyle) -> int

Append a named style to cellStyleXfs/cellStyles.

Source code in src/xlspy/workbook/_styles.py
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
def add_named_style(self, style: NamedStyle) -> int:
    """Append a named style to ``cellStyleXfs``/``cellStyles``."""
    if not isinstance(style, NamedStyle):
        raise TypeError("style must be a NamedStyle")
    if self._root is None:
        self.to_bytes()
    root = self._root
    style_xfs = self._container(
        root,
        "cellStyleXfs",
        '<xf numFmtId="0" fontId="0" fillId="0" borderId="0"/>',
    )
    base = Style(
        font=style.font,
        fill=style.fill,
        border=style.border,
        number_format=style.number_format,
        alignment=style.alignment,
        protection=style.protection,
    )
    xf_index = len(self.cell_style_xfs)
    style_xfs.append(safe_fromstring(self._named_xf_xml(base)))
    style_xfs.set("count", str(len(style_xfs)))
    self.cell_style_xfs.append(base)

    cell_styles = self._container(
        root,
        "cellStyles",
        '<cellStyle name="Normal" xfId="0" builtinId="0"/>',
    )
    attrs = f"name={quoteattr(style.name)} xfId={quoteattr(str(xf_index))}"
    if style.builtinId is not None:
        attrs += f' builtinId="{style.builtinId}"'
    if style.hidden:
        attrs += ' hidden="1"'
    cell_styles.append(safe_fromstring(f"<cellStyle {attrs}/>"))
    cell_styles.set("count", str(len(cell_styles)))

    if style.name not in self.named_styles:
        self.named_styles.append(style.name)
    self.named_style_defs[style.name] = style
    return xf_index

add

add(style: Style) -> int

Return the XF index for style, appending components as needed.

Source code in src/xlspy/workbook/_styles.py
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
def add(self, style: Style) -> int:
    """Return the XF index for ``style``, appending components as needed."""
    if not isinstance(style, Style):
        raise TypeError("style must be a Style instance")
    if style.pattern is None and isinstance(style.fill, PatternFill) and _pattern_fill_key(style.fill) is None:
        style = replace(style, fill=None)
    if isinstance(style.pattern, PatternFill) and _pattern_fill_key(style.pattern) is None:
        style = replace(style, pattern=None)
    font_key, fill_key, border_key, numfmt, align_key, prot_key = split_style(style)
    font_id = self._intern_font(font_key)
    fill_id = self._intern_fill(fill_key)
    border_id = self._intern_border(border_key)
    numfmt_id = 0 if numfmt is None else self._intern_numfmt(numfmt)
    if align_key is not None and all(value is None for value in align_key):
        align_key = None
    if prot_key is not None and all(value is None for value in prot_key):
        prot_key = None
    key = (
        font_id,
        fill_id,
        border_id,
        numfmt_id,
        align_key,
        prot_key,
        bool(style.quote_prefix),
        bool(style.pivot_button),
    )
    existing = self._xf_index.get(key)
    if existing is not None:
        return existing
    index = len(self.xfs)
    alignment = _alignment_from_key(align_key)
    protection = _protection_from_key(prot_key)
    quote_prefix = bool(style.quote_prefix)
    pivot_button = bool(style.pivot_button)
    self.xfs.append(
        _Xf(
            font_id,
            fill_id,
            border_id,
            numfmt_id,
            alignment,
            protection,
            quote_prefix=quote_prefix,
            pivot_button=pivot_button,
        )
    )
    self.styles.append(style)
    self._xf_xml.append(
        self._xf_xml_for(
            font_id,
            fill_id,
            border_id,
            numfmt_id,
            align_key,
            prot_key,
            quote_prefix=quote_prefix,
            pivot_button=pivot_button,
        )
    )
    self._xf_index[key] = index
    return index

to_bytes

to_bytes() -> bytes

Serialise the table, preserving unrelated style children.

Source code in src/xlspy/workbook/_styles.py
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
def to_bytes(self) -> bytes:
    """Serialise the table, preserving unrelated style children."""
    if self._root is None:
        root = ET.Element(qname("styleSheet"))
        ET.SubElement(root, qname("fonts"), {"count": str(len(self._font_xml))})
        ET.SubElement(root, qname("fills"), {"count": str(len(self._fill_xml))})
        ET.SubElement(root, qname("borders"), {"count": str(len(self._border_xml))})
        cell_style_xfs = ET.SubElement(root, qname("cellStyleXfs"), {"count": "1"})
        ET.SubElement(
            cell_style_xfs,
            qname("xf"),
            {
                "numFmtId": "0",
                "fontId": "0",
                "fillId": "0",
                "borderId": "0",
            },
        )
        ET.SubElement(root, qname("cellXfs"), {"count": str(len(self._xf_xml))})
        cell_styles = ET.SubElement(root, qname("cellStyles"), {"count": "1"})
        ET.SubElement(
            cell_styles,
            qname("cellStyle"),
            {
                "name": "Normal",
                "xfId": "0",
                "builtinId": "0",
            },
        )
        ET.SubElement(root, qname("dxfs"), {"count": "0"})
        ET.SubElement(
            root,
            qname("tableStyles"),
            {
                "count": "0",
                "defaultTableStyle": "TableStyleMedium9",
                "defaultPivotStyle": "PivotStyleLight16",
            },
        )
        self._root = root

    root = self._root
    custom = []
    for num_id, code in sorted(self.num_formats.items()):
        if num_id in self.custom_num_formats:
            quoted = escape(code, {'"': "&quot;"})
            custom.append(f'<numFmt numFmtId="{num_id}" formatCode="{quoted}"/>')
    self._replace_container(root, "numFmts", custom, len(custom) if custom else None)
    self._replace_container(root, "fonts", self._font_xml, len(self._font_xml))
    self._replace_container(root, "fills", self._fill_xml, len(self._fill_xml))
    self._replace_container(root, "borders", self._border_xml, len(self._border_xml))
    self._replace_container(root, "cellXfs", self._xf_xml, len(self._xf_xml))
    source = getattr(self, "_source", None)
    if source is not None:
        # Keep Excel's prefixes: mc:Ignorable names them.
        return serialize_like(root, source)
    ET.register_namespace("", MAIN)
    return cast(bytes, ET.tostring(root, encoding="utf-8", xml_declaration=True))

append_dxfs

append_dxfs(fragments: list[str]) -> list[int]

Add differential formats; return the index of each in the table.

fragments are <dxf> elements in the main namespace. A format equal to one the table holds reuses it, so repeated edits do not leave unused copies behind. Number formats are given this table's ids, so that a format code keeps one id in the workbook.

Source code in src/xlspy/workbook/_styles.py
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
def append_dxfs(self, fragments: list[str]) -> list[int]:
    """Add differential formats; return the index of each in the table.

    ``fragments`` are ``<dxf>`` elements in the main namespace. A format
    equal to one the table holds reuses it, so repeated edits do not
    leave unused copies behind. Number formats are given this table's
    ids, so that a format code keeps one id in the workbook.
    """
    if self._root is None:
        self.to_bytes()
    root = self._root
    if root is None:  # to_bytes() sets it; this only narrows the type
        raise RuntimeError("style table has no XML root")
    container = next((child for child in root if _local(child.tag) == "dxfs"), None)
    if container is None:
        self._replace_container(root, "dxfs", [f'<dxf xmlns="{MAIN}"/>'])
        container = next(child for child in root if _local(child.tag) == "dxfs")
        container.clear()
    indexes = []
    for fragment in fragments:
        node = safe_fromstring(fragment)
        try:
            style = _read_differential(node)
        except (TypeError, ValueError):
            style = None
        if style is not None and style in self.dxfs[: len(container)]:
            indexes.append(self.dxfs.index(style))
            continue
        for numfmt in node.iter(qname("numFmt")):
            numfmt.set("numFmtId", str(self._intern_numfmt(numfmt.get("formatCode", "General"))))
        # Keep the parsed list in step with the container.
        del self.dxfs[len(container) :]
        self.dxfs.extend([None] * (len(container) - len(self.dxfs)))
        indexes.append(len(container))
        container.append(node)
        self.dxfs.append(style)
    container.set("count", str(len(container)))
    return indexes

style_at

style_at(index: int) -> Style

The Style of a cell format index; the default style for an index out of range.

Source code in src/xlspy/workbook/_styles.py
1065
1066
1067
1068
1069
def style_at(self, index: int) -> Style:
    """The Style of a cell format index; the default style for an index out of range."""
    if not 0 <= index < len(self.styles):
        return self.styles[0]
    return self.styles[index]

dxf_at

dxf_at(index: int | None) -> DifferentialStyle | None

The differential style at index, or None when there is none.

Source code in src/xlspy/workbook/_styles.py
1071
1072
1073
1074
1075
def dxf_at(self, index: int | None) -> DifferentialStyle | None:
    """The differential style at ``index``, or None when there is none."""
    if index is None or not 0 <= index < len(self.dxfs):
        return None
    return self.dxfs[index]

clone

clone() -> XlsxStyleTable

Return an independent copy of the table.

Source code in src/xlspy/workbook/_styles.py
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
def clone(self) -> XlsxStyleTable:
    """Return an independent copy of the table."""
    clone = XlsxStyleTable()
    clone._root = copy.deepcopy(self._root)
    clone.fonts = list(self.fonts)
    clone.fills = list(self.fills)
    clone.borders = list(self.borders)
    clone.num_formats = dict(self.num_formats)
    clone.custom_num_formats = set(self.custom_num_formats)
    clone.dxfs = list(self.dxfs)
    clone.named_styles = list(self.named_styles)
    clone.cell_style_xfs = list(self.cell_style_xfs)
    clone.named_style_defs = dict(self.named_style_defs)
    clone.xfs = list(self.xfs)
    clone.styles = list(self.styles)
    clone._font_keys = list(self._font_keys)
    clone._fill_keys = list(self._fill_keys)
    clone._border_keys = list(self._border_keys)
    clone._font_xml = list(self._font_xml)
    clone._fill_xml = list(self._fill_xml)
    clone._border_xml = list(self._border_xml)
    clone._xf_xml = list(self._xf_xml)
    clone._next_numfmt_id = self._next_numfmt_id
    clone._rebuild_indexes()
    return clone