Skip to content

Cell

Cell class for “table:table-cell” and “table:covered-table-cell” tags.

Classes:

Name Description
Cell

A cell of a table, “table:table-cell” and “table:covered-table-cell”.

_bool module-attribute

_bool = builtins.bool

_float module-attribute

_float = builtins.float

_int module-attribute

_int = builtins.int

Cell

Bases: ListMixin, TocMixin, SectionMixin, AnnotationMixin, ElementTyped

A cell of a table, “table:table-cell” and “table:covered-table-cell”.

Methods:

Name Description
__init__

Create a cell element.

__repr__
is_covered

Check if the cell is covered.

is_empty

Check if the cell is empty.

is_spanned

Check if the cell spans over multiple cells.

set_value

Set the cell state from a Python value.

span_area

Return the dimensions of the area spanned by the cell.

Attributes:

Name Type Description
bool _bool

Get or set the value of the cell as a boolean.

clone Cell
currency str | None

Get or set the currency used for monetary values.

date date

Get or set the value of the cell as a date.

datetime datetime

Get or set the value of the cell as a datetime.

decimal Decimal

Get or set the value of the cell as a Decimal (or 0.0).

duration timedelta

Get or set the value of the cell as a duration (Python timedelta).

float _float

Get or set the value of the cell as a float (or 0.0).

formula str | None

Get or set the formula of the cell.

int _int

Get or set the value of the cell as an integer (or 0).

repeated _int | None

Get or set the number of times the cell is repeated across columns.

string str

Get or set the value of the cell as a string (or ‘’).

style str | None

Get or set the style name of the cell.

type str | None

Get or set the type of the cell.

value CellValue | None

Get or set the value of the cell.

