Skip to content

Updating

Edits to existing files that keep everything else in the package.

API reference · Guide

XlsxUpdater

XlsxUpdater(path: str | PathLike[str])

Bases: _UpdaterBase, XlsxEditMixin, XlsxSheetsMixin

Replace the data region of sheets in an existing XLSX or XLSM file.

The workbook, styles, drawings and all unrelated ZIP members are kept in place. Only the selected worksheet XML, shared strings and pivot-cache metadata are changed. Macro parts in an XLSM package are copied as opaque ZIP members and are never parsed or rewritten.

Source code in src/xlspy/xlsx_updater.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def __init__(self, path: str | os.PathLike[str]) -> None:
    self._package = ZipPackage(path)
    try:
        if self._package.has("xl/workbook.bin"):
            raise ValueError("The input is XLSB; use XlsbUpdater")
        if not self._package.has("xl/workbook.xml"):
            raise InvalidFileError("XLSX workbook.xml was not found")
        if b"http://purl.oclc.org/ooxml/spreadsheetml/main" in self._package.get("xl/workbook.xml")[:4096]:
            # Edits write Transitional markup, which a Strict package must not mix.
            raise UnsupportedFeatureError(
                "Strict Open XML workbooks are supported for reading only "
                "(ExcelReader, load_workbook(read_only=True)); save as a regular .xlsx to edit"
            )
        with reading(path):
            self._date_1904 = self._load_date_system()
            self._sheets = self._load_sheet_structure()
    except BaseException:
        self._package.close()
        raise
    self._init_shared_string_state()
    self._shared_strings_prefix = ""
    self._use_shared_strings = False

get_sheet_states

get_sheet_states() -> dict[str, str]

Sheet visibility (visible, hidden or veryHidden) by name.

Source code in src/xlspy/_xlsx_sheets.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def get_sheet_states(self) -> dict[str, str]:
    """Sheet visibility (``visible``, ``hidden`` or ``veryHidden``) by name."""
    root = safe_fromstring(self._workbook_xml())
    states = {}
    for node in root.findall(f"{{{MAIN}}}sheets/{{{MAIN}}}sheet"):
        name = node.get("name")
        if name is None:
            continue
        state = node.get("state", "visible")
        states[name] = state if state in SHEET_STATES else "visible"
    return states

get_active_sheet

get_active_sheet() -> int

Index of the sheet Excel shows when the workbook opens.

Source code in src/xlspy/_xlsx_sheets.py
102
103
104
105
106
107
108
def get_active_sheet(self) -> int:
    """Index of the sheet Excel shows when the workbook opens."""
    root = safe_fromstring(self._workbook_xml())
    view = root.find(f"{{{MAIN}}}bookViews/{{{MAIN}}}workbookView")
    if view is None:
        return 0
    return _int_attribute(view.get("activeTab")) or 0

set_active_sheet

set_active_sheet(index: int) -> None

Make the sheet at 0-based index the active one.

Source code in src/xlspy/_xlsx_sheets.py
110
111
112
113
114
115
116
117
118
119
120
121
def set_active_sheet(self, index: int) -> None:
    """Make the sheet at 0-based ``index`` the active one."""
    if not 0 <= index < len(self._sheets):
        raise IndexError("active sheet index out of range")
    xml = self._workbook_xml()
    match = element_pattern("workbookView").search(xml)
    first = None
    if match is not None:
        first = _int_attribute(tag_attributes(_opening_tag(match.group(0))).get("firstSheet"))
    updated = _write_view(xml, index, first)
    if updated != xml:
        self._apply_parts({"xl/workbook.xml": updated})

set_sheet_state

set_sheet_state(name: str, state: str) -> None

Set a sheet to "visible", "hidden" or "veryHidden".

Source code in src/xlspy/_xlsx_sheets.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def set_sheet_state(self, name: str, state: str) -> None:
    """Set a sheet to ``"visible"``, ``"hidden"`` or ``"veryHidden"``."""
    check_sheet_state(state)
    xml = self._workbook_xml()
    found = False

    def change(match: re.Match[str]) -> str:
        nonlocal found
        opening = _opening_tag(match.group(0))
        if tag_attributes(opening).get("name") != name:
            return match.group(0)
        found = True
        return replace_or_add_xml_attribute(opening, "state", state) + match.group(0)[len(opening) :]

    updated = element_pattern("sheet").sub(change, xml)
    if not found:
        raise KeyError(f"Worksheet not found: {name}")
    if updated != xml:
        self._apply_parts({"xl/workbook.xml": updated})

add_sheet

add_sheet(name: str, index: int | None = None, *, state: str = 'visible') -> str

Add an empty worksheet at index (default: last); return its part path.

Source code in src/xlspy/_xlsx_sheets.py
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def add_sheet(self, name: str, index: int | None = None, *, state: str = "visible") -> str:
    """Add an empty worksheet at ``index`` (default: last); return its part path."""
    check_sheet_name(name, self._sheets)
    check_sheet_state(state)

    current = list(self._sheets)
    position = len(current) if index is None else max(0, min(index, len(current)))
    path = next_sheet_part(self._package.names(), "xml")
    xml = self._workbook_xml()
    root = safe_fromstring(xml)
    sheet_id = (
        max(
            (int(node.get("sheetId", "0") or 0) for node in root.findall(f"{{{MAIN}}}sheets/{{{MAIN}}}sheet")),
            default=0,
        )
        + 1
    )

    rels_path = "xl/_rels/workbook.xml.rels"
    rels = safe_fromstring(self._package.get(rels_path))
    rid = _next_relationship_id(rels)
    ET.SubElement(
        rels,
        f"{{{PKG_REL}}}Relationship",
        {
            "Id": rid,
            "Type": REL + "/worksheet",
            "Target": posixpath.relpath(path, "xl"),
        },
    )
    types = safe_fromstring(self._package.get("[Content_Types].xml"))
    ET.SubElement(
        types,
        f"{{{CT}}}Override",
        {"PartName": "/" + path, "ContentType": _WORKSHEET_CONTENT_TYPE},
    )

    state_attribute = "" if state == "visible" else f' state="{state}"'
    fragment = f'<sheet xmlns:r="{REL}" name={quoteattr(name)} sheetId="{sheet_id}" r:id="{rid}"{state_attribute}/>'
    xml = _splice_sheet_entry(xml, fragment, position)

    order = current[:position] + [name] + current[position:]
    mapping = {old: order.index(existing) for old, existing in enumerate(current)}
    previous_active = self.get_active_sheet()
    active = mapping.get(previous_active, previous_active)
    states = self.get_sheet_states()
    states[name] = state
    xml = _remap_active_and_first(xml, mapping, order, states, active)

    updates: dict[str, Any] = {
        "xl/workbook.xml": xml,
        path: _EMPTY_WORKSHEET,
        rels_path: _xml(rels),
        "[Content_Types].xml": _xml(types),
    }
    removed: list[str] = []
    self._recalculate(updates, removed)
    self._apply_parts(updates, removed)
    self._sheets = {sheet: (path if sheet == name else self._sheets[sheet]) for sheet in order}
    return path

remove_sheet

remove_sheet(name: str) -> None

Remove a sheet, its part and the parts only it refers to.

References to it become #REF! and names local to it are dropped.

Source code in src/xlspy/_xlsx_sheets.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def remove_sheet(self, name: str) -> None:
    """Remove a sheet, its part and the parts only it refers to.

    References to it become ``#REF!`` and names local to it are dropped.
    """
    path = self._sheets.get(name)
    if path is None:
        raise KeyError(f"Worksheet not found: {name}")
    if len(self._sheets) == 1:
        raise ValueError("a workbook must keep at least one sheet")
    package = self._package
    # As for XLSB: slicers and pivots own workbook-level caches that would
    # be left pointing at a removed sheet.
    if sheet_has_slicers(package, path):
        raise UnsupportedFeatureError(f"sheet {name!r} holds table slicers; removing it is not supported yet")
    if sheet_has_pivots(package, path):
        raise UnsupportedFeatureError(f"sheet {name!r} holds pivot tables; removing it is not supported yet")

    current = list(self._sheets)
    removed_index = current.index(name)
    order = [sheet for sheet in current if sheet != name]
    xml = self._workbook_xml()
    xml, rid = _remove_sheet_entry(xml, name)
    xml = _strip_local_sheet_names(xml, removed_index)
    mapping = {old: order.index(sheet) for old, sheet in enumerate(current) if sheet != name}
    previous_active = self.get_active_sheet()
    active = mapping.get(previous_active, min(previous_active, len(order) - 1))
    states = self.get_sheet_states()
    states.pop(name, None)
    xml = _remap_active_and_first(xml, mapping, order, states, active)

    rels_path = "xl/_rels/workbook.xml.rels"
    rels = safe_fromstring(package.get(rels_path))
    for node in list(rels):
        if rid is not None and node.get("Id") == rid:
            rels.remove(node)
    types = safe_fromstring(package.get("[Content_Types].xml"))

    removed: list[str] = []
    skip = {_part_rels_path(path)}
    _drop_sheet_part_tree(package, path, removed, skip)
    _remove_part_overrides(types, removed)

    updates: dict[str, Any] = {
        "xl/workbook.xml": xml,
        rels_path: _xml(rels),
        "[Content_Types].xml": _xml(types),
    }
    self._recalculate(updates, removed)
    self._apply_parts(updates, removed)
    self._sheets = {sheet: self._sheets[sheet] for sheet in order}
    self._chartsheets.discard(name)

rename_sheet

rename_sheet(old: str, new: str) -> None

Rename sheet old to new; raises KeyError when old is absent.

Source code in src/xlspy/_xlsx_sheets.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def rename_sheet(self, old: str, new: str) -> None:
    """Rename sheet ``old`` to ``new``; raises KeyError when ``old`` is absent."""
    if old not in self._sheets:
        raise KeyError(f"Worksheet not found: {old}")
    if old == new:
        return
    check_sheet_name(new, [name for name in self._sheets if name != old])
    workbook_xml = self._workbook_xml()
    updated, found = _rename_sheet_entry(workbook_xml, old, new)
    if not found:
        raise KeyError(f"Worksheet not found: {old}")
    updated = _rename_defined_names(updated, old, new)
    updates: dict[str, Any] = {"xl/workbook.xml": updated}
    updates.update(_renamed_reference_parts(self._package, old, new))
    updates.update(renamed_chart_parts(self._package, old, new))
    self._apply_parts(updates)
    self._sheets = {(new if name == old else name): path for name, path in self._sheets.items()}
    if old in self._chartsheets:
        self._chartsheets.discard(old)
        self._chartsheets.add(new)

reorder_sheets

reorder_sheets(order: Iterable[str]) -> None

