Skip to content

Named Range

NamedRange class for “table:named-range” tag.

Classes:

Name Description
NamedRange

Named range of cells in a table, “table:named-range”.

Functions:

Name Description
table_name_check

Validate a table name for use in ODF documents.

_RE_TABLE_NAME module-attribute

_RE_TABLE_NAME = compile("^\\'|[\\n\\\\/\\*\\?:\\][]|\\'$")

NamedRange

Bases: Element

Named range of cells in a table, “table:named-range”.

Identifies inside the spreadsheet a range of cells of a table by a name and the name of the table.

Name Ranges have the following attributes:

name -- name of the named range

table_name -- name of the table

start -- first cell of the named range, tuple (x, y)

end -- last cell of the named range, tuple (x, y)

crange -- range of the named range, tuple (x, y, z, t)

usage -- None or str, usage of the named range.

Methods:

Name Description
__init__

Initialize a NamedRange element.

get_value

Retrieve the value of the first cell of the named range.

get_values

Retrieve the values of all cells within the named range.

set_range

Set the cell range for the named range.

set_table_name

Set the name of the table associated with the named range.

set_usage

Set the usage type for the named range.

set_value

Set the value of the first cell within the named range.

set_values

Set the values of a range of cells within the named range.

Attributes:

Name Type Description
crange tuple[int, int, int, int]
end tuple[int, int]
name str | None

Get the name of the named range.