x _int | None
y _int | None
Source code in odfdo/cell.py
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
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
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
class Cell(ListMixin, TocMixin, SectionMixin, AnnotationMixin, ElementTyped):
    """A cell of a table, "table:table-cell" and "table:covered-table-cell"."""

    _tag = "table:table-cell"

    def __init__(
        self,
        value: CellValue | None = None,
        text: str | None = None,
        cell_type: str | None = None,
        currency: str | None = None,
        formula: str | None = None,
        repeated: _int | None = None,
        style: str | None = None,
        **kwargs: Any,
    ) -> None:
        """Create a cell element.

        A cell in a table, represented by "table:table-cell".
        This constructor creates a cell element containing the given value.
        The textual representation is automatically formatted but can be
        provided explicitly. The cell type can be deduced automatically,
        unless the number is a percentage or currency. If the cell type is
        "currency", the currency must be specified. The cell can also be
        repeated across a given number of columns.

        Args:
            value: The Python value to set for the cell. Can be a boolean,
                int, float, Decimal, date, datetime, str, timedelta or None.
            text: The textual representation of the cell's content. If not
                provided, it is generated from the value.
            cell_type: The explicit type of the cell. Valid options include
                'boolean', 'currency', 'date', 'float', 'percentage',
                'string', or 'time'. If not provided, it's guessed from the
                value.
            currency: A three-letter currency code (e.g., "EUR", "USD") if
                the cell_type is 'currency'.
            formula: The formula for the cell.
            repeated: The number of times this cell should be repeated across
                columns. Must be greater than 1.
            style: The name of the style to apply to the cell.
        """
        super().__init__(**kwargs)
        self.x: _int | None = None
        self.y: _int | None = None
        if self._do_init:
            self.set_value(
                value,
                text=text,
                cell_type=cell_type,
                currency=currency,
                formula=formula,
            )
            if repeated and repeated > 1:
                self.repeated = repeated
            if style is not None:
                self.style = style

    def __repr__(self) -> str:
        return f"<{self.__class__.__name__} x={self.x} y={self.y}>"

    @property
    def clone(self) -> Cell:
        clone = Element.clone.fget(self)
        clone.y = self.y
        clone.x = self.x
        return clone

    @property
    def value(self) -> CellValue | None:
        """Get or set the value of the cell.

        When getting, the type is inferred from the 'office:value-type'
        attribute.
        When setting, the type of the provided Python value determines the
        'office:value-type' of the cell. The style of the cell is kept, to
        clear completely the cell, use cell.clear().

        Note: the cell style content is kepts when using "cell.value = None".
        To ensure an absolute empty cell, use cell.clear() that will remove
        all componants (style, xml:id, ...).

        Warning:
            *   For `date`, `datetime`, and `timedelta`, a default text value
                is automatically generated.
            *   For boolean types, the text value will be either 'True' or
                'False'.
            *   For numeric types, the return value is typically `Decimal` or
                `int`. Use the `float`, `decimal`, or `int` properties to
                force a specific return type.
            *   To customize the text representation, use the `set_value()`
                method.
            *   To change the string representation of the cell without
                changing the cell type, use the low level property cell.text
            *   If modifying a repeated cell directly (`cell.repeated > 1`),
                changing its value will affect all repeated instances sharing
                this cell XML element node. To modify a single repeated cell
                without affecting others, use `Table.set_value()` or
                `Row.set_value()`.

        Returns:
            Union[str, bool, int, float, Decimal, date, datetime, timedelta,
                None]: The value of the cell in its appropriate Python type.
        """
        value_type = self.get_attribute_string("office:value-type")
        if value_type in {"float", "percentage", "currency"} or (
            value_type is None and self.get_attribute("office:value") is not None
        ):
            val_str = self.get_attribute_string("office:value")
            if val_str is None:
                return None
            s_upper = val_str.strip().upper()
            if s_upper == "NAN":
                return _float("nan")
            if s_upper in {"INF", "+INF", "INFINITY", "+INFINITY"}:
                return _float("inf")
            if s_upper in {"-INF", "-INFINITY"}:
                return _float("-inf")
            with contextlib.suppress(Exception):
                value_decimal = Decimal(val_str)
                if _int(value_decimal) == value_decimal:
                    return _int(value_decimal)
                return value_decimal
            try:
                return _float(val_str)
            except Exception:
                return None
        match value_type:
            case "boolean":
                return self.bool
            case "date":
                value_str = str(self.get_attribute_string("office:date-value"))
                if "T" in value_str:
                    return DateTime.decode(value_str)
                return Date.decode(value_str)
            case "time":
                return Duration.decode(
                    str(self.get_attribute_string("office:time-value"))
                )
            case "string":
                value = self.get_attribute_string("office:string-value")
                if value is not None:
                    return value
                value_list = []
                for para in self.get_elements("text:p"):
                    value_list.append(para.inner_text)
                return "\n".join(value_list)
            case _:
                return None

    @value.setter
    def value(self, value: CellValue | None) -> None:
        match value:
            case None:
                self.delete_children()
                self.clear_attrinutes()
            case str() | bytes():
                self.string = value
            case _bool():
                self.bool = value
            case _float():
                self.float = value
            case Decimal():
                self.decimal = value
            case _int():
                self.int = value
            case timedelta():
                self.duration = value
            case _datetime():
                self.datetime = value
            case _date():
                self.date = value
            case _:
                raise TypeError(f"Unknown value type, try with set_value() : {value!r}")

    @property
    def _bool_string(self) -> str:
        """Return the boolean value as a string '0' or '1'."""
        value = self.get_attribute_string("office:boolean-value")
        if not isinstance(value, str):
            return "0"
        return "1" if value == "true" else "0"

    @property
    def float(self) -> _float:
        """Get or set the value of the cell as a float (or 0.0).

        The style of the cell is kept, to clear completely the cell, use
        cell.clear().

        When setting the value, force the cell type to "float".

        Warning:
            If modifying a repeated cell directly ("cell.repeated > 1"),
            changing its value will affect all repeated instances sharing
            this cell XML element node. To modify a single repeated cell
            without affecting others, use "Table.set_value()" or
            "Row.set_value()".
        """
        for tag in {"office:value", "office:string-value"}:
            read_attr = self.get_attribute(tag)
            if isinstance(read_attr, str):
                s_upper = read_attr.strip().upper()
                if s_upper == "NAN":
                    return _float("nan")
                if s_upper in {"INF", "+INF", "INFINITY", "+INFINITY"}:
                    return _float("inf")
                if s_upper in {"-INF", "-INFINITY"}:
                    return _float("-inf")
                with contextlib.suppress(ValueError, TypeError):
                    return _float(read_attr)
        return _float(self._bool_string)

    @float.setter
    def float(self, value: str | _float | _int | Decimal | None) -> None:
        if isinstance(value, str):
            s_upper = value.strip().upper()
            if s_upper == "NAN":
                self._set_float_value_str("NaN")
                return
            if s_upper in {"INF", "+INF", "INFINITY", "+INFINITY"}:
                self._set_float_value_str("INF")
                return
            if s_upper in {"-INF", "-INFINITY"}:
                self._set_float_value_str("-INF")
                return

        try:
            value_float = _float(value)  # ty: ignore[invalid-argument-type]
        except (ValueError, TypeError, ConversionSyntax):
            value_float = 0.0

        if math.isnan(value_float):
            value_str = "NaN"
        elif math.isinf(value_float):
            value_str = "INF" if value_float > 0 else "-INF"
        else:
            value_str = str(value_float)

        self._set_float_value_str(value_str)

    def _set_float_value_str(self, value_str: str) -> None:
        if self.type != "float":
            # remove attributes that can exist from a previous different cell
            # type.
            # Note: the Cell may also contains non standanrd attributes (ooo)
            # or sub elements (test:p, ...)
            self.clear_attrinutes()
            self.set_attribute("office:value-type", "float")
        self.set_attribute("office:value", value_str)
        self.set_text_content(value_str)

    @property
    def decimal(self) -> Decimal:
        """Get or set the value of the cell as a Decimal (or 0.0).

        The style of the cell is kept, to clear completely the cell, use
        cell.clear().

        When setting the value, force the cell type to "float".

        Warning:
            If modifying a repeated cell directly ("cell.repeated > 1"),
            changing its value will affect all repeated instances sharing
            this cell XML element node. To modify a single repeated cell
            without affecting others, use "Table.set_value()" or
            "Row.set_value()".
        """
        for tag in {"office:value", "office:string-value"}:
            read_attr = self.get_attribute(tag)
            if isinstance(read_attr, str):
                s_upper = read_attr.strip().upper()
                if s_upper == "NAN":
                    return Decimal("nan")
                if s_upper in {"INF", "+INF", "INFINITY", "+INFINITY"}:
                    return Decimal("inf")
                if s_upper in {"-INF", "-INFINITY"}:
                    return Decimal("-inf")
                with contextlib.suppress(ValueError, TypeError, ConversionSyntax):
                    return Decimal(read_attr)
        return Decimal(self._bool_string)

    @decimal.setter
    def decimal(self, value: str | _float | _int | Decimal | None) -> None:
        if isinstance(value, str):
            s_upper = value.strip().upper()
            if s_upper == "NAN":
                self._set_float_value_str("NaN")
                return
            if s_upper in {"INF", "+INF", "INFINITY", "+INFINITY"}:
                self._set_float_value_str("INF")
                return
            if s_upper in {"-INF", "-INFINITY"}:
                self._set_float_value_str("-INF")
                return

        if isinstance(value, float):
            if math.isnan(value):
                self._set_float_value_str("NaN")
                return
            if math.isinf(value):
                self._set_float_value_str("INF" if value > 0 else "-INF")
                return

        if isinstance(value, Decimal):
            if value.is_nan():
                self._set_float_value_str("NaN")
                return
            if value.is_infinite():
                self._set_float_value_str("INF" if value > 0 else "-INF")
                return

        try:
            value_decimal = Decimal(str(value))
        except (ValueError, TypeError, ConversionSyntax, InvalidOperation):
            value_decimal = Decimal("0")

        self._set_float_value_str(str(value_decimal))

    @property
    def int(self) -> _int:
        """Get or set the value of the cell as an integer (or 0).

        The style of the cell is kept, to clear completely the cell, use
        cell.clear().

        When setting the value, force the cell type to "float".

        Warning:
            If modifying a repeated cell directly ("cell.repeated > 1"),
            changing its value will affect all repeated instances sharing
            this cell XML element node. To modify a single repeated cell
            without affecting others, use "Table.set_value()" or
            "Row.set_value()".
        """
        for tag in {"office:value", "office:string-value"}:
            read_attr = self.get_attribute(tag)
            if isinstance(read_attr, str):
                with contextlib.suppress(ValueError, TypeError):
                    return _int(_float(read_attr))
        return _int(self._bool_string)

    @int.setter
    def int(self, value: str | _float | _int | Decimal | None) -> None:
        try:
            value_int = _int(value)  # ty:ignore
        except (ValueError, TypeError, ConversionSyntax):
            value_int = 0
        value_str = str(value_int)
        self._set_float_value_str(value_str)

    @property
    def string(self) -> str:
        """Get or set the value of the cell as a string (or '').

        The style of the cell is kept, to clear completely the cell, use
        cell.clear().

        When setting the value, force the cell type to "string".

        Warning:
            If modifying a repeated cell directly ("cell.repeated > 1"),
            changing its value will affect all repeated instances sharing
            this cell XML element node. To modify a single repeated cell
            without affecting others, use "Table.set_value()" or
            "Row.set_value()".
        """
        value = self.get_attribute_string("office:string-value")
        if isinstance(value, str):
            return value
        return ""

    @string.setter
    def string(
        self,
        value: str | bytes | _int | _float | Decimal | _bool | None,
    ) -> None:
        if value is None:
            value_str = ""
        elif isinstance(value, bytes):
            value_str = value.decode()
        else:
            value_str = str(value)
        self.delete_children()
        if self.type != "string":
            # remove attributes that can exist from a previous different cell
            # type.
            # Note: the Cell may also contains non standanrd attributes (ooo)
            # or sub elements (text:p, ...)
            self.clear_attrinutes()
            self.set_attribute("office:value-type", "string")
        self.set_attribute("office:string-value", value_str)
        self.set_text_content(value_str)

    @property
    def bool(self) -> _bool:
        """Get or set the value of the cell as a boolean.

        The style of the cell is kept, to clear completely the cell, use
        cell.clear().

        When setting the value, force the cell type to "boolean".

        Warning:
            If modifying a repeated cell directly ("cell.repeated > 1"),
            changing its value will affect all repeated instances sharing
            this cell XML element node. To modify a single repeated cell
            without affecting others, use "Table.set_value()" or
            "Row.set_value()".
        """
        value = self.get_attribute_string("office:boolean-value")
        if isinstance(value, str):
            return value == "true"
        return _bool(self.int)

    @bool.setter
    def bool(
        self,
        value: str | bytes | _int | _float | Decimal | _bool | None,
    ) -> None:
        if isinstance(value, (_bool, str, bytes)):
            bvalue = Boolean.encode(value)
        else:
            bvalue = Boolean.encode(_bool(value))
        if self.type != "boolean":
            # remove attributes that can exist from a previous different cell
            # type.
            # Note: the Cell may also contains non standanrd attributes (ooo)
            # or sub elements (test:p, ...)
            self.clear_attrinutes()
            self.set_attribute("office:value-type", "boolean")
        self.set_attribute("office:boolean-value", bvalue)
        self.set_text_content(bvalue)

    @property
    def duration(self) -> timedelta:
        """Get or set the value of the cell as a duration (Python timedelta).

        The style of the cell is kept, to clear completely the cell, use
        cell.clear().

        When setting the value, force the cell type to "time".

        Warning:
            If modifying a repeated cell directly ("cell.repeated > 1"),
            changing its value will affect all repeated instances sharing
            this cell XML element node. To modify a single repeated cell
            without affecting others, use "Table.set_value()" or
            "Row.set_value()".
        """
        value = self.get_attribute("office:time-value")
        if isinstance(value, str):
            return Duration.decode(value)
        return timedelta(0)

    @duration.setter
    def duration(self, value: timedelta) -> None:
        dvalue = Duration.encode(value)
        if self.type != "time":
            # remove attributes that can exist from a previous different cell
            # type.
            # Note: the Cell may also contains non standanrd attributes (ooo)
            # or sub elements (test:p, ...)
            self.clear_attrinutes()
            self.set_attribute("office:value-type", "time")
        self.set_attribute("office:time-value", dvalue)
        self.set_text_content(dvalue)

    @property
    def datetime(self) -> _datetime:
        """Get or set the value of the cell as a datetime.

        The style of the cell is kept, to clear completely the cell, use
        cell.clear().

        When setting the value, force the cell type to "date".

        Warning:
            If modifying a repeated cell directly ("cell.repeated > 1"),
            changing its value will affect all repeated instances sharing
            this cell XML element node. To modify a single repeated cell
            without affecting others, use "Table.set_value()" or
            "Row.set_value()".
        """
        value = self.get_attribute("office:date-value")
        if isinstance(value, str):
            return DateTime.decode(value)
        return _datetime.fromtimestamp(0)

    @datetime.setter
    def datetime(self, value: _datetime) -> None:
        dvalue = DateTime.encode(value)
        if self.type != "date":
            # remove attributes that can exist from a previous different cell
            # type.
            # Note: the Cell may also contains non standanrd attributes (ooo)
            # or sub elements (test:p, ...)
            self.clear_attrinutes()
            self.set_attribute("office:value-type", "date")
        self.set_attribute("office:date-value", dvalue)
        self.set_text_content(dvalue)

    @property
    def date(self) -> _date:
        """Get or set the value of the cell as a date.

        The style of the cell is kept, to clear completely the cell, use
        cell.clear().

        When setting the value, force the cell type to "date".

        Warning:
            If modifying a repeated cell directly ("cell.repeated > 1"),
            changing its value will affect all repeated instances sharing
            this cell XML element node. To modify a single repeated cell
            without affecting others, use "Table.set_value()" or
            "Row.set_value()".
        """
        value = self.get_attribute("office:date-value")
        if isinstance(value, str):
            return Date.decode(value)
        return _date.fromtimestamp(0)

    @date.setter
    def date(self, value: _date) -> None:
        dvalue = Date.encode(value)
        if self.type != "date":
            # remove attributes that can exist from a previous different cell
            # type.
            # Note: the Cell may also contains non standanrd attributes (ooo)
            # or sub elements (test:p, ...)
            self.clear_attrinutes()
            self.set_attribute("office:value-type", "date")
        self.set_attribute("office:date-value", dvalue)
        self.set_text_content(dvalue)

    def set_value(
        self,
        value: CellValue | None,
        text: str | None = None,
        cell_type: str | None = None,
        currency: str | None = None,
        formula: str | None = None,
    ) -> None:
        """Set the cell state from a Python value.

        The `text` parameter defines how the cell is displayed.
        The cell type is guessed unless explicitly provided.
        For monetary values, the name of the currency must be provided.

        The style of the cell is kept, to clear completely the cell, use
        cell.clear().

        Warning:
            If modifying a repeated cell directly ("cell.repeated > 1"),
            changing its value will affect all repeated instances sharing
            this cell XML element node. To modify a single repeated cell
            without affecting others, use "Table.set_value()" or
            "Row.set_value()".

        Args:
            value:
                The Python value to assign to the cell.
            text: The explicit textual representation of the cell's content.
                If None, it is derived from the `value`.
            cell_type: The explicit type of the cell's value. Can be
                'boolean', 'float', 'date', 'string', 'time', 'currency', or
                'percentage'.
            currency: A string representing the currency, e.g., "EUR" or
                "USD", required if `cell_type` is 'currency'.
            formula: The formula to set for the cell.
        """
        text = self.set_value_and_type(
            value=value,
            text=text,
            value_type=cell_type,
            currency=currency,
        )
        if text is not None:
            self.text_content = text
        if formula is not None:
            self.formula = formula

    @property
    def type(self) -> str | None:
        """Get or set the type of the cell.

        Valid types include 'boolean', 'float', 'date', 'string', or 'time'.

        Returns:
            str or None: The type of the cell's value.
        """
        return self.get_attribute_string("office:value-type")

    @type.setter
    def type(self, cell_type: str) -> None:
        self.set_attribute("office:value-type", cell_type)

    @property
    def currency(self) -> str | None:
        """Get or set the currency used for monetary values.

        Warning:
            If modifying a repeated cell directly ("cell.repeated > 1"),
            changing its value will affect all repeated instances sharing
            this cell XML element node. To modify a single repeated cell
            without affecting others, use "Table.set_value()" or
            "Row.set_value()".

        Returns:
            str or None: The currency code (e.g., "EUR", "USD").
        """
        return self.get_attribute_string("office:currency")

    @currency.setter
    def currency(self, currency: str) -> None:
        self.set_attribute("office:currency", currency)

    def _set_repeated(self, repeated: _int | None) -> None:
        """Set the number of times the cell is repeated (internal).

        Internal method that sets the 'table:number-columns-repeated'
        attribute, or removes it if `repeated` is None or less than 2,
        without triggering cache updates.

        Args:
            repeated: The number of times the cell should be repeated. If
                None or less than 2, the attribute is removed.
        """
        if repeated is None or repeated < 2:
            with contextlib.suppress(KeyError):
                self.del_attribute("table:number-columns-repeated")
            return
        self.set_attribute("table:number-columns-repeated", str(repeated))

    @property
    def repeated(self) -> _int | None:
        """Get or set the number of times the cell is repeated across columns.

        This property is typically None when using the higher-level table API.

        Returns:
            int or None: The number of repetitions, or None if not repeated.
        """
        repeated = self.get_attribute("table:number-columns-repeated")
        if repeated is None:
            return None
        return _int(repeated)

    @repeated.setter
    def repeated(self, repeated: _int | None) -> None:
        self._set_repeated(repeated)
        # update cache
        child: Element = self
        while True:
            # look for Row, parent may be group of rows
            upper = child.parent
            if not upper:
                # lonely cell
                return
            # parent may be group of rows, not table
            if isinstance(upper, Element) and upper._tag == "table:table-row":
                upper._compute_row_cache()
                return
            child = upper

    @property
    def style(self) -> str | None:
        """Get or set the style name of the cell.

        Returns:
            str or None: The name of the style applied to the cell.
        """
        return self.get_attribute_string("table:style-name")

    @style.setter
    def style(self, style: str | Style) -> None:
        self.set_style_attribute("table:style-name", style)

    @property
    def formula(self) -> str | None:
        """Get or set the formula of the cell.

        The formula is stored as a string and is not interpreted by odfdo.

        Returns:
            str or None: The formula string, or None if no formula is defined.
        """
        return self.get_attribute_string("table:formula")

    @formula.setter
    def formula(self, formula: str | None) -> None:
        self.set_attribute("table:formula", formula)

    def is_empty(self, aggressive: _bool = False) -> _bool:
        """Check if the cell is empty.

        An empty cell has no value, no children, is not covered, and is not
        spanned. By default, cells with a style are not considered empty.

        Args:
            aggressive: If True, a cell with a style but no content is also
                considered empty. Defaults to False.

        Returns:
            bool: True if the cell is empty, False otherwise.
        """
        if (
            self.value is not None
            or self.children
            or self.is_covered()
            or self.is_spanned()
        ):
            return False
        if not aggressive and self.style is not None:  # noqa: SIM103
            return False
        return True

    def is_covered(self) -> _bool:
        """Check if the cell is covered.

        A covered cell is represented by the "table:covered-table-cell" tag.

        Returns:
            bool: True if the cell is covered, False otherwise.
        """
        return self.tag == "table:covered-table-cell"

    def is_spanned(self, covered: _bool = True) -> _bool:
        """Check if the cell spans over multiple cells.

        A cell is considered spanned if it has 'table:number-columns-spanned'
        or 'table:number-rows-spanned' attributes.

        Args:
            covered: If True, covered cells (those with the
                "table:covered-table-cell" tag) are also considered spanned.
                Defaults to True.

        Returns:
            bool: True if the cell is spanned, False otherwise.
        """
        if self.is_covered():
            return covered
        if self.get_attribute("table:number-columns-spanned") is not None:
            return True
        if self.get_attribute("table:number-rows-spanned") is not None:  # noqa: SIM103
            return True
        return False

    _is_spanned = is_spanned  # compatibility

    def span_area(self) -> tuple[_int, _int]:
        """Return the dimensions of the area spanned by the cell.

        Returns a tuple `(nb_columns, nb_rows)` indicating how many columns
        and rows the cell spans. If the cell is not spanned, it returns
        `(0, 0)`.

        Returns:
            tuple[int, int]: A tuple containing the number of spanned columns
                and rows.
        """
        columns = self.get_attribute_integer("table:number-columns-spanned") or 0
        rows = self.get_attribute_integer("table:number-rows-spanned") or 0
        return (columns, rows)