Put the sheets in order (every sheet name, once).

Source code in src/xlspy/_xlsx_sheets.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def reorder_sheets(self, order: Iterable[str]) -> None:
    """Put the sheets in ``order`` (every sheet name, once)."""
    order = list(order)
    current = list(self._sheets)
    if sorted(order) != sorted(current):
        raise ValueError("order must list every sheet exactly once")
    if order == current:
        return

    xml = self._workbook_xml()
    container = element_pattern("sheets").search(xml)
    if container is None:
        raise ValueError("workbook.xml sheets element was not found")
    body = container.group(0)
    by_name = {
        tag_attributes(match.group(0)).get("name"): match.group(0)
        for match in element_pattern("sheet").finditer(body)
    }
    if any(name not in by_name for name in order):
        raise ValueError("order must list every sheet exactly once")
    opening_end = body.index(">") + 1
    closing_start = body.rfind("</")
    reordered = "".join(by_name[name] for name in order)
    body = body[:opening_end] + reordered + body[closing_start:]
    xml = xml[: container.start()] + body + xml[container.end() :]

    mapping = {}
    for new, name in enumerate(order):
        mapping[current.index(name)] = new
    xml = element_pattern("definedName").sub(lambda match: _remap_local_sheet_id(match, mapping), xml)
    active = self.get_active_sheet()
    active = mapping.get(active, active)
    states = self.get_sheet_states()
    xml = _remap_active_and_first(xml, mapping, order, states, active)

    updates: dict[str, Any] = {"xl/workbook.xml": xml}
    removed: list[str] = []
    self._recalculate(updates, removed)
    self._apply_parts(updates, removed)
    self._sheets = {name: self._sheets[name] for name in order}

get_comments

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

Read classic note text and authors from the current staged package.

Source code in src/xlspy/_xlsx_edit.py
165
166
167
168
169
def get_comments(self, sheet_name: str) -> dict[str, Comment]:
    """Read classic note text and authors from the current staged package."""
    path, _ = self._sheet_xml(sheet_name)
    _, _, parts = find_comment_parts(self._package.get, self._package.names(), path)
    return read_comments(self._package.get(parts["comments"][0])) if "comments" in parts else {}

get_threaded_comments

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

Read Excel 365 conversations from the current staged package.

Source code in src/xlspy/_xlsx_edit.py
171
172
173
174
175
176
177
178
179
180
def get_threaded_comments(self, sheet_name: str) -> dict[str, ThreadedComment]:
    """Read Excel 365 conversations from the current staged package."""
    path, _ = self._sheet_xml(sheet_name)
    names = self._package.names()
    part = find_threaded_part(self._package.get, names, path)
    if part is None:
        return {}
    people_part = find_person_part(self._package.get, names, "xl/workbook.xml")
    people = read_persons(self._package.get(people_part[0])) if people_part is not None else {}
    return read_threaded_comments(self._package.get(part[0]), people)

set_comments

set_comments(sheet_name: str, comments: Mapping[str, Comment | None]) -> None

Set selected classic notes; None removes a note, other notes are kept.

Source code in src/xlspy/_xlsx_edit.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def set_comments(self, sheet_name: str, comments: Mapping[str, Comment | None]) -> None:
    """Set selected classic notes; None removes a note, other notes are kept."""
    path, sheet, sheet_root = self._sheet_root(sheet_name)
    merges = [n.attrib["ref"] for n in sheet_root.findall(f"{{{MAIN}}}mergeCells/{{{MAIN}}}mergeCell")]
    changes = normalize_comments(comments, allow_none=True, merges=merges)
    if not changes:
        return
    names = self._package.names()
    legacy = sheet_root.find(f"{{{MAIN}}}legacyDrawing")
    legacy_rid = None if legacy is None else legacy.get(f"{{{REL}}}id")
    rp, relationships, parts = find_comment_parts(self._package.get, names, path, legacy_rid)
    for relationship in relationships:
        if relationship.get("Type", "").rsplit("/", 1)[-1] in {"threadedComment", "threadedComments"}:
            threaded = safe_fromstring(self._package.get(resolve_part(path, relationship.attrib["Target"])))
            occupied = {cell_ref(node.attrib["ref"]) for node in threaded if "ref" in node.attrib}
            if any(ref in occupied and value is not None for ref, value in changes.items()):
                raise ValueError("a classic note cannot replace a threaded comment")
    current = (
        read_comments(self._package.get(parts["comments"][0]), include_threaded=True) if "comments" in parts else {}
    )
    changes = {ref: value for ref, value in changes.items() if value is not None or ref in current}
    if not changes:
        return
    for other_path in self._sheets.values():
        if other_path == path:
            continue
        other = comment_part_targets(self._package.get, names, other_path)
        if any(value[0] in other for value in parts.values()):
            raise ValueError("editing comment/VML parts shared by worksheets is unsupported")
    if legacy is not None and "vmlDrawing" not in parts:
        raise ValueError("unsupported legacy drawing relationship")

    edit = NotePartsEdit(path, relationships, parts, names)
    cp = edit.ensure("comments", "xl/comments", "comment", "xml")
    vp = edit.ensure("vmlDrawing", "xl/drawings", "commentsDrawing", "vml")
    comment_data = comments_xml(changes, self._package.get(cp) if cp in names else None)
    vml_data = vml_xml(changes, self._package.get(vp) if vp in names else None)
    remaining = read_comments(comment_data, include_threaded=True)
    removed: list[str] = []
    updates: dict[str, Any] = {cp: comment_data, vp: vml_data}
    types = safe_fromstring(self._package.get("[Content_Types].xml"))

    if not remaining:
        edit.drop(cp, "comments", types, updates, removed)
    elif not any(n.get("PartName") == "/" + cp for n in types):
        ET.SubElement(types, f"{{{CT}}}Override", {"PartName": "/" + cp, "ContentType": COMMENTS_TYPE})
    has_shapes = any(n.tag == f"{{{V}}}shape" for n in safe_fromstring(vml_data).iter())
    if not has_shapes:
        edit.drop(vp, "vmlDrawing", types, updates, removed)
        sheet = replace_element(sheet, "legacyDrawing", "")
    else:
        # Use a part override: it cannot alter another VML part's type.
        if not any(n.get("PartName") == "/" + vp for n in types) and not any(
            n.get("Extension") == "vml" for n in types
        ):
            ET.SubElement(types, f"{{{CT}}}Override", {"PartName": "/" + vp, "ContentType": VML_TYPE})
        if legacy is None:
            fragment = f'<legacyDrawing xmlns="{MAIN}" xmlns:r="{REL}" r:id="{parts["vmlDrawing"][1]}"/>'
            sheet = replace_element(
                sheet,
                "legacyDrawing",
                fragment,
                before=(
                    "legacyDrawingHF",
                    "picture",
                    "oleObjects",
                    "controls",
                    "webPublishItems",
                    "tableParts",
                    "extLst",
                ),
            )
    updates[path] = sheet
    if len(relationships):
        updates[rp] = element_bytes(relationships)
    elif rp in names:
        removed.append(rp)
    updates["[Content_Types].xml"] = element_bytes(types)
    self._apply_parts(updates, removed)

set_threaded_comments

set_threaded_comments(sheet_name: str, comments: Mapping[str, ThreadedComment | None]) -> None

Set selected Excel 365 conversations; None removes a conversation.

The first message of each conversation owns its replies. Excel needs a classic note whose author is tc={id} to link a conversation to its cell, so this method writes that companion note too.

Source code in src/xlspy/_xlsx_edit.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
def set_threaded_comments(self, sheet_name: str, comments: Mapping[str, ThreadedComment | None]) -> None:
    """Set selected Excel 365 conversations; None removes a conversation.

    The first message of each conversation owns its replies. Excel needs a
    classic note whose author is ``tc={id}`` to link a conversation to its
    cell, so this method writes that companion note too.
    """
    path, sheet, sheet_root = self._sheet_root(sheet_name)
    merges = [n.attrib["ref"] for n in sheet_root.findall(f"{{{MAIN}}}mergeCells/{{{MAIN}}}mergeCell")]
    changes = normalize_threaded_comments(comments, allow_none=True, merges=merges)
    if not changes:
        return
    names = set(self._package.names())
    legacy = sheet_root.find(f"{{{MAIN}}}legacyDrawing")
    legacy_rid = None if legacy is None else legacy.get(f"{{{REL}}}id")
    rp, relationships, parts = find_comment_parts(self._package.get, names, path, legacy_rid)

    existing_comments = (
        read_comments(self._package.get(parts["comments"][0]), include_threaded=True) if "comments" in parts else {}
    )
    classic_notes = {
        ref: comment for ref, comment in existing_comments.items() if not is_threaded_companion(comment)
    }
    replaced = [ref for ref, thread in changes.items() if thread is not None and ref in classic_notes]
    if replaced:
        raise ValueError(f"a threaded comment cannot replace the classic note on {replaced[0]}")

    threaded = find_threaded_part(self._package.get, names, path)
    people_part = find_person_part(self._package.get, names, "xl/workbook.xml")
    people = read_persons(self._package.get(people_part[0])) if people_part is not None else {}
    current_threads = read_threaded_comments(self._package.get(threaded[0]), people) if threaded is not None else {}
    updated_threads = dict(current_threads)
    for ref, thread in changes.items():
        if thread is None:
            updated_threads.pop(ref, None)
        else:
            updated_threads[ref] = thread

    updated_data = None
    if updated_threads:
        updated_data, _ = threaded_comments_xml(
            updated_threads,
            existing=self._package.get(threaded[0]) if threaded is not None else None,
            changed=set(changes),
            persons=people,
            scope=path,
        )

    updates: dict[str, Any] = {}
    removed: list[str] = []
    types = safe_fromstring(self._package.get("[Content_Types].xml"))

    companion_changes = self._threaded_companion_changes(changes, existing_comments)
    if companion_changes:
        sheet = self._write_threaded_companions(
            path, sheet, parts, relationships, names, legacy, types, updates, removed, companion_changes
        )
    self._write_threaded_part(
        path, names, relationships, threaded, updated_threads, updated_data, types, updates, removed
    )
    self._write_people_part(path, names, people, people_part, updated_threads, types, updates, removed)

    if len(relationships):
        updates[rp] = element_bytes(relationships)
    elif rp in names:
        removed.append(rp)
    updates["[Content_Types].xml"] = element_bytes(types)
    self._apply_parts(updates, removed)
set_hyperlinks(sheet_name: str, links: Mapping[str, Hyperlink | None]) -> None

Set selected cells' hyperlinks; None removes one, other links are kept.

Only the link changes: the cell's value and style stay as they are. A link whose range starts at a given cell is replaced as a whole.

