# Updating

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

[API reference](<https://justybase.github.io/xlspy/api/index.md>) · [Guide](<https://justybase.github.io/xlspy/usage/index.md>)

## 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.

### get\_sheet\_states

```
get_sheet_states() -> dict[str, str]
```

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

### get\_active\_sheet

```
get_active_sheet() -> int
```

Index of the sheet Excel shows when the workbook opens.

### set\_active\_sheet

```
set_active_sheet(index: int) -> None
```

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

### set\_sheet\_state

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

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

### 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.

### 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.

### rename\_sheet

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

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

### reorder\_sheets

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

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

### get\_comments

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

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

### get\_threaded\_comments

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

Read Excel 365 conversations from the current staged package.

### 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.

### 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.

### set\_hyperlinks

```
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.

### get\_defined\_names

```
get_defined_names() -> list[DefinedName]
```

Return user-defined global and worksheet-local names.

### set\_defined\_name

```
set_defined_name(definition: DefinedName) -> None
```

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

### set\_defined\_names

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

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

### 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.

### remove\_defined\_names

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

Remove many defined names in one workbook rewrite.

### set\_sheet\_protection

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

Set or replace the protection of a sheet.

### set\_merged\_cells

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

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

### set\_data\_validations

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

Replace the sheet's data validation rules with `rules`.

### set\_workbook\_protection

```
set_workbook_protection(protection: WorkbookProtection) -> None
```

Set or replace the workbook protection.

### 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).

### 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.

### get\_sheet\_names

```
get_sheet_names() -> list[str]
```

Return worksheet and chartsheet names in workbook order.

### get\_worksheet\_names

```
get_worksheet_names() -> list[str]
```

The names of the worksheets alone, in workbook order.

### get\_chartsheet\_names

```
get_chartsheet_names() -> list[str]
```

The chartsheet names, in workbook order.

### 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`.

### 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.

### save

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

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

### to\_bytes

```
to_bytes() -> bytes
```

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

## XlsmUpdater

```
XlsmUpdater = XlsxUpdater
```

## XlsbUpdater

```
XlsbUpdater(path: str | PathLike[str])
```

Bases: `_UpdaterBase`, `XlsbSheetsMixin`, `XlsbEditMixin`

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

### DataValidation

```
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

```
ooxml_type: str
```

The OOXML name of `type`.

#### allowBlank

```
allowBlank: bool
```

openpyxl's name for `allow_blank`.

#### showDropDown

```
showDropDown: bool
```

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

It is the inverse of `show_dropdown`.

#### showErrorMessage

```
showErrorMessage: bool
```

openpyxl's name for `show_error_message`.

#### showInputMessage

```
showInputMessage: bool
```

openpyxl's name for `show_input_message`.

#### errorStyle

```
errorStyle: str
```

openpyxl's name for `error_style`.

#### errorTitle

```
errorTitle: str | None
```

openpyxl's name for `error_title`.

#### promptTitle

```
promptTitle: str | None
```

openpyxl's name for `prompt_title`.

#### imeMode

```
imeMode: str | None
```

openpyxl's name for `ime_mode`.

### Hyperlink

```
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

```
is_internal: bool
```

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

#### location

```
location: str
```

The `Sheet!A1` form of an internal link.

#### display\_text

```
display_text: str
```

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

### ThreadedComment

```
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

```
parent_id: str | None
```

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

#### messages

```
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.

### 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.

#### add\_existing

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

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

#### flush

```
flush() -> None
```

Commit pending lookup-index inserts without clearing new values.

#### begin\_transaction

```
begin_transaction() -> None
```

Start a disk-backed transaction for one streamed replacement.

#### commit\_transaction

```
commit_transaction() -> None
```

Commit the current streamed replacement transaction.

#### rollback\_transaction

```
rollback_transaction() -> None
```

Restore the index and pending values to the transaction snapshot.

### 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).

### 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.

### get\_threaded\_comments

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

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

### 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.

### set\_threaded\_comments

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

Editing Excel 365 conversations in XLSB is not supported.

### get\_defined\_names

```
get_defined_names() -> list[DefinedName]
```

The workbook's defined names.

### set\_defined\_name

```
set_defined_name(definition: DefinedName) -> None
```

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

### set\_defined\_names

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

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

### 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.

### remove\_defined\_names

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

Remove many defined names in one workbook rewrite.

### set\_sheet\_protection

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

Set or replace the protection of a sheet.

### set\_merged\_cells

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

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

### set\_hyperlinks

```
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.

### set\_data\_validations

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

Replace the sheet's data validation rules with `rules`.

### 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.

### set\_workbook\_protection

```
set_workbook_protection(protection: WorkbookProtection) -> None
```

Set or replace the workbook protection.

### 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).

### get\_sheet\_states

```
get_sheet_states() -> dict[str, str]
```

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

### get\_active\_sheet

```
get_active_sheet() -> int
```

Index of the sheet Excel shows when the workbook opens.

### 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.

### 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.

### rename\_sheet

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

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

### reorder\_sheets

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

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

### set\_sheet\_state

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

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

### set\_active\_sheet

```
set_active_sheet(index: int) -> None
```

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

### 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.

### get\_sheet\_names

```
get_sheet_names() -> list[str]
```

Return worksheet and chartsheet names in workbook order.

### get\_worksheet\_names

```
get_worksheet_names() -> list[str]
```

The names of the worksheets alone, in workbook order.

### get\_chartsheet\_names

```
get_chartsheet_names() -> list[str]
```

The chartsheet names, in workbook order.

### 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`.

### 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.

### save

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

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

### to\_bytes

```
to_bytes() -> bytes
```

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