_bool_string property

_bool_string: str

Return the boolean value as a string ‘0’ or ‘1’.

_is_spanned class-attribute instance-attribute

_is_spanned = is_spanned

_tag class-attribute instance-attribute

_tag = 'table:table-cell'

bool property writable

bool: _bool

Get or set the value of the cell as a boolean.

The style of the cell is kept, to clear completely the cell, use cell.clear().

When setting the value, force the cell type to “boolean”.

Warning

If modifying a repeated cell directly (“cell.repeated > 1”), changing its value will affect all repeated instances sharing this cell XML element node. To modify a single repeated cell without affecting others, use “Table.set_value()” or “Row.set_value()”.

clone property

clone: Cell

currency property writable

currency: str | None

Get or set the currency used for monetary values.

Warning

If modifying a repeated cell directly (“cell.repeated > 1”), changing its value will affect all repeated instances sharing this cell XML element node. To modify a single repeated cell without affecting others, use “Table.set_value()” or “Row.set_value()”.

Returns:

Type Description
str | None

str or None: The currency code (e.g., “EUR”, “USD”).

date property writable

date: date

Get or set the value of the cell as a date.

The style of the cell is kept, to clear completely the cell, use cell.clear().

When setting the value, force the cell type to “date”.

Warning

If modifying a repeated cell directly (“cell.repeated > 1”), changing its value will affect all repeated instances sharing this cell XML element node. To modify a single repeated cell without affecting others, use “Table.set_value()” or “Row.set_value()”.