Source code in src/xlspy/_xlsx_edit.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
def set_hyperlinks(self, sheet_name: str, links: Mapping[str, Hyperlink | None]) -> None:
    """Set selected cells' hyperlinks; None removes one, other links are kept.

    Only the link changes: the cell's value and style stay as they are. A
    link whose range starts at a given cell is replaced as a whole.
    """
    path, sheet = self._sheet_xml(sheet_name)
    changes = {}
    for ref, link in links.items():
        if link is not None and not isinstance(link, Hyperlink):
            raise TypeError("hyperlinks must be xlspy Hyperlink objects or None")
        changes[cell_ref(ref)] = link
    if not changes:
        return
    rp = rels_path(path)
    names = self._package.names()
    relationships = (
        safe_fromstring(self._package.get(rp)) if rp in names else ET.Element(f"{{{PKG_REL}}}Relationships")
    )
    prefix = self._tag_prefix(sheet, "worksheet")
    container = element_pattern("hyperlinks").search(sheet)
    kept: list[Any] = []
    dropped: set[Any] = set()
    if container:
        for match in element_pattern("hyperlink").finditer(container[0]):
            attrs = tag_attributes(match[0])
            try:
                first_col, first_row, _, _ = parse_cell_range(attrs.get("ref", "").split()[0])
                start = f"{column_label(first_col)}{first_row + 1}"
            except (IndexError, ValueError):
                start = None
            if start in changes:
                dropped.update(value for key, value in attrs.items() if key.endswith(":id"))
            else:
                kept.append(match[0])

    used_ids = {node.get("Id") for node in relationships}
    added = []
    index = 1  # Ids only get taken here, so the first free one never moves back.
    for ref, link in changes.items():
        if link is None:
            continue
        text = f' ref="{ref}"'
        if link.is_internal:
            text += f" location={quoteattr(xml_text(link.location))}"
        else:
            while f"rId{index}" in used_ids:
                index += 1
            rid = f"rId{index}"
            used_ids.add(rid)
            ET.SubElement(
                relationships,
                f"{{{PKG_REL}}}Relationship",
                {
                    "Id": rid,
                    "Type": HYPERLINK_TYPE,
                    "Target": xml_text(link.target),
                    "TargetMode": "External",
                },
            )
            text += f' xmlns:r="{REL}" r:id="{rid}"'
        if link.text is not None:
            text += f" display={quoteattr(xml_text(link.text))}"
        if link.tooltip is not None:
            text += f" tooltip={quoteattr(xml_text(link.tooltip))}"
        added.append(f"<{prefix}hyperlink{text}/>")

    items = kept + added
    fragment = f"<{prefix}hyperlinks>{''.join(items)}</{prefix}hyperlinks>" if items else ""
    sheet = replace_element(sheet, "hyperlinks", fragment, before=_AFTER_HYPERLINKS)
    # A dropped link's relationship goes unless something else uses it.
    if dropped:
        still_used = set(re.findall(r"""[\w.-]+:id=["']([^"']*)["']""", sheet))
        for node in list(relationships):
            rel_id = node.get("Id")
            if (
                rel_id is not None
                and rel_id in dropped
                and rel_id not in still_used
                and node.get("Type") == HYPERLINK_TYPE
            ):
                relationships.remove(node)
    updates: dict[str, str | bytes] = {path: sheet}
    removed: list[str] = []
    ET.register_namespace("", PKG_REL)
    if len(relationships):
        updates[rp] = element_bytes(relationships)
    elif rp in names:
        removed.append(rp)
    self._apply_parts(updates, removed)

get_defined_names

get_defined_names() -> list[DefinedName]

Return user-defined global and worksheet-local names.

Source code in src/xlspy/_xlsx_edit.py
615
616
617
def get_defined_names(self) -> list[DefinedName]:
    """Return user-defined global and worksheet-local names."""
    return read_defined_names(self._package.get("xl/workbook.xml"), self._workbook_sheets())

set_defined_name

set_defined_name(definition: DefinedName) -> None

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

Source code in src/xlspy/_xlsx_edit.py
619
620
621
def set_defined_name(self, definition: DefinedName) -> None:
    """Add a defined name, replacing one with the same name and scope."""
    self.set_defined_names([definition])

set_defined_names

set_defined_names(definitions: Iterable[DefinedName]) -> None

Add many defined names in one workbook rewrite (linear, not quadratic).

Source code in src/xlspy/_xlsx_edit.py
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
def set_defined_names(self, definitions: Iterable[DefinedName]) -> None:
    """Add many defined names in one workbook rewrite (linear, not quadratic)."""
    definitions = list(definitions)
    for definition in definitions:
        if not isinstance(definition, DefinedName):
            raise TypeError("definition must be DefinedName")
    if not definitions:
        return
    sheets = self._workbook_sheets()
    resolved = [self._resolve_defined_name(definition, sheets) for definition in definitions]
    # Last wins on (name, scope), like sequential set_defined_name and XLSB.
    deduped: dict[tuple[str, str | None], DefinedName] = {}
    for definition in resolved:
        key = (definition.name.casefold(), definition.scope)
        if key in deduped:
            del deduped[key]
        deduped[key] = definition
    resolved = list(deduped.values())
    fragments = [definition.to_xml(sheets) for definition in resolved]
    xml = self._package.get("xl/workbook.xml").decode("utf-8")
    for definition in resolved:
        xml = self._remove_name(xml, definition.name, definition.scope, sheets)
    combined = "".join(fragments)
    if element_pattern("definedNames").search(xml):
        xml = append_child(xml, "definedNames", combined)
    else:
        xml = replace_element(
            xml,
            "definedNames",
            f'<definedNames xmlns="{MAIN}">{combined}</definedNames>',
            before=(
                "calcPr",
                "oleSize",
                "customWorkbookViews",
                "pivotCaches",
                "smartTagPr",
                "smartTagTypes",
                "webPublishing",
                "fileRecoveryPr",
                "webPublishObjects",
                "extLst",
            ),
        )
    self._apply_name_change(xml)

remove_defined_name

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

Remove a defined name; with scope, the one local to that sheet.

Source code in src/xlspy/_xlsx_edit.py
692
693
694
def remove_defined_name(self, name: str, scope: str | None = None) -> None:
    """Remove a defined name; with ``scope``, the one local to that sheet."""
    self.remove_defined_names([(name, scope)])

remove_defined_names

remove_defined_names(names: Iterable[tuple[str, str | None]]) -> None

Remove many defined names in one workbook rewrite.

Source code in src/xlspy/_xlsx_edit.py
696
697
698
699
700
701
702
703
704
705
706
707
708
709
def remove_defined_names(self, names: Iterable[tuple[str, str | None]]) -> None:
    """Remove many defined names in one workbook rewrite."""
    names = list(names)
    if not names:
        return
    sheets = self._workbook_sheets()
    for name, scope in names:
        DefinedName(name, "0", scope).to_xml(sheets)
    xml = self._package.get("xl/workbook.xml").decode("utf-8")
    updated = xml
    for name, scope in names:
        updated = self._remove_name(updated, name, scope, sheets)
    if updated != xml:
        self._apply_name_change(updated)

set_sheet_protection

set_sheet_protection(sheet_name: str, protection: SheetProtection) -> None

Set or replace the protection of a sheet.

Source code in src/xlspy/_xlsx_edit.py
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
def set_sheet_protection(self, sheet_name: str, protection: SheetProtection) -> None:
    """Set or replace the protection of a sheet."""
    if not isinstance(protection, SheetProtection):
        raise TypeError("protection must be SheetProtection")
    path, xml = self._sheet_xml(sheet_name)
    xml = replace_element(
        xml,
        "sheetProtection",
        protection.to_xml(),
        before=(
            "protectedRanges",
            "scenarios",
            "autoFilter",
            "sortState",
            "dataConsolidate",
            "customSheetViews",
            "mergeCells",
            "phoneticPr",
            "conditionalFormatting",
            "dataValidations",
            "hyperlinks",
            "printOptions",
            "pageMargins",
            "pageSetup",
            "headerFooter",
            "rowBreaks",
            "colBreaks",
            "drawing",
            "legacyDrawing",
            "tableParts",
            "extLst",
        ),
    )
    self._apply_parts({path: xml})

set_merged_cells

set_merged_cells(sheet_name: str, ranges: Iterable[str]) -> None

Replace the sheet's merged ranges with ranges (A1 range strings).

Source code in src/xlspy/_xlsx_edit.py
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
def set_merged_cells(self, sheet_name: str, ranges: Iterable[str]) -> None:
    """Replace the sheet's merged ranges with ``ranges`` (A1 range strings)."""
    path, xml = self._sheet_xml(sheet_name)
    refs = normalize_merges(ranges)
    fragment = ""
    if refs:
        cells = "".join(f"<mergeCell ref={quoteattr(ref)}/>" for ref in refs)
        fragment = f'<mergeCells xmlns="{MAIN}" count="{len(refs)}">{cells}</mergeCells>'
    updated = replace_element(
        xml,
        "mergeCells",
        fragment,
        before=("phoneticPr", "conditionalFormatting", "dataValidations", "hyperlinks", *_AFTER_HYPERLINKS),
    )
    if updated != xml:
        self._apply_parts({path: updated})

set_data_validations

set_data_validations(sheet_name: str, rules: Sequence[DataValidation]) -> None

Replace the sheet's data validation rules with rules.

Source code in src/xlspy/_xlsx_edit.py
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
def set_data_validations(self, sheet_name: str, rules: Sequence[DataValidation]) -> None:
    """Replace the sheet's data validation rules with ``rules``."""
    rules = normalize_validations(rules)
    path, xml = self._sheet_xml(sheet_name)
    fragment = ""
    if rules:
        body = "".join(data_validation_xml(rule) for rule in rules)
        fragment = f'<dataValidations xmlns="{MAIN}" count="{len(rules)}">{body}</dataValidations>'
    updated = replace_element(
        xml,
        "dataValidations",
        fragment,
        before=("hyperlinks", *_AFTER_HYPERLINKS),
    )
    if updated != xml:
        self._apply_parts({path: updated})

set_workbook_protection

set_workbook_protection(protection: WorkbookProtection) -> None

Set or replace the workbook protection.

Source code in src/xlspy/_xlsx_edit.py
780
781
782
783
784
785
786
def set_workbook_protection(self, protection: WorkbookProtection) -> None:
    """Set or replace the workbook protection."""
    if not isinstance(protection, WorkbookProtection):
        raise TypeError("protection must be WorkbookProtection")
    xml = self._package.get("xl/workbook.xml").decode("utf-8")
    xml = replace_element(xml, "workbookProtection", protection.to_xml(), before=("bookViews", "sheets"))
    self._apply_parts({"xl/workbook.xml": xml})