start tuple[int, int]
table_name str
usage str | None
Source code in odfdo/named_range.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
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
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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
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
class NamedRange(Element):
    """Named range of cells in a table, "table:named-range".

    Identifies inside the spreadsheet
    a range of cells of a table by a name and the name of the table.

    Name Ranges have the following attributes:

        name -- name of the named range

        table_name -- name of the table

        start -- first cell of the named range, tuple (x, y)

        end -- last cell of the named range, tuple (x, y)

        crange -- range of the named range, tuple (x, y, z, t)

        usage -- None or str, usage of the named range.
    """

    _tag = "table:named-range"

    def __init__(
        self,
        name: str | None = None,
        crange: str | tuple | list | None = None,
        table_name: str | None = None,
        usage: str | None = None,
        **kwargs: Any,
    ) -> None:
        """Initialize a NamedRange element.

        A NamedRange element identifies a range of cells in a table by a name
        and the table's name. The `name` must be alphanumeric with underscores,
        and not formatted like a cell coordinate (e.g., "A1").
        The `table_name` must be a valid table name (without single quotes or slashes).

        Args:
            name: The name of the named range.
            crange: The cell or area coordinate,
                e.g., "A1", "A1:B2", (0, 0), or (0, 0, 1, 1).
            table_name: The name of the table the range belongs to.
            usage: The usage of the named range, one of
                "print-range", "filter", "repeat-column", "repeat-row", or None.
            **kwargs: Additional keyword arguments for the parent `Element` class.
        """
        super().__init__(**kwargs)
        self.usage: str | None = None
        self.table_name: str = ""
        self.start: tuple[int, int] = 0, 0
        self.end: tuple[int, int] = 0, 0
        self.crange: tuple[int, int, int, int] = 0, 0, 0, 0
        self.usage = None
        if self._do_init:
            self.name = name or ""
            self.table_name = table_name_check(table_name)
            self.set_range(crange or "")
            self.set_usage(usage)
        cell_range_address = self.get_attribute_string("table:cell-range-address") or ""
        if not cell_range_address:
            return
        self.usage = self.get_attribute_string("table:range-usable-as")
        name_range = cell_range_address.replace("$", "")
        name, crange = name_range.split(".", 1)
        if name.startswith("'") and name.endswith("'"):
            name = name[1:-1]
        self.table_name = name
        crange = crange.replace(".", "")
        self._set_range(crange)

    def set_usage(self, usage: str | None = None) -> None:
        """Set the usage type for the named range.

        The usage specifies how the named range is intended to be used (e.g.,
        for printing, filtering, or repeating columns/rows).

        Args:
            usage: The usage type. Can be "print-range", "filter",
                "repeat-column", "repeat-row", or None to clear the usage.
        """
        if usage is not None:
            usage = usage.strip().lower()
            if usage not in ("print-range", "filter", "repeat-column", "repeat-row"):
                usage = None
        if usage is None:
            with contextlib.suppress(KeyError):
                self.del_attribute("table:range-usable-as")
            self.usage = None
        else:
            self.set_attribute("table:range-usable-as", usage)
            self.usage = usage

    @staticmethod
    def _check_nr_name(name: str) -> str:
        """Validate a named range name.

        Ensures the name is not empty, contains only alphanumeric characters and
        underscores, and does not resemble a cell coordinate (e.g., "A1").

        Args:
            name: The name to validate.

        Returns:
            str: The validated name.

        Raises:
            ValueError: If the name is empty, contains forbidden characters,
                or is formatted like a cell coordinate.
        """
        name = name.strip()
        if not name:
            raise ValueError("Named Range name can't be empty.")
        for x in name:
            if x in _forbidden_in_named_range():
                msg = f"Character forbidden in Named Range name: {x!r} "
                raise ValueError(msg)
        step = ""
        for x in name:
            if x in string.ascii_letters and step in ("", "A"):
                step = "A"
                continue
            elif step in ("A", "A1") and x in string.digits:
                step = "A1"
                continue
            else:
                step = ""
                break
        if step == "A1":
            msg = f"Name of the type 'ABC123' is not allowed for Named Range: {name!r}"
            raise ValueError(msg)
        return name

    @property
    def name(self) -> str | None:
        """Get the name of the named range.

        The name is mandatory, must be alphanumeric with underscores, and cannot
        be formatted like a cell coordinate (e.g., "A1").

        Returns:
            str | None: The name of the named range.
        """
        return self.get_attribute_string("table:name")

    @name.setter
    def name(self, name: str) -> None:
        """Set the name of the named range.

        If a named range with the same name already exists in the document, it
        will be replaced.

        Args:
            name: The new name for the named range.
        """
        name = self._check_nr_name(name)
        with contextlib.suppress(Exception):
            # we are not on an NR inserted in a document.
            # We know the body should contains NR mixin if
            # not exception.
            if body := self.document_body:
                named_range = body.get_named_range(name)  # type: ignore[attr-defined]
                if named_range:
                    named_range.delete()
        self.set_attribute("table:name", name)

    def set_table_name(self, name: str) -> None:
        """Set the name of the table associated with the named range.

        Args:
            name: The name of the table.

        Raises:
            TypeError: If `name` is not a string (propagated from `table_name_check`).
            ValueError: If `name` is empty or contains forbidden characters (propagated from `table_name_check`).
        """
        self.table_name = table_name_check(name)
        self._update_attributes()

    def _set_range(self, coord: tuple | list | str) -> None:
        """Internal helper to set the cell range coordinates.

        Args:
            coord: The cell or area coordinate,
                e.g., "A1", "A1:B2", (0, 0), or (0, 0, 1, 1).

        Raises:
            ValueError: If the coordinate format is incorrect.
        """
        digits = convert_coordinates(coord)
        if len(digits) == 4:
            x, y, z, t = digits
        else:
            x, y = digits
            z, t = digits
        if x is None or y is None or z is None or t is None:
            raise ValueError(f"Wrong format for cell range: {coord!r}")
        self.start = x, y
        self.end = z, t
        self.crange = x, y, z, t

    def set_range(
        self,
        crange: str | tuple[int, int] | tuple[int, int, int, int] | list[int],
    ) -> None:
        """Set the cell range for the named range.

        The range can be specified as a single cell (e.g., "A1", (0, 0)) or
        an area (e.g., "A1:B2", (0, 0, 1, 1)).

        Args:
            crange: The cell or area coordinate.

        Raises:
            ValueError: If the coordinate format is incorrect (propagated from `_set_range`).
        """
        self._set_range(crange)
        self._update_attributes()

    def _update_attributes(self) -> None:
        """Update the `table:base-cell-address` and `table:cell-range-address`
        attributes based on the current named range's properties.
        """
        self.set_attribute("table:base-cell-address", self._make_base_cell_address())
        self.set_attribute("table:cell-range-address", self._make_cell_range_address())

    def _make_base_cell_address(self) -> str:
        """Construct the `table:base-cell-address` string for the named range.

        Returns:
            str: The formatted base cell address (e.g., "$'Sheet Name'.A1").
        """
        # assuming we got table_name and range
        if " " in self.table_name:
            name = f"'{self.table_name}'"
        else:
            name = self.table_name
        return f"${name}.${digit_to_alpha(self.start[0])}${self.start[1] + 1}"

    def _make_cell_range_address(self) -> str:
        """Construct the `table:cell-range-address` string for the named range.

        Returns:
            str: The formatted cell range address (e.g., "$'Sheet Name'.A1:$'Sheet Name'.B2").
        """
        # assuming we got table_name and range
        if " " in self.table_name:
            name = f"'{self.table_name}'"
        else:
            name = self.table_name
        if self.start == self.end:
            return self._make_base_cell_address()
        return (
            f"${name}.${digit_to_alpha(self.start[0])}${self.start[1] + 1}:"
            f".${digit_to_alpha(self.end[0])}${self.end[1] + 1}"
        )

    def get_values(
        self,
        cell_type: str | None = None,
        complete: bool = True,
        get_type: bool = False,
        flat: bool = False,
    ) -> list:
        """Retrieve the values of all cells within the named range.

        This is a shortcut to `Table.get_values()` method, applied to the
        table and range defined by this named range.

        Args:
            cell_type: Filter cells by their type (e.g., "string", "float").
            complete: If True, returns a rectangular list, filling empty
                cells with None. If False, returns only non-empty cells.
            get_type: If True, returns (value, type) tuples for each cell.
            flat: If True, returns a flat list of values.

        Returns:
            list: A list of cell values, formatted according to the arguments.

        Raises:
            ValueError: If the named range's table is not found or not inside a document.
        """
        body = self.document_body
        if not body:
            raise ValueError("Table is not inside a document.")
        table = body.get_table(name=self.table_name)
        if table is None:
            raise ValueError(f"Table not found: {self.table_name!r}")
        return table.get_values(self.crange, cell_type, complete, get_type, flat)

    def get_value(self, get_type: bool = False) -> Any:
        """Retrieve the value of the first cell of the named range.

        This is a shortcut to `Table.get_value()` method, applied to the
        first cell defined by this named range.

        Args:
            get_type: If True, returns a tuple of (value, type) for the cell.

        Returns:
            Any | tuple[Any, str]: The cell's value, or a tuple of (value, type)
                if `get_type` is True.

        Raises:
            ValueError: If the named range's table is not found or not inside a document.
        """
        body = self.document_body
        if not body:
            raise ValueError("Table is not inside a document.")
        table: Table | None = body.get_table(name=self.table_name)
        if table is None:
            raise ValueError(f"Table not found: {self.table_name!r}")
        return table.get_value(self.start, get_type)

    def set_values(
        self,
        values: list,
        style: str | None = None,
        cell_type: str | None = None,
        currency: str | None = None,
    ) -> None:
        """Set the values of a range of cells within the named range.

        This is a shortcut to `Table.set_values()` method, applied to the
        table and range defined by this named range.

        Args:
            values: A list of lists representing the new values for the cells.
            style: The style name to apply to the cells.
            cell_type: The type to set for the cells (e.g., "string", "float").
            currency: The currency symbol to use for "currency" type cells.

        Raises:
            ValueError: If the named range's table is not found or not inside a document.
        """
        body = self.document_body
        if not body:
            raise ValueError("Table is not inside a document.")
        table = body.get_table(name=self.table_name)
        if table is None:
            raise ValueError(f"Table not found: {self.table_name!r}")
        table.set_values(
            values,
            coord=self.crange,
            style=style,
            cell_type=cell_type,
            currency=currency,
        )

    def set_value(
        self,
        value: Any,
        cell_type: str | None = None,
        currency: str | None = None,
        style: str | None = None,
    ) -> None:
        """Set the value of the first cell within the named range.

        This is a shortcut to `Table.set_value()` method, applied to the
        first cell defined by this named range.

        Args:
            value: The value to set for the cell.
            cell_type: The type to set for the cell (e.g., "string", "float").
            currency: The currency symbol to use for "currency" type cells.
            style: The style name to apply to the cell.

        Raises:
            ValueError: If the named range's table is not found or not inside a document.
        """
        body = self.document_body
        if not body:
            raise ValueError("Table is not inside a document.")
        table = body.get_table(name=self.table_name)
        if table is None:
            raise ValueError(f"Table not found: {self.table_name!r}")
        table.set_value(
            coord=self.start,
            value=value,
            cell_type=cell_type,
            currency=currency,
            style=style,
        )