datetime property writable

datetime: datetime

Get or set the value of the cell as a datetime.

The style of the cell is kept, to clear completely the cell, use cell.clear().

When setting the value, force the cell type to “date”.

Warning

If modifying a repeated cell directly (“cell.repeated > 1”), changing its value will affect all repeated instances sharing this cell XML element node. To modify a single repeated cell without affecting others, use “Table.set_value()” or “Row.set_value()”.

decimal property writable

decimal: Decimal

Get or set the value of the cell as a Decimal (or 0.0).

The style of the cell is kept, to clear completely the cell, use cell.clear().

When setting the value, force the cell type to “float”.

Warning

If modifying a repeated cell directly (“cell.repeated > 1”), changing its value will affect all repeated instances sharing this cell XML element node. To modify a single repeated cell without affecting others, use “Table.set_value()” or “Row.set_value()”.

duration property writable

duration: timedelta

Get or set the value of the cell as a duration (Python timedelta).

The style of the cell is kept, to clear completely the cell, use cell.clear().

When setting the value, force the cell type to “time”.

Warning

If modifying a repeated cell directly (“cell.repeated > 1”), changing its value will affect all repeated instances sharing this cell XML element node. To modify a single repeated cell without affecting others, use “Table.set_value()” or “Row.set_value()”.