update_cells

update_cells(sheet_name: str, cells: Mapping[str, object], *, styles: Mapping[str, int] | None = None) -> None

Update sparse cells, preserving styles, notes and untouched cell XML.

styles maps addresses to cell XF indexes. An address only in styles keeps its value (or becomes a styled blank).

Source code in src/xlspy/_xlsx_edit.py
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
def update_cells(
    self, sheet_name: str, cells: Mapping[str, object], *, styles: Mapping[str, int] | None = None
) -> None:
    """Update sparse cells, preserving styles, notes and untouched cell XML.

    ``styles`` maps addresses to cell XF indexes. An address only in
    ``styles`` keeps its value (or becomes a styled blank).
    """
    path, xml, root, fast = self._sheet_scan_source(sheet_name)
    values, style_ids, targets = self._normalize_cell_edits(
        cells,
        styles,
        cells_error="cells must map cell references to values",
        styles_error="styles must map cell references to XF indexes",
        duplicate_error="duplicate cell reference: {ref}",
        keep=_KEEP,
    )
    if not targets:
        return
    scan = self._scan_cell_targets(xml, root, fast, values)
    self._check_cell_targets(scan, values)
    sheet_data = fast.sheet_data if fast is not None else sheet_data_match(xml)
    if sheet_data is None:
        raise ValueError("Worksheet sheetData element was not found")
    xml = self._patch_sheet_cell_targets(xml, sheet_data, scan, values, style_ids, targets)
    updates = {path: xml}
    removed: list[str] = []
    removed_shared_refs = self._update_shared_strings_count(updates, scan)
    self._recalculate_if_needed(updates, removed, scan, values)
    self._apply_parts(updates, removed)
    self._account_removed_shared_strings(removed_shared_refs)

close

close() -> None

Release temporary files held by the updater.

While in use, the updater keeps shared-string data and staged package parts on disk. Calling close (or simply dropping the updater) removes them.

Source code in src/xlspy/_updater_base.py
82
83
84
85
86
87
88
89
90
91
92
def close(self) -> None:
    """Release temporary files held by the updater.

    While in use, the updater keeps shared-string data and staged package
    parts on disk.  Calling ``close`` (or simply dropping the updater)
    removes them.
    """

    if self._stream_shared_strings is not None:
        self._stream_shared_strings.close()
    self._package.close()

get_sheet_names

get_sheet_names() -> list[str]

Return worksheet and chartsheet names in workbook order.

Source code in src/xlspy/_updater_base.py
112
113
114
115
def get_sheet_names(self) -> list[str]:
    """Return worksheet and chartsheet names in workbook order."""

    return list(self._sheets)

get_worksheet_names

get_worksheet_names() -> list[str]

The names of the worksheets alone, in workbook order.

Source code in src/xlspy/_updater_base.py
117
118
119
120
def get_worksheet_names(self) -> list[str]:
    """The names of the worksheets alone, in workbook order."""

    return [name for name in self._sheets if name not in self._chartsheets]

get_chartsheet_names

get_chartsheet_names() -> list[str]

The chartsheet names, in workbook order.

Source code in src/xlspy/_updater_base.py
122
123
124
125
def get_chartsheet_names(self) -> list[str]:
    """The chartsheet names, in workbook order."""

    return [name for name in self._sheets if name in self._chartsheets]

replace_sheet_data

replace_sheet_data(sheet_name: str, rows: Iterable[Sequence[Any]], *, headers: Sequence[str] | None = None, style_fallback: StyleFallback = 'inherit') -> None

Replace one worksheet's used data region.

rows is materialised once, so generators are supported but the operation remains atomic with respect to the in-memory package. A (value, format_string) cell is accepted for compatibility with the writers; its value is used and no new style is created. Once a streaming shared-string store is loaded, the call is forwarded to replace_sheet_data_stream.

Source code in src/xlspy/_updater_base.py
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
157
158
159
160
161
def replace_sheet_data(
    self,
    sheet_name: str,
    rows: Iterable[Sequence[Any]],
    *,
    headers: Sequence[str] | None = None,
    style_fallback: StyleFallback = "inherit",
) -> None:
    """Replace one worksheet's used data region.

    ``rows`` is materialised once, so generators are supported but the
    operation remains atomic with respect to the in-memory package. A
    ``(value, format_string)`` cell is accepted for compatibility with the
    writers; its value is used and no new style is created. Once a
    streaming shared-string store is loaded, the call is forwarded to
    ``replace_sheet_data_stream``.
    """

    sheet_path = self._replacement_sheet_path(sheet_name, style_fallback)
    if self._stream_shared_strings is not None:
        self.replace_sheet_data_stream(
            sheet_name,
            rows,
            headers=headers,
            style_fallback=style_fallback,
        )
        return
    materialized, header_values = self._checked_rows(sheet_name, sheet_path, rows, headers)
    self._replace_loaded_rows(
        sheet_name,
        sheet_path,
        materialized,
        header_values,
        style_fallback,
    )

replace_sheet_data_stream

replace_sheet_data_stream(sheet_name: str, rows: Iterable[Sequence[Any]], *, headers: Sequence[str] | None = None, style_fallback: StyleFallback = 'inherit') -> None

Replace worksheet data atomically while streaming rows.

The package and disk-backed shared-string index are committed only after the one-pass row source and all metadata updates succeed. A failure therefore leaves this updater reusable for a later attempt.

Source code in src/xlspy/_updater_base.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def replace_sheet_data_stream(
    self,
    sheet_name: str,
    rows: Iterable[Sequence[Any]],
    *,
    headers: Sequence[str] | None = None,
    style_fallback: StyleFallback = "inherit",
) -> None:
    """Replace worksheet data atomically while streaming rows.

    The package and disk-backed shared-string index are committed only
    after the one-pass row source and all metadata updates succeed.  A
    failure therefore leaves this updater reusable for a later attempt.
    """

    self._replacement_sheet_path(sheet_name, style_fallback)
    self._ensure_stream_shared_strings()
    store = self._stream_shared_strings
    self._package.begin_transaction()
    try:
        if store is not None:
            store.begin_transaction()
        self._replace_sheet_data_stream_impl(
            sheet_name,
            rows,
            headers=headers,
            style_fallback=style_fallback,
        )
        self._package.commit_transaction()
        if store is not None:
            store.commit_transaction()
    except BaseException:
        if store is not None:
            store.rollback_transaction()
        self._package.rollback_transaction()
        raise

save

save(output_path: str | PathLike[str] | None = None) -> None

Save to a new path or atomically replace the input file.

Source code in src/xlspy/_updater_base.py
317
318
319
320
def save(self, output_path: str | os.PathLike[str] | None = None) -> None:
    """Save to a new path or atomically replace the input file."""

    self._package.save(output_path)

to_bytes

to_bytes() -> bytes

Return the current package as bytes in the updater's format.

Source code in src/xlspy/_updater_base.py
322
323
324
325
def to_bytes(self) -> bytes:
    """Return the current package as bytes in the updater's format."""

    return self._package.to_bytes()

XlsmUpdater module-attribute

XlsmUpdater = XlsxUpdater

XlsbUpdater

XlsbUpdater(path: str | PathLike[str])

Bases: _UpdaterBase, XlsbSheetsMixin, XlsbEditMixin

Replace the data region of sheets in an existing XLSB file.

Source code in src/xlspy/xlsb_updater.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def __init__(self, path: str | os.PathLike[str]) -> None:
    self._package = ZipPackage(path)
    try:
        if self._package.has("xl/workbook.xml"):
            raise ValueError("The input is XLSX; use XlsxUpdater")
        if not self._package.has("xl/workbook.bin"):
            raise InvalidFileError("XLSB workbook.bin was not found")
        with reading(path):
            self._date_1904 = self._load_date_system()
            self._sheets = self._load_sheet_structure()
    except BaseException:
        self._package.close()
        raise
    self._init_shared_string_state()
    self._shared_strings_data: bytes | None = None
    self._replace_formula_context: FormulaContext | None = None

DataValidation dataclass

DataValidation(type: str, sqref: str | tuple[str, ...] | list[str], formula1: object = None, formula2: object = None, operator: str | None = None, allow_blank: bool = True, show_dropdown: bool = True, show_input_message: bool = False, prompt_title: str | None = None, prompt: str | None = None, show_error_message: bool = True, error_title: str | None = None, error: str | None = None, error_style: str = 'stop', ime_mode: str | None = None)

A validation rule applied to one or more cell ranges.

type is one of list, whole, decimal, date, time, text_length or custom. For list the formula1 is either a literal list such as '"New,Active,Closed"' or a range such as "Lists!$A$2:$A$9". For custom it is a formula that must evaluate to true for valid input. operator applies to the numeric, date, time and text-length types only, and defaults to between.

show_dropdown=False hides the arrow of a list rule. allow_blank accepts empty cells. Prompts and error messages are shown when their show_* flag is true.

Examples:

Add a dropdown, a numeric range and a date rule to one sheet:

import datetime

from xlspy import DataValidation, XlsxWriter

rows = [["Region", "Amount", "Date"], ["North", 10, datetime.date(2026, 1, 5)]]
with XlsxWriter("validated.xlsx") as workbook:
    workbook.add_sheet("Data")
    workbook.write_sheet(
        rows,
        data_validations=[
            DataValidation("list", "A2:A50", formula1='"North,South,East"'),
            DataValidation("whole", "B2:B50", formula1=1, formula2=100),
            DataValidation("date", "C2:C50", formula1=datetime.date(2026, 1, 1),
                           operator="greater_than"),
        ],
    )

Invalid combinations raise ValueError when the rule is created.

See Also

Formula for custom rules, and ExcelTable for structured references in a validation formula.

ooxml_type property

ooxml_type: str

The OOXML name of type.

allowBlank property

allowBlank: bool

openpyxl's name for allow_blank.

showDropDown property

showDropDown: bool

openpyxl's raw OOXML flag: True hides the in-cell list.

It is the inverse of show_dropdown.

showErrorMessage property

showErrorMessage: bool

openpyxl's name for show_error_message.

showInputMessage property

showInputMessage: bool

openpyxl's name for show_input_message.

errorStyle property

errorStyle: str

openpyxl's name for error_style.

errorTitle property

errorTitle: str | None

openpyxl's name for error_title.

promptTitle property

promptTitle: str | None

openpyxl's name for prompt_title.

imeMode property

imeMode: str | None

openpyxl's name for ime_mode.

Hyperlink(target: str, text: str | None = None, tooltip: str | None = None)

A link written as the value of a cell.