_tag class-attribute instance-attribute

_tag = 'table:named-range'

crange instance-attribute

crange: tuple[int, int, int, int] = (0, 0, 0, 0)

end instance-attribute

end: tuple[int, int] = (0, 0)

name property writable

name: str | None

Get the name of the named range.

The name is mandatory, must be alphanumeric with underscores, and cannot be formatted like a cell coordinate (e.g., “A1”).

Returns:

Type Description
str | None

str | None: The name of the named range.

start instance-attribute

start: tuple[int, int] = (0, 0)

table_name instance-attribute

table_name: str = name

usage instance-attribute

usage: str | None = get_attribute_string(
    "table:range-usable-as"
)

__init__

__init__(
    name: str | None = None,
    crange: str | tuple | list | None = None,
    table_name: str | None = None,
    usage: str | None = None,
    **kwargs: Any,
) -> None

Initialize a NamedRange element.

A NamedRange element identifies a range of cells in a table by a name and the table’s name. The name must be alphanumeric with underscores, and not formatted like a cell coordinate (e.g., “A1”). The table_name must be a valid table name (without single quotes or slashes).

Parameters:

Name Type Description Default
name str | None

The name of the named range.

None
crange str | tuple | list | None

The cell or area coordinate, e.g., “A1”, “A1:B2”, (0, 0), or (0, 0, 1, 1).