float property writable

float: _float

Get or set the value of the cell as a float (or 0.0).

The style of the cell is kept, to clear completely the cell, use cell.clear().

When setting the value, force the cell type to “float”.

Warning

If modifying a repeated cell directly (“cell.repeated > 1”), changing its value will affect all repeated instances sharing this cell XML element node. To modify a single repeated cell without affecting others, use “Table.set_value()” or “Row.set_value()”.

formula property writable

formula: str | None

Get or set the formula of the cell.

The formula is stored as a string and is not interpreted by odfdo.

Returns:

Type Description
str | None

str or None: The formula string, or None if no formula is defined.

int property writable

int: _int

Get or set the value of the cell as an integer (or 0).

The style of the cell is kept, to clear completely the cell, use cell.clear().

When setting the value, force the cell type to “float”.

Warning

If modifying a repeated cell directly (“cell.repeated > 1”), changing its value will affect all repeated instances sharing this cell XML element node. To modify a single repeated cell without affecting others, use “Table.set_value()” or “Row.set_value()”.

repeated property writable

repeated: _int | None

Get or set the number of times the cell is repeated across columns.

This property is typically None when using the higher-level table API.

Returns:

Type Description
_int | None

int or None: The number of repetitions, or None if not repeated.

string property writable

string: str