target is an http, https, mailto or ftp URL, or an internal location written as "#Sheet Name!B2" (quote the sheet name with single quotes when it contains spaces: "#'Sales Data'!B2"). Other schemes and relative file paths are refused. text is the displayed label and defaults to the target; tooltip is shown on hover. Linked cells use the built-in hyperlink look unless the cell has its own style.

Examples:

A Hyperlink is a cell value, so it goes where the text belongs:

from xlspy import Hyperlink, XlsxWriter

rows = [
    ["Report", Hyperlink("https://example.com/report", text="Open report")],
    ["Back", Hyperlink("#Links!A1", text="Back to top")],
]
with XlsxWriter("links.xlsx") as workbook:
    workbook.add_sheet("Links")
    workbook.write_sheet(rows)
See Also

Comment for a note attached to a cell, and Shape for a linked shape.

is_internal property

is_internal: bool

True for a link to a place in the workbook (a target that starts with #).

location property

location: str

The Sheet!A1 form of an internal link.

display_text property

display_text: str

The text shown in the cell: text, or the target when there is none.

ThreadedComment dataclass

ThreadedComment(text: str, author: str, created: datetime | None = None, resolved: bool = False, id: str | None = None, replies: list[ThreadedComment] = list(), _person: Person | None = None, _parent_id: str | None = None)

One message in an Excel 365 threaded conversation.

The first message owns replies and resolved. Replies are one level deep; reply() appends one. created is optional: when it is None the message carries no timestamp, which keeps a save deterministic. id is generated on save when it is None.

Examples:

Write a conversation and a reply into a new workbook:

from xlspy import ThreadedComment, XlsxWriter

thread = ThreadedComment("Confirm the amount", "Jan")
thread.reply("Confirmed", "Ola")
with XlsxWriter("review.xlsx") as workbook:
    workbook.add_sheet("Data")
    workbook.write_sheet(
        [["Amount"], [120]],
        threaded_comments={"A2": thread},
    )
See Also

Comment for classic notes, and XlsxUpdater.set_threaded_comments for conversations in an existing workbook.

parent_id property

parent_id: str | None

The id of the message this one answers; None on the first message.

messages property

messages: list[ThreadedComment]

The first message followed by its replies.

reply

reply(text: str, author: str, created: datetime | None = None, id: str | None = None) -> ThreadedComment

Append a reply to this conversation and return it.

Source code in src/xlspy/threaded_comments.py
123
124
125
126
127
128
129
130
131
132
133
def reply(
    self,
    text: str,
    author: str,
    created: _datetime.datetime | None = None,
    id: str | None = None,
) -> ThreadedComment:
    """Append a reply to this conversation and return it."""
    message = ThreadedComment(text, author, created, False, id)
    self.replies.append(message)
    return message

DiskStringIndex

DiskStringIndex(directory: str | PathLike[str], *, total_count: int = 0)

Disk-backed shared-string lookup with an append-only pending file.

The indexes of the strings looked up last are kept in memory as well (at most _CACHE_LIMIT, so memory stays bounded): an index never changes once given, except by add_existing and a rollback, which drop them.

Source code in src/xlspy/_zip_package.py
60
61
62
63
64
65
66
67
68
69
70
71
72
def __init__(self, directory: str | os.PathLike[str], *, total_count: int = 0):
    directory = Path(directory)
    self._database = sqlite3.connect(directory / "shared-strings.sqlite3")
    self._database.execute("CREATE TABLE IF NOT EXISTS strings (value TEXT PRIMARY KEY, idx INTEGER NOT NULL)")
    self._database.commit()
    self._pending_path = directory / "shared-strings.pending"
    self._pending = self._pending_path.open("ab+")
    self.total_count = total_count
    self.unique_count = 0
    self.dirty = False
    self._uncommitted_inserts = 0
    self._transaction: dict[str, Any] | None = None
    self._cache: dict[str, int] = {}

add_existing

add_existing(value: str, index: int) -> None

Add one original SST value using its stable zero-based index.

Source code in src/xlspy/_zip_package.py
79
80
81
82
83
84
85
86
87
88
89
def add_existing(self, value: str, index: int) -> None:
    """Add one original SST value using its stable zero-based index."""

    # The in-memory reference implementation uses a dict comprehension,
    # so duplicate shared strings resolve to their last index.
    self._cache.pop(value, None)
    self._database.execute(
        "INSERT OR REPLACE INTO strings(value, idx) VALUES (?, ?)",
        (value, index),
    )
    self.unique_count = max(self.unique_count, index + 1)

flush

flush() -> None

Commit pending lookup-index inserts without clearing new values.

Source code in src/xlspy/_zip_package.py
142
143
144
145
146
147
def flush(self) -> None:
    """Commit pending lookup-index inserts without clearing new values."""

    if self._uncommitted_inserts:
        self._database.commit()
        self._uncommitted_inserts = 0

begin_transaction

begin_transaction() -> None

Start a disk-backed transaction for one streamed replacement.

Source code in src/xlspy/_zip_package.py
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
176
177
178
def begin_transaction(self) -> None:
    """Start a disk-backed transaction for one streamed replacement."""

    if self._transaction is not None:
        raise RuntimeError("A shared-string transaction is already active")

    self.flush()
    self._pending.flush()
    descriptor, backup_path = tempfile.mkstemp(
        prefix="shared-strings-", suffix=".backup", dir=self._pending_path.parent
    )
    os.close(descriptor)
    backup = Path(backup_path)
    try:
        with self._pending_path.open("rb") as source, backup.open("wb") as target:
            copy_stream(source, target)
    except BaseException:
        try:
            backup.unlink()
        except FileNotFoundError:
            pass
        raise

    self._transaction = {
        "total_count": self.total_count,
        "unique_count": self.unique_count,
        "dirty": self.dirty,
        "uncommitted_inserts": self._uncommitted_inserts,
        "pending_backup": backup,
    }

commit_transaction

commit_transaction() -> None

Commit the current streamed replacement transaction.

Source code in src/xlspy/_zip_package.py
180
181
182
183
184
185
186
187
188
189
190
191
192
def commit_transaction(self) -> None:
    """Commit the current streamed replacement transaction."""

    transaction = self._transaction
    if transaction is None:
        return
    self._database.commit()
    backup = transaction["pending_backup"]
    try:
        backup.unlink()
    except FileNotFoundError:
        pass
    self._transaction = None

rollback_transaction

rollback_transaction() -> None

Restore the index and pending values to the transaction snapshot.

Source code in src/xlspy/_zip_package.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def rollback_transaction(self) -> None:
    """Restore the index and pending values to the transaction snapshot."""

    transaction = self._transaction
    if transaction is None:
        return

    backup = transaction["pending_backup"]
    self._cache.clear()
    try:
        # New values always receive indexes at or above the old unique
        # count, so no in-memory list of inserted strings is needed.
        self._database.execute(
            "DELETE FROM strings WHERE idx >= ?",
            (transaction["unique_count"],),
        )
        self._database.commit()
        self._uncommitted_inserts = 0

        self._pending.seek(0)
        self._pending.truncate()
        with backup.open("rb") as source:
            copy_stream(source, self._pending)
        self._pending.flush()

        self.total_count = transaction["total_count"]
        self.unique_count = transaction["unique_count"]
        self.dirty = transaction["dirty"]
    finally:
        try:
            backup.unlink()
        except FileNotFoundError:
            pass
        self._transaction = None

set_pending_tables

set_pending_tables(pending: Iterable[Any], removed: Iterable[tuple[int, str]] = ()) -> None

The tables a save is about to write, each with its id (empty when the save is done).

Source code in src/xlspy/_xlsb_edit.py
179
180
181
182
def set_pending_tables(self, pending: Iterable[Any], removed: Iterable[tuple[int, str]] = ()) -> None:
    """The tables a save is about to write, each with its id (empty when the save is done)."""
    self._pending_tables = tuple(pending)
    self._pending_removed_tables = tuple(removed)

get_comments

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

The classic notes of a sheet, keyed by cell reference.

The compatibility notes of Excel 365 conversations are not included; use get_threaded_comments for those.

Source code in src/xlspy/_xlsb_edit.py
212
213
214
215
216
217
218
219
220
221
222
223
224
def get_comments(self, sheet_name: str) -> dict[str, Comment]:
    """The classic notes of a sheet, keyed by cell reference.

    The compatibility notes of Excel 365 conversations are not included;
    use `get_threaded_comments` for those.
    """
    path, _ = self._sheet_bin(sheet_name)
    _, _, parts = find_comment_parts(self._package.get, self._package.names(), path)
    return (
        classic_comments_only(parse_comments(self._package.get(parts["comments"][0]))[0])
        if "comments" in parts
        else {}
    )

get_threaded_comments

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

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

Source code in src/xlspy/_xlsb_edit.py
226
227
228
229
230
231
232
233
234
235
def get_threaded_comments(self, sheet_name: str) -> dict[str, ThreadedComment]:
    """Read the sheet's Excel 365 conversations, keyed by cell reference."""
    path, _ = self._sheet_bin(sheet_name)
    names = self._package.names()
    part = find_threaded_part(self._package.get, names, path)
    if part is None:
        return {}
    people_part = find_person_part(self._package.get, names, "xl/workbook.bin")
    people = read_persons(self._package.get(people_part[0])) if people_part is not None else {}
    return read_threaded_comments(self._package.get(part[0]), people)

set_comments

set_comments(sheet_name: str, comments: Mapping[str, Comment | None]) -> None

Add or replace notes on a sheet, keyed by cell reference; None removes one.

Source code in src/xlspy/_xlsb_edit.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def set_comments(self, sheet_name: str, comments: Mapping[str, Comment | None]) -> None:
    """Add or replace notes on a sheet, keyed by cell reference; None removes one."""
    path, data = self._sheet_bin(sheet_name)
    changes = normalize_comments(comments, allow_none=True)
    check_merged_refs(data, [ref for ref, value in changes.items() if value is not None])
    names = self._package.names()
    legacy = [read_wide(p)[0] for r, p in records(data) if r.record_id == LEGACY_DRAWING]
    if len(legacy) > 1:
        raise ValueError("unsupported legacy drawing relationship")
    rp, relationships, parts = find_comment_parts(self._package.get, names, path, legacy[0] if legacy else None)
    for node in relationships:
        if node.get("Type", "").rsplit("/", 1)[-1] in {"threadedComment", "threadedComments"}:
            root = safe_fromstring(self._package.get(resolve_part(path, node.attrib["Target"])))
            occupied = {cell_ref(n.attrib["ref"]) for n in root if "ref" in n.attrib}
            if any(ref in occupied and value is not None for ref, value in changes.items()):
                raise ValueError("a classic note cannot replace a threaded comment")
    current = parse_comments(self._package.get(parts["comments"][0]))[0] if "comments" in parts else {}
    changes = {ref: value for ref, value in changes.items() if value is not None or ref in current}
    if not changes:
        return
    for other in self._sheets.values():
        if other == path:
            continue
        other_parts = comment_part_targets(self._package.get, names, other)
        if any(p[0] in other_parts for p in parts.values()):
            raise ValueError("comment/VML parts shared by sheets cannot be edited")
    if legacy and "vmlDrawing" not in parts:
        raise ValueError("unsupported legacy drawing relationship")
    edit = NotePartsEdit(path, relationships, parts, names)
    cp = edit.ensure("comments", "xl/comments", "comment", "bin")
    vp = edit.ensure("vmlDrawing", "xl/drawings", "commentsDrawing", "vml")
    note_data = comments_bin(changes, self._package.get(cp) if cp in names else None, part=cp)
    drawing = vml_xml(changes, self._package.get(vp) if vp in names else None)
    remaining = parse_comments(note_data)[0]
    types = safe_fromstring(self._package.get("[Content_Types].xml"))
    updates: dict[str, Any] = {cp: note_data, vp: drawing}
    removed: list[str] = []
    if remaining:
        if not any(node.get("PartName") == "/" + cp for node in types):
            ET.SubElement(types, f"{{{CT}}}Override", {"PartName": "/" + cp, "ContentType": _XLSB_COMMENTS_TYPE})
    else:
        edit.drop(cp, "comments", types, updates, removed)
    if any(node.tag == f"{{{V}}}shape" for node in safe_fromstring(drawing).iter()):
        if not any(node.get("PartName") == "/" + vp or node.get("Extension") == "vml" for node in types):
            ET.SubElement(types, f"{{{CT}}}Override", {"PartName": "/" + vp, "ContentType": VML_TYPE})
        if not legacy:
            data = replace_records(
                data,
                {LEGACY_DRAWING},
                build_record(LEGACY_DRAWING, wide_string(parts["vmlDrawing"][1])),
                before=(0x228, 0x229, 0x27F, 0x294, 0x82),
            )
    else:
        edit.drop(vp, "vmlDrawing", types, updates, removed)
        data = replace_records(data, {LEGACY_DRAWING}, before=(0x82,))
    updates[path] = data
    if len(relationships):
        updates[rp] = ET.tostring(relationships, encoding="utf-8")
    elif rp in names:
        removed.append(rp)
    updates["[Content_Types].xml"] = ET.tostring(types, encoding="utf-8")
    self._apply_parts(updates, removed)

set_threaded_comments

set_threaded_comments(sheet_name: str, comments: Mapping[str, ThreadedComment | None]) -> None

Editing Excel 365 conversations in XLSB is not supported.

Source code in src/xlspy/_xlsb_edit.py
300
301
302
303
304
def set_threaded_comments(self, sheet_name: str, comments: Mapping[str, ThreadedComment | None]) -> None:
    """Editing Excel 365 conversations in XLSB is not supported."""
    raise UnsupportedFeatureError(
        "XLSB workbooks keep threaded comments for reading only; save as XLSX to edit them"
    )

get_defined_names

get_defined_names() -> list[DefinedName]

The workbook's defined names.

Source code in src/xlspy/_xlsb_edit.py
328
329
330
def get_defined_names(self) -> list[DefinedName]:
    """The workbook's defined names."""
    return self._context(self._package.get("xl/workbook.bin"), self._part_or_none).defined_names()

set_defined_name

set_defined_name(definition: DefinedName) -> None

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

Source code in src/xlspy/_xlsb_edit.py
332
333
334
def set_defined_name(self, definition: DefinedName) -> None:
    """Add a defined name, replacing one with the same name and scope."""
    self.set_defined_names([definition])

set_defined_names

set_defined_names(definitions: Iterable[DefinedName]) -> None

Add many defined names in one workbook rewrite (linear, not quadratic).

Source code in src/xlspy/_xlsb_edit.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
def set_defined_names(self, definitions: Iterable[DefinedName]) -> None:
    """Add many defined names in one workbook rewrite (linear, not quadratic)."""
    definitions = list(definitions)
    for definition in definitions:
        if not isinstance(definition, DefinedName):
            raise TypeError("definition must be DefinedName")
    if not definitions:
        return
    sheets = list(self._sheets)
    resolved = [self._resolve_defined_name(definition, sheets) for definition in definitions]
    original = self._package.get("xl/workbook.bin")
    context = self._context(original)
    for definition in resolved:
        context.set_name(definition)
    updates = {"xl/workbook.bin": context.write_workbook(original)}
    removed: list[str] = []
    self._invalidate_calculation(updates, removed)
    self._apply_parts(updates, removed)

remove_defined_name

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

Remove a defined name; with scope, the one local to that sheet.

Source code in src/xlspy/_xlsb_edit.py
355
356
357
def remove_defined_name(self, name: str, scope: str | None = None) -> None:
    """Remove a defined name; with ``scope``, the one local to that sheet."""
    self.remove_defined_names([(name, scope)])

remove_defined_names

remove_defined_names(names: Iterable[tuple[str, str | None]]) -> None

Remove many defined names in one workbook rewrite.

Source code in src/xlspy/_xlsb_edit.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
def remove_defined_names(self, names: Iterable[tuple[str, str | None]]) -> None:
    """Remove many defined names in one workbook rewrite."""
    names = list(names)
    if not names:
        return
    for _name, scope in names:
        if scope is not None and scope not in self._sheets:
            raise KeyError(f"Worksheet not found: {scope}")
    original = self._package.get("xl/workbook.bin")
    context = self._context(original)
    changed = False
    for name, scope in names:
        if context.remove_name(name, scope):
            changed = True
    if not changed:
        return
    updates = {"xl/workbook.bin": context.write_workbook(original)}
    removed: list[str] = []
    self._invalidate_calculation(updates, removed)
    self._apply_parts(updates, removed)

set_sheet_protection

set_sheet_protection(sheet_name: str, protection: SheetProtection) -> None

Set or replace the protection of a sheet.

Source code in src/xlspy/_xlsb_edit.py
380
381
382
383
384
385
386
387
388
389
390
391
def set_sheet_protection(self, sheet_name: str, protection: SheetProtection) -> None:
    """Set or replace the protection of a sheet."""
    if not isinstance(protection, SheetProtection):
        raise TypeError("protection must be SheetProtection")
    path, data = self._sheet_bin(sheet_name)
    data = replace_records(
        data,
        {SHEET_PROTECTION, SHEET_PROTECTION_ISO},
        sheet_protection_bin(protection),
        before=(0xA1, 0xB1, 0x1CD, 0x1EE, 0x1DC, 0x226, 0x227, 0x294, 0x82),
    )
    self._apply_parts({path: data})

set_merged_cells

set_merged_cells(sheet_name: str, ranges: Iterable[str]) -> None

Replace the sheet's merged ranges with ranges (A1 range strings).

Source code in src/xlspy/_xlsb_edit.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
def set_merged_cells(self, sheet_name: str, ranges: Iterable[str]) -> None:
    """Replace the sheet's merged ranges with ``ranges`` (A1 range strings)."""

    path, data = self._sheet_bin(sheet_name)
    refs = normalize_merges(list(ranges))
    block = b""
    if refs:
        pieces = [build_record(0xB1, struct.pack("<I", len(refs)))]
        for ref in refs:
            c1, r1, c2, r2 = parse_cell_range(ref)
            pieces.append(build_record(0xB0, struct.pack("<IIII", r1, r2, c1, c2)))
        pieces.append(build_record(0xB2))
        block = b"".join(pieces)
    if not block and not any(r.record_id in _MERGE_RECORDS for r, _ in records(data)):
        return
    self._apply_parts({path: replace_records(data, _MERGE_RECORDS, block, before=_AFTER_MERGES)})
set_hyperlinks(sheet_name: str, links: Mapping[str, Hyperlink | None]) -> None

Set selected cells' hyperlinks; None removes one, other links are kept.

Only the link changes: the cell's value and style stay as they are. A link whose range starts at a given cell is replaced as a whole. External targets reuse the sheet's hyperlink relationships, new ones get fresh ids, and a removed link's relationship goes unless another link uses it.

Source code in src/xlspy/_xlsb_edit.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
def set_hyperlinks(self, sheet_name: str, links: Mapping[str, Hyperlink | None]) -> None:
    """Set selected cells' hyperlinks; None removes one, other links are kept.

    Only the link changes: the cell's value and style stay as they are. A
    link whose range starts at a given cell is replaced as a whole. External
    targets reuse the sheet's hyperlink relationships, new ones get fresh
    ids, and a removed link's relationship goes unless another link uses it.
    """

    path, data = self._sheet_bin(sheet_name)
    changes = {}
    for ref, link in links.items():
        if link is not None and not isinstance(link, Hyperlink):
            raise TypeError("hyperlinks must be xlspy Hyperlink objects or None")
        changes[cell_ref(ref)] = link
    if not changes:
        return
    # (row, column, payload) of the links that stay, as they are in the file.
    kept: list[tuple[int, int, bytes]] = []
    dropped = set()
    used = set()
    had_links = False
    for record, payload in records(data):
        if record.record_id != 0x1EE:
            continue
        had_links = True
        if len(payload) < 16:
            raise InvalidFileError("XLSB hyperlink record is cut short")
        first_row, _, first_col, _ = struct.unpack_from("<4I", payload)
        relationship = read_wide(payload, 16)[0]
        if f"{column_label(first_col)}{first_row + 1}" in changes:
            dropped.add(relationship)
        else:
            used.add(relationship)
            kept.append((first_row, first_col, payload))
    entries = []
    for ref, link in changes.items():
        if link is not None:
            col, row, _, _ = parse_cell_range(ref)
            entries.append((row, col, link))
    if not entries and not dropped:
        return  # nothing to remove

    rels_name = rels_path(path)
    has_rels = self._package.has(rels_name)
    root = safe_fromstring(self._package.get(rels_name)) if has_rels else ET.Element(f"{{{PKG_REL}}}Relationships")
    by_target = {
        rel.get("Target"): rel.get("Id")
        for rel in root
        if rel.get("Type") == HYPERLINK_TYPE and rel.get("TargetMode") == "External"
    }
    taken = {rel.get("Id") for rel in root}
    rels_changed = False
    block = list(kept)
    number = 1  # Ids only get taken here, so the first free one never moves back.
    for row, col, link in entries:
        rid = None
        if not link.is_internal:
            rid = by_target.get(link.target)
            if rid is None:
                while f"rId{number}" in taken:
                    number += 1
                rid = f"rId{number}"
                taken.add(rid)
                ET.SubElement(
                    root,
                    f"{{{PKG_REL}}}Relationship",
                    {
                        "Id": rid,
                        "Type": HYPERLINK_TYPE,
                        "Target": link.target,
                        "TargetMode": "External",
                    },
                )
                by_target[link.target] = rid
                rels_changed = True
            used.add(rid)
        block.append((row, col, _hlink_payload(row, col, link, rid)))
    for rel in list(root):
        if rel.get("Type") == HYPERLINK_TYPE and rel.get("Id") in dropped and rel.get("Id") not in used:
            root.remove(rel)
            rels_changed = True
    block.sort(key=lambda item: item[:2])
    records_block = b"".join(build_record(0x1EE, payload) for _, _, payload in block)
    parts = {path: replace_records(data, {0x1EE} if had_links else (), records_block, before=_BRT_AFTER_HYPERLINKS)}
    removed: list[str] = []
    if rels_changed and not len(root):
        if has_rels:
            removed.append(rels_name)
    elif rels_changed:
        ET.register_namespace("", PKG_REL)
        parts[rels_name] = b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' + ET.tostring(
            root, encoding="utf-8", xml_declaration=False
        )
    self._apply_parts(parts, removed)