None
table_name str | None

The name of the table the range belongs to.

None
usage str | None

The usage of the named range, one of “print-range”, “filter”, “repeat-column”, “repeat-row”, or None.

None
**kwargs Any

Additional keyword arguments for the parent Element class.

{}
Source code in odfdo/named_range.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def __init__(
    self,
    name: str | None = None,
    crange: str | tuple | list | None = None,
    table_name: str | None = None,
    usage: str | None = None,
    **kwargs: Any,
) -> None:
    """Initialize a NamedRange element.

    A NamedRange element identifies a range of cells in a table by a name
    and the table's name. The `name` must be alphanumeric with underscores,
    and not formatted like a cell coordinate (e.g., "A1").
    The `table_name` must be a valid table name (without single quotes or slashes).

    Args:
        name: The name of the named range.
        crange: The cell or area coordinate,
            e.g., "A1", "A1:B2", (0, 0), or (0, 0, 1, 1).
        table_name: The name of the table the range belongs to.
        usage: The usage of the named range, one of
            "print-range", "filter", "repeat-column", "repeat-row", or None.
        **kwargs: Additional keyword arguments for the parent `Element` class.
    """
    super().__init__(**kwargs)
    self.usage: str | None = None
    self.table_name: str = ""
    self.start: tuple[int, int] = 0, 0
    self.end: tuple[int, int] = 0, 0
    self.crange: tuple[int, int, int, int] = 0, 0, 0, 0
    self.usage = None
    if self._do_init:
        self.name = name or ""
        self.table_name = table_name_check(table_name)
        self.set_range(crange or "")
        self.set_usage(usage)
    cell_range_address = self.get_attribute_string("table:cell-range-address") or ""
    if not cell_range_address:
        return
    self.usage = self.get_attribute_string("table:range-usable-as")
    name_range = cell_range_address.replace("$", "")
    name, crange = name_range.split(".", 1)
    if name.startswith("'") and name.endswith("'"):
        name = name[1:-1]
    self.table_name = name
    crange = crange.replace(".", "")
    self._set_range(crange)