Get or set the value of the cell as a string (or ‘’).

The style of the cell is kept, to clear completely the cell, use cell.clear().

When setting the value, force the cell type to “string”.

Warning

If modifying a repeated cell directly (“cell.repeated > 1”), changing its value will affect all repeated instances sharing this cell XML element node. To modify a single repeated cell without affecting others, use “Table.set_value()” or “Row.set_value()”.

style property writable

style: str | None

Get or set the style name of the cell.

Returns:

Type Description
str | None

str or None: The name of the style applied to the cell.

type property writable

type: str | None

Get or set the type of the cell.

Valid types include ‘boolean’, ‘float’, ‘date’, ‘string’, or ‘time’.

Returns:

Type Description
str | None

str or None: The type of the cell’s value.

value property writable

value: CellValue | None

Get or set the value of the cell.

When getting, the type is inferred from the ‘office:value-type’ attribute. When setting, the type of the provided Python value determines the ‘office:value-type’ of the cell. The style of the cell is kept, to clear completely the cell, use cell.clear().

Note: the cell style content is kepts when using “cell.value = None”. To ensure an absolute empty cell, use cell.clear() that will remove all componants (style, xml:id, …).

Warning
  • For date, datetime, and timedelta, a default text value is automatically generated.
  • For boolean types, the text value will be either ‘True’ or ‘False’.
  • For numeric types, the return value is typically Decimal or int. Use the float, decimal, or int properties to force a specific return type.
  • To customize the text representation, use the set_value() method.
  • To change the string representation of the cell without changing the cell type, use the low level property cell.text
  • If modifying a repeated cell directly (cell.repeated > 1), changing its value will affect all repeated instances sharing this cell XML element node. To modify a single repeated cell without affecting others, use Table.set_value() or Row.set_value().

Returns:

Type Description
CellValue | None

Union[str, bool, int, float, Decimal, date, datetime, timedelta, None]: The value of the cell in its appropriate Python type.

x instance-attribute

x: _int | None = None

y instance-attribute

y: _int | None = None

__init__

__init__(
    value: CellValue | None = None,
    text: str | None = None,
    cell_type: str | None = None,
    currency: str | None = None,
    formula: str | None = None,
    repeated: _int | None = None,
    style: str | None = None,
    **kwargs: Any,
) -> None

Create a cell element.

A cell in a table, represented by “table:table-cell”. This constructor creates a cell element containing the given value. The textual representation is automatically formatted but can be provided explicitly. The cell type can be deduced automatically, unless the number is a percentage or currency. If the cell type is “currency”, the currency must be specified. The cell can also be repeated across a given number of columns.