set_data_validations

set_data_validations(sheet_name: str, rules: Sequence[DataValidation]) -> None

Replace the sheet's data validation rules with rules.

Source code in src/xlspy/_xlsb_edit.py
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
def set_data_validations(self, sheet_name: str, rules: Sequence[DataValidation]) -> None:
    """Replace the sheet's data validation rules with ``rules``."""

    rules = list(rules)
    for rule in rules:
        if not isinstance(rule, DataValidation):
            raise TypeError("data validations must be xlspy DataValidation objects")
    path, data = self._sheet_bin(sheet_name)
    targets = {BRT_BEGIN_DVALS, BRT_DVAL, BRT_END_DVALS}
    if not rules and not any(r.record_id in targets for r, _ in records(data)):
        return
    original_workbook = self._package.get("xl/workbook.bin")
    context = self._context(original_workbook)
    block = validations_bin(rules, context)
    self._apply_parts(
        {
            path: replace_records(data, targets, block, before=(0x1EE,) + _BRT_AFTER_HYPERLINKS),
            "xl/workbook.bin": context.write_workbook(original_workbook),
        }
    )

set_conditional_formats

set_conditional_formats(sheet_name: str, formats: Iterable[tuple[str, bool | None, list[Any]]], dxf_id: Callable[[Any], int], links: Mapping[int, bytes] | None = None) -> None