_check_nr_name staticmethod

_check_nr_name(name: str) -> str

Validate a named range name.

Ensures the name is not empty, contains only alphanumeric characters and underscores, and does not resemble a cell coordinate (e.g., “A1”).

Parameters:

Name Type Description Default
name str

The name to validate.

required

Returns:

Name Type Description
str str

The validated name.

Raises:

Type Description
ValueError

If the name is empty, contains forbidden characters, or is formatted like a cell coordinate.

Source code in odfdo/named_range.py
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
207
208
209
210
211
212
213
214
215
216
217
218
219
@staticmethod
def _check_nr_name(name: str) -> str:
    """Validate a named range name.

    Ensures the name is not empty, contains only alphanumeric characters and
    underscores, and does not resemble a cell coordinate (e.g., "A1").

    Args:
        name: The name to validate.

    Returns:
        str: The validated name.

    Raises:
        ValueError: If the name is empty, contains forbidden characters,
            or is formatted like a cell coordinate.
    """
    name = name.strip()
    if not name:
        raise ValueError("Named Range name can't be empty.")
    for x in name:
        if x in _forbidden_in_named_range():
            msg = f"Character forbidden in Named Range name: {x!r} "
            raise ValueError(msg)
    step = ""
    for x in name:
        if x in string.ascii_letters and step in ("", "A"):
            step = "A"
            continue
        elif step in ("A", "A1") and x in string.digits:
            step = "A1"
            continue
        else:
            step = ""
            break
    if step == "A1":
        msg = f"Name of the type 'ABC123' is not allowed for Named Range: {name!r}"
        raise ValueError(msg)
    return name

_make_base_cell_address

_make_base_cell_address() -> str

Construct the table:base-cell-address string for the named range.

Returns:

Name Type Description
str str

The formatted base cell address (e.g., “$’Sheet Name’.A1”).

Source code in odfdo/named_range.py
314
315
316
317
318
319
320
321
322
323
324
325
def _make_base_cell_address(self) -> str:
    """Construct the `table:base-cell-address` string for the named range.

    Returns:
        str: The formatted base cell address (e.g., "$'Sheet Name'.A1").
    """
    # assuming we got table_name and range
    if " " in self.table_name:
        name = f"'{self.table_name}'"
    else:
        name = self.table_name
    return f"${name}.${digit_to_alpha(self.start[0])}${self.start[1] + 1}"

_make_cell_range_address

_make_cell_range_address() -> str

Construct the table:cell-range-address string for the named range.

Returns:

Name Type Description
str str

The formatted cell range address (e.g., “$’Sheet Name’.A1:$’Sheet Name’.B2”).

Source code in odfdo/named_range.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
def _make_cell_range_address(self) -> str:
    """Construct the `table:cell-range-address` string for the named range.

    Returns:
        str: The formatted cell range address (e.g., "$'Sheet Name'.A1:$'Sheet Name'.B2").
    """
    # assuming we got table_name and range
    if " " in self.table_name:
        name = f"'{self.table_name}'"
    else:
        name = self.table_name
    if self.start == self.end:
        return self._make_base_cell_address()
    return (
        f"${name}.${digit_to_alpha(self.start[0])}${self.start[1] + 1}:"
        f".${digit_to_alpha(self.end[0])}${self.end[1] + 1}"
    )

_set_range

_set_range(coord: tuple | list | str) -> None

Internal helper to set the cell range coordinates.

Parameters:

Name Type Description Default
coord tuple | list | str

The cell or area coordinate, e.g., “A1”, “A1:B2”, (0, 0), or (0, 0, 1, 1).

required

Raises:

Type Description
ValueError

If the coordinate format is incorrect.