Parameters:

Name Type Description Default
value CellValue | None

The Python value to set for the cell. Can be a boolean, int, float, Decimal, date, datetime, str, timedelta or None.

None
text str | None

The textual representation of the cell’s content. If not provided, it is generated from the value.

None
cell_type str | None

The explicit type of the cell. Valid options include ‘boolean’, ‘currency’, ‘date’, ‘float’, ‘percentage’, ‘string’, or ‘time’. If not provided, it’s guessed from the value.

None
currency str | None

A three-letter currency code (e.g., “EUR”, “USD”) if the cell_type is ‘currency’.

None
formula str | None

The formula for the cell.

None
repeated _int | None

The number of times this cell should be repeated across columns. Must be greater than 1.

None
style str | None

The name of the style to apply to the cell.

None
Source code in odfdo/cell.py
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def __init__(
    self,
    value: CellValue | None = None,
    text: str | None = None,
    cell_type: str | None = None,
    currency: str | None = None,
    formula: str | None = None,
    repeated: _int | None = None,
    style: str | None = None,
    **kwargs: Any,
) -> None:
    """Create a cell element.

    A cell in a table, represented by "table:table-cell".
    This constructor creates a cell element containing the given value.
    The textual representation is automatically formatted but can be
    provided explicitly. The cell type can be deduced automatically,
    unless the number is a percentage or currency. If the cell type is
    "currency", the currency must be specified. The cell can also be
    repeated across a given number of columns.

    Args:
        value: The Python value to set for the cell. Can be a boolean,
            int, float, Decimal, date, datetime, str, timedelta or None.
        text: The textual representation of the cell's content. If not
            provided, it is generated from the value.
        cell_type: The explicit type of the cell. Valid options include
            'boolean', 'currency', 'date', 'float', 'percentage',
            'string', or 'time'. If not provided, it's guessed from the
            value.
        currency: A three-letter currency code (e.g., "EUR", "USD") if
            the cell_type is 'currency'.
        formula: The formula for the cell.
        repeated: The number of times this cell should be repeated across
            columns. Must be greater than 1.
        style: The name of the style to apply to the cell.
    """
    super().__init__(**kwargs)
    self.x: _int | None = None
    self.y: _int | None = None
    if self._do_init:
        self.set_value(
            value,
            text=text,
            cell_type=cell_type,
            currency=currency,
            formula=formula,
        )
        if repeated and repeated > 1:
            self.repeated = repeated
        if style is not None:
            self.style = style

__repr__

__repr__() -> str
Source code in odfdo/cell.py
111
112
def __repr__(self) -> str:
    return f"<{self.__class__.__name__} x={self.x} y={self.y}>"

_set_float_value_str

_set_float_value_str(value_str: str) -> None
Source code in odfdo/cell.py
294
295
296
297
298
299
300
301
302
303
def _set_float_value_str(self, value_str: str) -> None:
    if self.type != "float":
        # remove attributes that can exist from a previous different cell
        # type.
        # Note: the Cell may also contains non standanrd attributes (ooo)
        # or sub elements (test:p, ...)
        self.clear_attrinutes()
        self.set_attribute("office:value-type", "float")
    self.set_attribute("office:value", value_str)
    self.set_text_content(value_str)

_set_repeated

_set_repeated(repeated: _int | None) -> None

Set the number of times the cell is repeated (internal).

Internal method that sets the ‘table:number-columns-repeated’ attribute, or removes it if repeated is None or less than 2, without triggering cache updates.

Parameters:

Name Type Description Default
repeated _int | None

The number of times the cell should be repeated. If None or less than 2, the attribute is removed.

required
Source code in odfdo/cell.py
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
def _set_repeated(self, repeated: _int | None) -> None:
    """Set the number of times the cell is repeated (internal).

    Internal method that sets the 'table:number-columns-repeated'
    attribute, or removes it if `repeated` is None or less than 2,
    without triggering cache updates.

    Args:
        repeated: The number of times the cell should be repeated. If
            None or less than 2, the attribute is removed.
    """
    if repeated is None or repeated < 2:
        with contextlib.suppress(KeyError):
            self.del_attribute("table:number-columns-repeated")
        return
    self.set_attribute("table:number-columns-repeated", str(repeated))

is_covered

is_covered() -> _bool

Check if the cell is covered.

A covered cell is represented by the “table:covered-table-cell” tag.

Returns:

Name Type Description
bool _bool

True if the cell is covered, False otherwise.

Source code in odfdo/cell.py
771
772
773
774
775
776
777
778
779
def is_covered(self) -> _bool:
    """Check if the cell is covered.

    A covered cell is represented by the "table:covered-table-cell" tag.

    Returns:
        bool: True if the cell is covered, False otherwise.
    """
    return self.tag == "table:covered-table-cell"

is_empty

is_empty(aggressive: _bool = False) -> _bool

Check if the cell is empty.

An empty cell has no value, no children, is not covered, and is not spanned. By default, cells with a style are not considered empty.

Parameters:

Name Type Description Default
aggressive _bool

If True, a cell with a style but no content is also considered empty. Defaults to False.

False

Returns:

Name Type Description
bool _bool

True if the cell is empty, False otherwise.