Replace the sheet's conditional formats with formats, an iterable of (sqref, pivot, rules); dxf_id(dxf) returns the index of a rule's differential style in the style sheet. links maps id(rule) to the BrtCFRuleExt payload of a rule whose Excel 2010 extension is kept as it is in the file.

Source code in src/xlspy/_xlsb_edit.py
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
def set_conditional_formats(
    self,
    sheet_name: str,
    formats: Iterable[tuple[str, bool | None, list[Any]]],
    dxf_id: Callable[[Any], int],
    links: Mapping[int, bytes] | None = None,
) -> None:
    """Replace the sheet's conditional formats with ``formats``, an
    iterable of ``(sqref, pivot, rules)``; ``dxf_id(dxf)`` returns the
    index of a rule's differential style in the style sheet. ``links`` maps
    ``id(rule)`` to the ``BrtCFRuleExt`` payload of a rule whose Excel 2010
    extension is kept as it is in the file."""

    path, data = self._sheet_bin(sheet_name)
    original_workbook = self._package.get("xl/workbook.bin")
    context = self._context(original_workbook)
    block = conditional_formats_bin(formats, context, dxf_id, links)
    data, groups = without_conditional_formats(data, frozenset((links or {}).values()))
    if block:
        data = replace_records(data, (), block, before=(0x23D, 0x1EE) + _BRT_AFTER_HYPERLINKS)
    if groups:
        data = insert_extension(data, groups)
    self._apply_parts({path: data, "xl/workbook.bin": context.write_workbook(original_workbook)})

set_workbook_protection

set_workbook_protection(protection: WorkbookProtection) -> None

Set or replace the workbook protection.

Source code in src/xlspy/_xlsb_edit.py
551
552
553
554
555
556
557
558
559
def set_workbook_protection(self, protection: WorkbookProtection) -> None:
    """Set or replace the workbook protection."""
    if not isinstance(protection, WorkbookProtection):
        raise TypeError("protection must be WorkbookProtection")
    data = self._package.get("xl/workbook.bin")
    data = replace_records(
        data, {BOOK_PROTECTION, BOOK_PROTECTION_ISO}, workbook_protection_bin(protection), before=(0x87, 0x8F)
    )
    self._apply_parts({"xl/workbook.bin": data})

update_cells

update_cells(sheet_name: str, cells: Mapping[str, object], *, styles: Mapping[str, int] | None = None) -> None

Set cell values; styles maps addresses to cell XF indexes.

An address only in styles keeps its value (or becomes a styled blank).

Source code in src/xlspy/_xlsb_edit.py
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
def update_cells(
    self, sheet_name: str, cells: Mapping[str, object], *, styles: Mapping[str, int] | None = None
) -> None:
    """Set cell values; ``styles`` maps addresses to cell XF indexes.

    An address only in ``styles`` keeps its value (or becomes a styled blank).
    """
    path, data = self._sheet_bin(sheet_name)
    values, style_ids, targets = self._normalize_cell_edits(
        cells,
        styles,
        cells_error="cells must map single-cell addresses to values",
        styles_error="styles must map single-cell addresses to XF indexes",
        duplicate_error="duplicate cell address {ref}",
        keep=KEEP,
    )
    if not targets:
        return
    begin_start, begin_end, end_start, row_starts, merges, groups, dimension, cell_bounds = _scan_sheet(data)
    check_merged_refs(data, [ref for ref, value in values.items() if value is not None], merges)
    for r1, r2, c1, c2 in groups:
        if any(c1 <= parse_cell_range(ref)[0] <= c2 and r1 <= parse_cell_range(ref)[1] <= r2 for ref in values):
            raise ValueError("editing members of array/shared/data-table formulas is unsupported")
    has_formulas = any(isinstance(value, (Formula, ArrayFormula, DataTableFormula)) for value in values.values())
    original_workbook = self._package.get("xl/workbook.bin") if has_formulas else None
    context = self._context(original_workbook) if has_formulas else None
    # Encode everything before staging any changes, including all formulas.
    for ref, value in values.items():
        col, row, _, _ = parse_cell_range(ref)
        encode_cell(value, col, 0, context, sheet_name, row, self._date_1904)
    patched, removed_shared_refs = self._rebuild_bin_rows(
        data,
        begin_end,
        end_start,
        row_starts,
        targets,
        style_ids,
        context,
        sheet_name,
    )
    patched = self._patch_bin_dimension(patched, dimension, begin_start, targets, cell_bounds)
    updates, removed = self._bin_update_parts(path, patched, context, original_workbook, removed_shared_refs)
    self._drop_bin_binary_index(updates, removed, path)
    self._apply_parts(updates, removed)
    self._account_removed_shared_strings(removed_shared_refs)
    if self._shared_strings_loaded and "xl/sharedStrings.bin" in updates:
        self._shared_strings_data = updates["xl/sharedStrings.bin"]

get_sheet_states

get_sheet_states() -> dict[str, str]

Sheet visibility (visible, hidden or veryHidden) by name.

Source code in src/xlspy/_xlsb_sheets.py
113
114
115
116
117
118
def get_sheet_states(self) -> dict[str, str]:
    """Sheet visibility (``visible``, ``hidden`` or ``veryHidden``) by name."""
    return {
        entry.name: STATE_NAMES.get(entry.state, "visible")
        for entry in _bundles(self._package.get("xl/workbook.bin"))
    }

get_active_sheet

get_active_sheet() -> int

Index of the sheet Excel shows when the workbook opens.

Source code in src/xlspy/_xlsb_sheets.py
120
121
122
123
124
125
126
def get_active_sheet(self) -> int:
    """Index of the sheet Excel shows when the workbook opens."""
    for record, payload in records(self._package.get("xl/workbook.bin")):
        if record.record_id == BOOK_VIEW and len(payload) >= 28:
            active: int = struct.unpack_from("<I", payload, 24)[0]
            return active
    return 0

add_sheet

add_sheet(name: str, index: int | None = None, *, state: str = 'visible') -> str

Add an empty worksheet at index (default: last); return its part path.

Source code in src/xlspy/_xlsb_sheets.py
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
157
158
159
160
161
162
163
def add_sheet(self, name: str, index: int | None = None, *, state: str = "visible") -> str:
    """Add an empty worksheet at ``index`` (default: last); return its part path."""
    check_sheet_name(name, self._sheets)
    check_sheet_state(state)
    workbook = self._package.get("xl/workbook.bin")
    entries = _bundles(workbook)
    path = next_sheet_part(self._package.names(), "bin")

    rels_path = "xl/_rels/workbook.bin.rels"
    rels = safe_fromstring(self._package.get(rels_path))
    rid = _next_id({node.get("Id") for node in rels}, "rId")
    ET.SubElement(
        rels,
        f"{{{PKG_REL}}}Relationship",
        {
            "Id": rid,
            "Type": REL + "/worksheet",
            "Target": posixpath.relpath(path, "xl"),
        },
    )
    types = safe_fromstring(self._package.get("[Content_Types].xml"))
    ET.SubElement(types, f"{{{CT}}}Override", {"PartName": "/" + path, "ContentType": WORKSHEET_TYPE})

    tab_id = max((entry.tab_id for entry in entries), default=0) + 1
    new = _Entry(None, STATE_CODES[state], tab_id, rid, name)
    index = len(entries) if index is None else max(0, min(index, len(entries)))
    entries.insert(index, new)
    parts = {
        path: _EMPTY_SHEET,
        rels_path: _xml(rels),
        "[Content_Types].xml": _xml(types),
    }
    parts["xl/workbook.bin"] = self._rewrite_sheet_list(workbook, entries, parts)
    self._apply_parts(parts)
    self._sheets = {entry.name: (path if entry is new else self._sheets[entry.name]) for entry in entries}
    return path

remove_sheet

remove_sheet(name: str) -> None

Remove a sheet, its part and its relationships.

References to it become #REF! and names local to it are dropped.