Source code in odfdo/named_range.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
def _set_range(self, coord: tuple | list | str) -> None:
    """Internal helper to set the cell range coordinates.

    Args:
        coord: The cell or area coordinate,
            e.g., "A1", "A1:B2", (0, 0), or (0, 0, 1, 1).

    Raises:
        ValueError: If the coordinate format is incorrect.
    """
    digits = convert_coordinates(coord)
    if len(digits) == 4:
        x, y, z, t = digits
    else:
        x, y = digits
        z, t = digits
    if x is None or y is None or z is None or t is None:
        raise ValueError(f"Wrong format for cell range: {coord!r}")
    self.start = x, y
    self.end = z, t
    self.crange = x, y, z, t

_update_attributes

_update_attributes() -> None

Update the table:base-cell-address and table:cell-range-address attributes based on the current named range’s properties.

Source code in odfdo/named_range.py
307
308
309
310
311
312
def _update_attributes(self) -> None:
    """Update the `table:base-cell-address` and `table:cell-range-address`
    attributes based on the current named range's properties.
    """
    self.set_attribute("table:base-cell-address", self._make_base_cell_address())
    self.set_attribute("table:cell-range-address", self._make_cell_range_address())

get_value

get_value(get_type: bool = False) -> Any

Retrieve the value of the first cell of the named range.

This is a shortcut to Table.get_value() method, applied to the first cell defined by this named range.

Parameters:

Name Type Description Default
get_type bool

If True, returns a tuple of (value, type) for the cell.

False

Returns:

Type Description
Any

Any | tuple[Any, str]: The cell’s value, or a tuple of (value, type) if get_type is True.

Raises:

Type Description
ValueError

If the named range’s table is not found or not inside a document.

Source code in odfdo/named_range.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def get_value(self, get_type: bool = False) -> Any:
    """Retrieve the value of the first cell of the named range.

    This is a shortcut to `Table.get_value()` method, applied to the
    first cell defined by this named range.

    Args:
        get_type: If True, returns a tuple of (value, type) for the cell.

    Returns:
        Any | tuple[Any, str]: The cell's value, or a tuple of (value, type)
            if `get_type` is True.

    Raises:
        ValueError: If the named range's table is not found or not inside a document.
    """
    body = self.document_body
    if not body:
        raise ValueError("Table is not inside a document.")
    table: Table | None = body.get_table(name=self.table_name)
    if table is None:
        raise ValueError(f"Table not found: {self.table_name!r}")
    return table.get_value(self.start, get_type)

get_values

get_values(
    cell_type: str | None = None,
    complete: bool = True,
    get_type: bool = False,
    flat: bool = False,
) -> list

Retrieve the values of all cells within the named range.

This is a shortcut to Table.get_values() method, applied to the table and range defined by this named range.

Parameters:

Name Type Description Default
cell_type str | None

Filter cells by their type (e.g., “string”, “float”).

None
complete bool

If True, returns a rectangular list, filling empty cells with None. If False, returns only non-empty cells.

True
get_type bool

If True, returns (value, type) tuples for each cell.

False
flat bool

If True, returns a flat list of values.

False

Returns:

Name Type Description
list list

A list of cell values, formatted according to the arguments.

Raises:

Type Description
ValueError

If the named range’s table is not found or not inside a document.

Source code in odfdo/named_range.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
def get_values(
    self,
    cell_type: str | None = None,
    complete: bool = True,
    get_type: bool = False,
    flat: bool = False,
) -> list:
    """Retrieve the values of all cells within the named range.

    This is a shortcut to `Table.get_values()` method, applied to the
    table and range defined by this named range.

    Args:
        cell_type: Filter cells by their type (e.g., "string", "float").
        complete: If True, returns a rectangular list, filling empty
            cells with None. If False, returns only non-empty cells.
        get_type: If True, returns (value, type) tuples for each cell.
        flat: If True, returns a flat list of values.

    Returns:
        list: A list of cell values, formatted according to the arguments.

    Raises:
        ValueError: If the named range's table is not found or not inside a document.
    """
    body = self.document_body
    if not body:
        raise ValueError("Table is not inside a document.")
    table = body.get_table(name=self.table_name)
    if table is None:
        raise ValueError(f"Table not found: {self.table_name!r}")
    return table.get_values(self.crange, cell_type, complete, get_type, flat)

set_range