Source code in odfdo/cell.py
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
def is_empty(self, aggressive: _bool = False) -> _bool:
    """Check if the cell is empty.

    An empty cell has no value, no children, is not covered, and is not
    spanned. By default, cells with a style are not considered empty.

    Args:
        aggressive: If True, a cell with a style but no content is also
            considered empty. Defaults to False.

    Returns:
        bool: True if the cell is empty, False otherwise.
    """
    if (
        self.value is not None
        or self.children
        or self.is_covered()
        or self.is_spanned()
    ):
        return False
    if not aggressive and self.style is not None:  # noqa: SIM103
        return False
    return True

is_spanned

is_spanned(covered: _bool = True) -> _bool

Check if the cell spans over multiple cells.

A cell is considered spanned if it has ‘table:number-columns-spanned’ or ‘table:number-rows-spanned’ attributes.

Parameters:

Name Type Description Default
covered _bool

If True, covered cells (those with the “table:covered-table-cell” tag) are also considered spanned. Defaults to True.

True

Returns:

Name Type Description
bool _bool

True if the cell is spanned, False otherwise.

Source code in odfdo/cell.py
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
def is_spanned(self, covered: _bool = True) -> _bool:
    """Check if the cell spans over multiple cells.

    A cell is considered spanned if it has 'table:number-columns-spanned'
    or 'table:number-rows-spanned' attributes.

    Args:
        covered: If True, covered cells (those with the
            "table:covered-table-cell" tag) are also considered spanned.
            Defaults to True.

    Returns:
        bool: True if the cell is spanned, False otherwise.
    """
    if self.is_covered():
        return covered
    if self.get_attribute("table:number-columns-spanned") is not None:
        return True
    if self.get_attribute("table:number-rows-spanned") is not None:  # noqa: SIM103
        return True
    return False

set_value

set_value(
    value: CellValue | None,
    text: str | None = None,
    cell_type: str | None = None,
    currency: str | None = None,
    formula: str | None = None,
) -> None

Set the cell state from a Python value.

The text parameter defines how the cell is displayed. The cell type is guessed unless explicitly provided. For monetary values, the name of the currency must be provided.

The style of the cell is kept, to clear completely the cell, use cell.clear().

Warning

If modifying a repeated cell directly (“cell.repeated > 1”), changing its value will affect all repeated instances sharing this cell XML element node. To modify a single repeated cell without affecting others, use “Table.set_value()” or “Row.set_value()”.

Parameters:

Name Type Description Default
value CellValue | None

The Python value to assign to the cell.

required
text str | None

The explicit textual representation of the cell’s content. If None, it is derived from the value.

None
cell_type str | None

The explicit type of the cell’s value. Can be ‘boolean’, ‘float’, ‘date’, ‘string’, ‘time’, ‘currency’, or ‘percentage’.

None
currency str | None

A string representing the currency, e.g., “EUR” or “USD”, required if cell_type is ‘currency’.

None
formula str | None

The formula to set for the cell.

None
Source code in odfdo/cell.py
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
def set_value(
    self,
    value: CellValue | None,
    text: str | None = None,
    cell_type: str | None = None,
    currency: str | None = None,
    formula: str | None = None,
) -> None:
    """Set the cell state from a Python value.

    The `text` parameter defines how the cell is displayed.
    The cell type is guessed unless explicitly provided.
    For monetary values, the name of the currency must be provided.

    The style of the cell is kept, to clear completely the cell, use
    cell.clear().

    Warning:
        If modifying a repeated cell directly ("cell.repeated > 1"),
        changing its value will affect all repeated instances sharing
        this cell XML element node. To modify a single repeated cell
        without affecting others, use "Table.set_value()" or
        "Row.set_value()".

    Args:
        value:
            The Python value to assign to the cell.
        text: The explicit textual representation of the cell's content.
            If None, it is derived from the `value`.
        cell_type: The explicit type of the cell's value. Can be
            'boolean', 'float', 'date', 'string', 'time', 'currency', or
            'percentage'.
        currency: A string representing the currency, e.g., "EUR" or
            "USD", required if `cell_type` is 'currency'.
        formula: The formula to set for the cell.
    """
    text = self.set_value_and_type(
        value=value,
        text=text,
        value_type=cell_type,
        currency=currency,
    )
    if text is not None:
        self.text_content = text
    if formula is not None:
        self.formula = formula

span_area

span_area() -> tuple[_int, _int]

Return the dimensions of the area spanned by the cell.

Returns a tuple (nb_columns, nb_rows) indicating how many columns and rows the cell spans. If the cell is not spanned, it returns (0, 0).

Returns:

Type Description
tuple[_int, _int]

tuple[int, int]: A tuple containing the number of spanned columns and rows.

Source code in odfdo/cell.py
805
806
807
808
809
810
811
812
813
814
815
816
817
818
def span_area(self) -> tuple[_int, _int]:
    """Return the dimensions of the area spanned by the cell.

    Returns a tuple `(nb_columns, nb_rows)` indicating how many columns
    and rows the cell spans. If the cell is not spanned, it returns
    `(0, 0)`.

    Returns:
        tuple[int, int]: A tuple containing the number of spanned columns
            and rows.
    """
    columns = self.get_attribute_integer("table:number-columns-spanned") or 0
    rows = self.get_attribute_integer("table:number-rows-spanned") or 0
    return (columns, rows)