Source code in src/xlspy/_xlsb_sheets.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def remove_sheet(self, name: str) -> None:
    """Remove a sheet, its part and its relationships.

    References to it become ``#REF!`` and names local to it are dropped.
    """
    path = self._sheets.get(name)
    if path is None:
        raise KeyError(f"Worksheet not found: {name}")
    if len(self._sheets) == 1:
        raise ValueError("a workbook must keep at least one sheet")

    # As for XLSX: the slicer caches would be left pointing at a removed table.
    if sheet_has_slicers(self._package, path):
        raise UnsupportedFeatureError(f"sheet {name!r} holds table slicers; removing it is not supported yet")
    # And a pivot table, its cache and the workbook's cache list would be left dangling.
    if sheet_has_pivots(self._package, path):
        raise UnsupportedFeatureError(f"sheet {name!r} holds pivot tables; removing it is not supported yet")
    workbook = self._package.get("xl/workbook.bin")
    entries = _bundles(workbook)
    removed = next(entry for entry in entries if entry.name == name)
    entries.remove(removed)

    rels_path = "xl/_rels/workbook.bin.rels"
    rels = safe_fromstring(self._package.get(rels_path))
    for node in list(rels):
        if node.get("Id") == removed.rid:
            rels.remove(node)
    types = safe_fromstring(self._package.get("[Content_Types].xml"))
    for node in list(types):
        if node.get("PartName") == "/" + path:
            types.remove(node)
    parts = {rels_path: _xml(rels), "[Content_Types].xml": _xml(types)}
    parts["xl/workbook.bin"] = self._rewrite_sheet_list(workbook, entries, parts)
    dropped = [path]
    sheet_rels = posixpath.join(posixpath.dirname(path), "_rels", posixpath.basename(path) + ".rels")
    if self._package.has(sheet_rels):
        dropped.append(sheet_rels)
    removed_parts: list[str] = []
    self._invalidate_calculation(parts, removed_parts)
    self._apply_parts(parts, dropped + removed_parts)
    del self._sheets[name]
    self._chartsheets.discard(name)

rename_sheet

rename_sheet(old: str, new: str) -> None

Rename sheet old to new; raises KeyError when old is absent.

Source code in src/xlspy/_xlsb_sheets.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def rename_sheet(self, old: str, new: str) -> None:
    """Rename sheet ``old`` to ``new``; raises KeyError when ``old`` is absent."""
    if old not in self._sheets:
        raise KeyError(f"Worksheet not found: {old}")
    if old == new:
        return
    check_sheet_name(new, [name for name in self._sheets if name != old])
    workbook = self._package.get("xl/workbook.bin")
    entries = _bundles(workbook)
    for entry in entries:
        if entry.name == old:
            entry.name = new
    parts = renamed_chart_parts(self._package, old, new)
    for name in self._package.names():
        if re.fullmatch(r"xl/worksheets/sheet[^/]*\.bin", name):
            data = self._package.get(name)
            updated = _rename_hyperlink_locations(data, old, new)
            if updated != data:
                parts[name] = updated
    parts["xl/workbook.bin"] = self._rewrite_sheet_list(workbook, entries, parts)
    self._apply_parts(parts)
    self._sheets = {(new if name == old else name): path for name, path in self._sheets.items()}
    if old in self._chartsheets:
        self._chartsheets.discard(old)
        self._chartsheets.add(new)

reorder_sheets

reorder_sheets(order: Iterable[str]) -> None

Put the sheets in order (every sheet name, once).

Source code in src/xlspy/_xlsb_sheets.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def reorder_sheets(self, order: Iterable[str]) -> None:
    """Put the sheets in ``order`` (every sheet name, once)."""
    order = list(order)
    if sorted(order) != sorted(self._sheets):
        raise ValueError("order must list every sheet exactly once")
    workbook = self._package.get("xl/workbook.bin")
    by_name = {entry.name: entry for entry in _bundles(workbook)}
    entries = [by_name[name] for name in order]
    # Entries read from workbook.bin always carry their old index.
    old_indexes = [entry.old_index for entry in entries]
    if old_indexes == sorted(index for index in old_indexes if index is not None):
        return
    parts: dict[str, Any] = {}
    parts["xl/workbook.bin"] = self._rewrite_sheet_list(workbook, entries, parts)
    removed: list[str] = []
    self._invalidate_calculation(parts, removed)
    self._apply_parts(parts, removed)
    self._sheets = {name: self._sheets[name] for name in order}

set_sheet_state

set_sheet_state(name: str, state: str) -> None

Set a sheet to "visible", "hidden" or "veryHidden".

Source code in src/xlspy/_xlsb_sheets.py
253
254
255
256
257
258
259
260
261
262
263
264
def set_sheet_state(self, name: str, state: str) -> None:
    """Set a sheet to ``"visible"``, ``"hidden"`` or ``"veryHidden"``."""
    check_sheet_state(state)
    workbook = self._package.get("xl/workbook.bin")
    entries = _bundles(workbook)
    entry = next((entry for entry in entries if entry.name == name), None)
    if entry is None:
        raise KeyError(f"Worksheet not found: {name}")
    if entry.state == STATE_CODES[state]:
        return
    entry.state = STATE_CODES[state]
    self._apply_parts({"xl/workbook.bin": self._rewrite_sheet_list(workbook, entries, {})})

set_active_sheet

set_active_sheet(index: int) -> None

Make the sheet at 0-based index the active one.

Source code in src/xlspy/_xlsb_sheets.py
266
267
268
269
270
271
272
273
274
def set_active_sheet(self, index: int) -> None:
    """Make the sheet at 0-based ``index`` the active one."""
    workbook = self._package.get("xl/workbook.bin")
    entries = _bundles(workbook)
    if not 0 <= index < len(entries):
        raise IndexError("active sheet index out of range")
    updated = _patch_book_views(workbook, lambda first, current: (min(first, index), index))
    if updated != workbook:
        self._apply_parts({"xl/workbook.bin": updated})

close

close() -> None

Release temporary files held by the updater.

While in use, the updater keeps shared-string data and staged package parts on disk. Calling close (or simply dropping the updater) removes them.

Source code in src/xlspy/_updater_base.py
82
83
84
85
86
87
88
89
90
91
92
def close(self) -> None:
    """Release temporary files held by the updater.

    While in use, the updater keeps shared-string data and staged package
    parts on disk.  Calling ``close`` (or simply dropping the updater)
    removes them.
    """

    if self._stream_shared_strings is not None:
        self._stream_shared_strings.close()
    self._package.close()

get_sheet_names

get_sheet_names() -> list[str]

Return worksheet and chartsheet names in workbook order.

Source code in src/xlspy/_updater_base.py
112
113
114
115
def get_sheet_names(self) -> list[str]:
    """Return worksheet and chartsheet names in workbook order."""

    return list(self._sheets)

get_worksheet_names

get_worksheet_names() -> list[str]

The names of the worksheets alone, in workbook order.

Source code in src/xlspy/_updater_base.py
117
118
119
120
def get_worksheet_names(self) -> list[str]:
    """The names of the worksheets alone, in workbook order."""

    return [name for name in self._sheets if name not in self._chartsheets]

get_chartsheet_names

get_chartsheet_names() -> list[str]

The chartsheet names, in workbook order.

Source code in src/xlspy/_updater_base.py
122
123
124
125
def get_chartsheet_names(self) -> list[str]:
    """The chartsheet names, in workbook order."""

    return [name for name in self._sheets if name in self._chartsheets]

replace_sheet_data

replace_sheet_data(sheet_name: str, rows: Iterable[Sequence[Any]], *, headers: Sequence[str] | None = None, style_fallback: StyleFallback = 'inherit') -> None

Replace one worksheet's used data region.

rows is materialised once, so generators are supported but the operation remains atomic with respect to the in-memory package. A (value, format_string) cell is accepted for compatibility with the writers; its value is used and no new style is created. Once a streaming shared-string store is loaded, the call is forwarded to replace_sheet_data_stream.

Source code in src/xlspy/_updater_base.py
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
157
158
159
160
161
def replace_sheet_data(
    self,
    sheet_name: str,
    rows: Iterable[Sequence[Any]],
    *,
    headers: Sequence[str] | None = None,
    style_fallback: StyleFallback = "inherit",
) -> None:
    """Replace one worksheet's used data region.

    ``rows`` is materialised once, so generators are supported but the
    operation remains atomic with respect to the in-memory package. A
    ``(value, format_string)`` cell is accepted for compatibility with the
    writers; its value is used and no new style is created. Once a
    streaming shared-string store is loaded, the call is forwarded to
    ``replace_sheet_data_stream``.
    """

    sheet_path = self._replacement_sheet_path(sheet_name, style_fallback)
    if self._stream_shared_strings is not None:
        self.replace_sheet_data_stream(
            sheet_name,
            rows,
            headers=headers,
            style_fallback=style_fallback,
        )
        return
    materialized, header_values = self._checked_rows(sheet_name, sheet_path, rows, headers)
    self._replace_loaded_rows(
        sheet_name,
        sheet_path,
        materialized,
        header_values,
        style_fallback,
    )

replace_sheet_data_stream

replace_sheet_data_stream(sheet_name: str, rows: Iterable[Sequence[Any]], *, headers: Sequence[str] | None = None, style_fallback: StyleFallback = 'inherit') -> None

Replace worksheet data atomically while streaming rows.

The package and disk-backed shared-string index are committed only after the one-pass row source and all metadata updates succeed. A failure therefore leaves this updater reusable for a later attempt.

Source code in src/xlspy/_updater_base.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def replace_sheet_data_stream(
    self,
    sheet_name: str,
    rows: Iterable[Sequence[Any]],
    *,
    headers: Sequence[str] | None = None,
    style_fallback: StyleFallback = "inherit",
) -> None:
    """Replace worksheet data atomically while streaming rows.

    The package and disk-backed shared-string index are committed only
    after the one-pass row source and all metadata updates succeed.  A
    failure therefore leaves this updater reusable for a later attempt.
    """

    self._replacement_sheet_path(sheet_name, style_fallback)
    self._ensure_stream_shared_strings()
    store = self._stream_shared_strings
    self._package.begin_transaction()
    try:
        if store is not None:
            store.begin_transaction()
        self._replace_sheet_data_stream_impl(
            sheet_name,
            rows,
            headers=headers,
            style_fallback=style_fallback,
        )
        self._package.commit_transaction()
        if store is not None:
            store.commit_transaction()
    except BaseException:
        if store is not None:
            store.rollback_transaction()
        self._package.rollback_transaction()
        raise

save

save(output_path: str | PathLike[str] | None = None) -> None

Save to a new path or atomically replace the input file.

Source code in src/xlspy/_updater_base.py
317
318
319
320
def save(self, output_path: str | os.PathLike[str] | None = None) -> None:
    """Save to a new path or atomically replace the input file."""

    self._package.save(output_path)

to_bytes

to_bytes() -> bytes

Return the current package as bytes in the updater's format.

Source code in src/xlspy/_updater_base.py
322
323
324
325
def to_bytes(self) -> bytes:
    """Return the current package as bytes in the updater's format."""

    return self._package.to_bytes()