set_range(
    crange: str
    | tuple[int, int]
    | tuple[int, int, int, int]
    | list[int],
) -> None

Set the cell range for the named range.

The range can be specified as a single cell (e.g., “A1”, (0, 0)) or an area (e.g., “A1:B2”, (0, 0, 1, 1)).

Parameters:

Name Type Description Default
crange str | tuple[int, int] | tuple[int, int, int, int] | list[int]

The cell or area coordinate.

required

Raises:

Type Description
ValueError

If the coordinate format is incorrect (propagated from _set_range).

Source code in odfdo/named_range.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def set_range(
    self,
    crange: str | tuple[int, int] | tuple[int, int, int, int] | list[int],
) -> None:
    """Set the cell range for the named range.

    The range can be specified as a single cell (e.g., "A1", (0, 0)) or
    an area (e.g., "A1:B2", (0, 0, 1, 1)).

    Args:
        crange: The cell or area coordinate.

    Raises:
        ValueError: If the coordinate format is incorrect (propagated from `_set_range`).
    """
    self._set_range(crange)
    self._update_attributes()

set_table_name

set_table_name(name: str) -> None

Set the name of the table associated with the named range.

Parameters:

Name Type Description Default
name str

The name of the table.

required

Raises:

Type Description
TypeError

If name is not a string (propagated from table_name_check).

ValueError

If name is empty or contains forbidden characters (propagated from table_name_check).

Source code in odfdo/named_range.py
254
255
256
257
258
259
260
261
262
263
264
265
def set_table_name(self, name: str) -> None:
    """Set the name of the table associated with the named range.

    Args:
        name: The name of the table.

    Raises:
        TypeError: If `name` is not a string (propagated from `table_name_check`).
        ValueError: If `name` is empty or contains forbidden characters (propagated from `table_name_check`).
    """
    self.table_name = table_name_check(name)
    self._update_attributes()

set_usage

set_usage(usage: str | None = None) -> None

Set the usage type for the named range.

The usage specifies how the named range is intended to be used (e.g., for printing, filtering, or repeating columns/rows).

Parameters:

Name Type Description Default
usage str | None

The usage type. Can be “print-range”, “filter”, “repeat-column”, “repeat-row”, or None to clear the usage.

None
Source code in odfdo/named_range.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def set_usage(self, usage: str | None = None) -> None:
    """Set the usage type for the named range.

    The usage specifies how the named range is intended to be used (e.g.,
    for printing, filtering, or repeating columns/rows).

    Args:
        usage: The usage type. Can be "print-range", "filter",
            "repeat-column", "repeat-row", or None to clear the usage.
    """
    if usage is not None:
        usage = usage.strip().lower()
        if usage not in ("print-range", "filter", "repeat-column", "repeat-row"):
            usage = None
    if usage is None:
        with contextlib.suppress(KeyError):
            self.del_attribute("table:range-usable-as")
        self.usage = None
    else:
        self.set_attribute("table:range-usable-as", usage)
        self.usage = usage

set_value

set_value(
    value: Any,
    cell_type: str | None = None,
    currency: str | None = None,
    style: str | None = None,
) -> None

Set the value of the first cell within the named range.

This is a shortcut to Table.set_value() method, applied to the first cell defined by this named range.

Parameters:

Name Type Description Default
value Any

The value to set for the cell.

required
cell_type str | None

The type to set for the cell (e.g., “string”, “float”).

None
currency str | None

The currency symbol to use for “currency” type cells.

None
style str | None

The style name to apply to the cell.

None

Raises:

Type Description
ValueError

If the named range’s table is not found or not inside a document.

Source code in odfdo/named_range.py
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
def set_value(
    self,
    value: Any,
    cell_type: str | None = None,
    currency: str | None = None,
    style: str | None = None,
) -> None:
    """Set the value of the first cell within the named range.

    This is a shortcut to `Table.set_value()` method, applied to the
    first cell defined by this named range.

    Args:
        value: The value to set for the cell.
        cell_type: The type to set for the cell (e.g., "string", "float").
        currency: The currency symbol to use for "currency" type cells.
        style: The style name to apply to the cell.

    Raises:
        ValueError: If the named range's table is not found or not inside a document.
    """
    body = self.document_body
    if not body:
        raise ValueError("Table is not inside a document.")
    table = body.get_table(name=self.table_name)
    if table is None:
        raise ValueError(f"Table not found: {self.table_name!r}")
    table.set_value(
        coord=self.start,
        value=value,
        cell_type=cell_type,
        currency=currency,
        style=style,
    )

set_values

set_values(
    values: list,
    style: str | None = None,
    cell_type: str | None = None,
    currency: str | None = None,
) -> None

Set the values of a range of cells within the named range.

This is a shortcut to Table.set_values() method, applied to the table and range defined by this named range.

Parameters:

Name Type Description Default
values list

A list of lists representing the new values for the cells.

required
style str | None

The style name to apply to the cells.

None
cell_type str | None

The type to set for the cells (e.g., “string”, “float”).

None
currency str | None

The currency symbol to use for “currency” type cells.

None

Raises:

Type Description
ValueError

If the named range’s table is not found or not inside a document.

Source code in odfdo/named_range.py
402
403
404
405
406
407
408
409
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
def set_values(
    self,
    values: list,
    style: str | None = None,
    cell_type: str | None = None,
    currency: str | None = None,
) -> None:
    """Set the values of a range of cells within the named range.

    This is a shortcut to `Table.set_values()` method, applied to the
    table and range defined by this named range.

    Args:
        values: A list of lists representing the new values for the cells.
        style: The style name to apply to the cells.
        cell_type: The type to set for the cells (e.g., "string", "float").
        currency: The currency symbol to use for "currency" type cells.

    Raises:
        ValueError: If the named range's table is not found or not inside a document.
    """
    body = self.document_body
    if not body:
        raise ValueError("Table is not inside a document.")
    table = body.get_table(name=self.table_name)
    if table is None:
        raise ValueError(f"Table not found: {self.table_name!r}")
    table.set_values(
        values,
        coord=self.crange,
        style=style,
        cell_type=cell_type,
        currency=currency,
    )

_forbidden_in_named_range cached

_forbidden_in_named_range() -> set[str]

Return a set of characters forbidden in named range names.

This set is computed once and cached. Forbidden characters include most punctuation and symbols, excluding underscore.

Returns:

Type Description
set[str]

set[str]: A set of forbidden characters.

Source code in odfdo/named_range.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
@cache
def _forbidden_in_named_range() -> set[str]:
    """Return a set of characters forbidden in named range names.

    This set is computed once and cached. Forbidden characters include
    most punctuation and symbols, excluding underscore.

    Returns:
        set[str]: A set of forbidden characters.
    """
    return {
        char
        for char in string.printable
        if char not in string.ascii_letters
        and char not in string.digits
        and char != "_"
    }

table_name_check

table_name_check(name: Any) -> str

Validate a table name for use in ODF documents.

Ensures the name is a non-empty string and does not contain forbidden characters like single quotes, slashes, asterisks, question marks, or brackets.

Parameters:

Name Type Description Default
name Any

The name to validate.

required

Returns:

Name Type Description
str str

The validated and stripped table name.

Raises:

Type Description
TypeError

If name is not a string.

ValueError

If name is empty or contains forbidden characters.

Source code in odfdo/named_range.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def table_name_check(name: Any) -> str:
    """Validate a table name for use in ODF documents.

    Ensures the name is a non-empty string and does not contain forbidden
    characters like single quotes, slashes, asterisks, question marks, or brackets.

    Args:
        name: The name to validate.

    Returns:
        str: The validated and stripped table name.

    Raises:
        TypeError: If `name` is not a string.
        ValueError: If `name` is empty or contains forbidden characters.
    """
    if not isinstance(name, str):
        raise TypeError("String required.")
    table_name: str = name.strip()
    if not table_name:
        raise ValueError("Empty name not allowed.")
    if match := _RE_TABLE_NAME.search(table_name):
        raise ValueError(f"Character {match.group()!r} not allowed.")
    return table_name