Skip to content

Table

Table class for “table:table” tag.

Classes:

Name Description
Table

A table, typically used in a spreadsheet or other ODF document, represented by “table:table”.

Functions:

Name Description
import_from_csv

Import a CSV file or file-like object into a new Table.

Attributes:

Name Type Description
BODY_NR_TAGS

BODY_NR_TAGS module-attribute

BODY_NR_TAGS = BODY_ALLOW_NAMED_RANGE_TAGS

_XP_COLUMN module-attribute

_XP_COLUMN = xpath_compile(
    "table:table-column|table:table-columns/table:table-column|table:table-header-columns/table:table-column"
)

_XP_ROW module-attribute

_XP_ROW = xpath_compile(
    "table:table-row|table:table-rows/table:table-row|table:table-header-rows/table:table-row|table:table-row-group/child::table:table-row"
)

_XP_ROW_GROUP module-attribute

_XP_ROW_GROUP = xpath_compile(
    "table:table-row-group|table:table-row-group/child::table:table-row-group"
)

Table

Bases: MDTable, FormMixin, OfficeFormsMixin, Element

A table, typically used in a spreadsheet or other ODF document, represented by “table:table”.

This class provides a comprehensive API for managing table structures, including cells, rows, and columns, along with their properties and content.

Methods:

Name Description
__init__

Initializes a Table element.

__str__
append

Append a Row or Column to the table.

append_cell

Append a cell to the end of the row at the given ‘y’ coordinate.

append_column

Append a column to the end of the table.

append_named_range

Append a named range to the document, replacing any existing one with the same name.

append_row

Append a row to the end of the table.

clear

Remove all children, text content, and attributes from the table element.

del_span

Delete a cell span.

delete_cell

Delete the cell at the given coordinates, shifting subsequent cells to the left.

delete_column

Delete the column at the given position.

delete_named_range

Delete the named range with the specified name.

delete_row

Delete the row at the given ‘y’ position (0-based).

extend_rows

Append a list of rows to the end of the table.

from_csv

Import a CSV string into a new Table object.

get_cell

Get the cell at the given coordinates (e.g., (0, 2) or “C1”).

get_cells

Get a list of cells, optionally from a specified area and filtered by criteria.

get_column

Get the column at the given ‘x’ position (0-based or alphabetical).

get_column_cells

Get a list of cells from the column at the given ‘x’ position.

get_column_values

Get the list of Python values for the cells in the column at the given ‘x’ position.

get_columns

Get a list of columns matching the specified criteria.

get_elements

Get a list of elements matching the XPath query.

get_formatted_text

Return a formatted text representation of the table.

get_named_range

Return the named range with the specified name.

get_named_ranges

Return a list of named ranges, optionally filtered by scope and table name.

get_row

Get the row at the given ‘y’ position (0-based).

get_row_sub_elements

Get the list of Element values for the cells of the row at the given ‘y’ position.

get_row_values

Get the list of Python values for the cells of the row at the given ‘y’ position.

get_rows

Get a list of rows matching the specified criteria.

get_value

Get the Python value of the cell at the given coordinates.

get_values

Get a matrix of values from the table, optionally from a specified area.

insert_cell

Insert a cell at the given coordinates, shifting existing cells to the right.

insert_column

Insert a column before the given ‘x’ position.

insert_row

Insert a row before the given ‘y’ position (0-based).

is_column_empty

Return True if every cell in the column at the ‘x’ position is empty.

is_empty

Return True if every cell in the table is empty.

is_row_empty

Return True if every cell in the row at the given ‘y’ position is empty.

iter_columns

Yield column elements, expanding repetitions.

iter_rows

Yield row elements, expanding repetitions.

iter_values

Yield lists of values of rows.

optimize_width

Remove empty rows and right-side empty cells in-place.

rstrip

Remove empty rows and right-side empty cells from the table in-place.

set_cell

Replace the cell at the given coordinates.

set_cell_image

Deprecated. Use recipes to insert an image in a cell.

set_cells

Set a matrix of cells in the table, starting from a specified coordinate.

set_column

Replace the column at the given ‘x’ position.

set_column_cells

Set the list of cells for the column at the given ‘x’ position.

set_column_values

Set the list of Python values for the cells in the column at the given ‘x’ position.

set_named_range

Create and insert a named range, replacing any existing one with the same name.

set_row

Replace the row at the given position with a new one.

set_row_cells

Set all the cells of the row at the given ‘y’ position.

set_row_values

Set the values of all cells in the row at the given ‘y’ position.

set_span

Create a cell span, spanning the first cell of the area over columns and/or rows.

set_value

Set the Python value of the cell at the given coordinates.

set_values

Set cell values in the table, starting from a specified coordinate.

to_csv

Export the table as a CSV string or file.

transpose

Swap rows and columns of the table in-place.

Attributes:

Name Type Description
cells list

Get all cells of the table as a list of lists.

columns list[Column]

Get a list of all columns in the table.

height int

Get the current height of the table.

name str | None

Get or set the name of the table.

print_ranges list[str]

Get or set the print ranges for the table.

printable bool

Get or set the printable status of the table.

protected bool

Get or set the protected status of the table.

protection_key str | None

Get or set the protection key for the table.

row_groups list[RowGroup]

Get the list of all RowGroup elements in the table.

rows list[Row]

Get a list of all rows in the table.

size tuple[int, int]

Get the current width and height of the table.

style str | None

Get or set the style name of the table.

traverse
traverse_columns
width int

Get the current width of the table, based on the column definitions.

Source code in odfdo/table.py
 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
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
class Table(MDTable, FormMixin, OfficeFormsMixin, Element):
    """A table, typically used in a spreadsheet or other ODF document, represented by "table:table".

    This class provides a comprehensive API for managing table structures,
    including cells, rows, and columns, along with their properties and content.
    """

    _tag = "table:table"
    _append = Element.append

    def __init__(
        self,
        name: str | None = None,
        width: int | str | None = None,
        height: int | str | None = None,
        protected: bool = False,
        protection_key: str | None = None,
        printable: bool = True,
        print_ranges: list[str] | None = None,
        style: str | None = None,
        **kwargs: Any,
    ) -> None:
        """Initializes a Table element.

        The table can optionally be pre-filled with a specified number of rows
        and cells.

        Args:
            name: The name of the table. It is required and
                cannot contain specific characters like `[]*?:/\\`.
                Apostrophes are also forbidden as the first or last character.
            width: The initial number of columns for the table.
            height: The initial number of rows for the table.
            protected: If True, the table is protected. A `protection_key`
                must be provided if this is True.
            protection_key: A hash value of the password for
                table protection.
            printable: If False, the table will not be printed. Defaults to True.
            print_ranges: A list of cell ranges
                (e.g., `['E6:K12', 'P6:R12']`) or a raw string specifying the
                print ranges.
            style: The name of the style to apply to the table.
            **kwargs: Additional keyword arguments for the Element base class.

        Raises:
            ValueError: If `protected` is True but `protection_key` is not provided.

        Note:
            Directly manipulating the XML tree while using the table API may lead
            to inconsistencies.
        """
        super().__init__(**kwargs)
        self._table_cache = TableCache()
        if self._do_init:
            self.name = name or ""
            if protected:
                self.protected = protected
                if protection_key is None:
                    raise ValueError(
                        "a protection_key must be provided for protected tables"
                    )
                self.protection_key = protection_key
            if not printable:
                self.printable = printable
            if print_ranges:
                self.print_ranges = print_ranges
            if style:
                self.style = style
            # Prefill the table
            if width is not None or height is not None:
                width = int(width or 1)
                height = int(height or 1)
                # Column groups for style information
                columns = Column(repeated=width)
                self._append(columns)
                for _i in range(height):
                    row = Row(width)
                    self._append(row)
        self._compute_table_cache()

    def __str__(self) -> str:
        def write_content(csv_writer: object) -> None:
            for values in self.iter_values():
                line = []
                for value in values:
                    if value is None:
                        value = ""
                    if isinstance(value, str):
                        value = value.strip()
                    line.append(value)
                csv_writer.writerow(line)  # type: ignore[attr-defined]

        out = StringIO(newline=os.linesep)
        csv_writer = csv.writer(
            out,
            delimiter=" ",
            doublequote=False,
            escapechar="\\",
            lineterminator=os.linesep,
            quotechar='"',
            quoting=csv.QUOTE_NONNUMERIC,
        )
        write_content(csv_writer)
        return out.getvalue()

    def get_elements(self, xpath_query: XPath | str) -> list[Element]:
        """Get a list of elements matching the XPath query.

        The query is applied to the current table element.

        Args:
            xpath_query: The XPath query string or a compiled
                XPath object.

        Returns:
            list[Element]: A list of matching elements, cloned from the
                original XML tree.
        """
        if isinstance(xpath_query, str):
            elements = xpath_return_elements(
                xpath_compile(xpath_query),
                self._xml_element,
            )
        else:
            elements = xpath_return_elements(
                xpath_query,
                self._xml_element,
            )
        cache = (self._table_cache, None)
        return [Element.from_tag_for_clone(e, cache) for e in elements]

    def clear(self) -> None:
        """Remove all children, text content, and attributes from the table element."""
        self._xml_element.clear()
        self._table_cache = TableCache()

    def _translate_y_from_any(self, y: str | int) -> int:
        """Translate a 'y' coordinate from any format to a 0-based integer index.

        Args:
            y: The Y-coordinate, which can be a 1-based integer or a string.

        Returns:
            int: The 0-based integer Y-coordinate.
        """
        # "3" (counting from 1) -> 2 (counting from 0)
        return translate_from_any(y, self.height, 1)

    def _translate_table_coordinates_list(
        self,
        coord: tuple | list,
    ) -> tuple[int | None, ...]:
        height = self.height
        width = self.width
        # assuming we got int values
        if len(coord) == 1:
            # It is a row
            y = coord[0]
            if y and y < 0:
                y = increment(y, height)
            return (None, y, None, y)
        if len(coord) == 2:
            # It is a row range, not a cell, because context is table
            y = coord[0]
            if y and y < 0:
                y = increment(y, height)
            t = coord[1]
            if t and t < 0:
                t = increment(t, height)
            return (None, y, None, t)
        # should be 4 int
        x, y, z, t = coord
        if x and x < 0:
            x = increment(x, width)
        if y and y < 0:
            y = increment(y, height)
        if z and z < 0:
            z = increment(z, width)
        if t and t < 0:
            t = increment(t, height)
        return (x, y, z, t)

    def _translate_table_coordinates_str(
        self,
        coord_str: str,
    ) -> tuple[int | None, ...]:
        coord = convert_coordinates(coord_str)
        # resulting coord has never <0 value
        if len(coord) == 2:
            x, y = coord
            # extent to an area :
            return (x, y, x, y)
        x, y, z, t = coord
        return (x, y, z, t)

    def _translate_table_coordinates(
        self,
        coord: tuple | list | str,
    ) -> tuple[int | None, ...]:
        if isinstance(coord, str):
            return self._translate_table_coordinates_str(coord)
        return self._translate_table_coordinates_list(coord)

    def _translate_column_coordinates_str(
        self,
        coord_str: str,
    ) -> tuple[int | None, ...]:
        coord = convert_coordinates(coord_str)
        # resulting coord has never <0 value
        if len(coord) == 2:
            x, y = coord
            # extent to an area :
            return (x, y, x, y)
        x, y, z, t = coord
        return (x, y, z, t)

    def _translate_column_coordinates_list(
        self,
        coord: tuple | list,
    ) -> tuple[int | None, ...]:
        width = self.width
        height = self.height
        # assuming we got int values
        if len(coord) == 1:
            # It is a column
            x = coord[0]
            if x and x < 0:
                x = increment(x, width)
            return (x, None, x, None)
        if len(coord) == 2:
            # It is a column range, not a cell, because context is table
            x = coord[0]
            if x and x < 0:
                x = increment(x, width)
            z = coord[1]
            if z and z < 0:
                z = increment(z, width)
            return (x, None, z, None)
        # should be 4 int
        x, y, z, t = coord
        if x and x < 0:
            x = increment(x, width)
        if y and y < 0:
            y = increment(y, height)
        if z and z < 0:
            z = increment(z, width)
        if t and t < 0:
            t = increment(t, height)
        return (x, y, z, t)

    def _translate_column_coordinates(
        self,
        coord: tuple | list | str,
    ) -> tuple[int | None, ...]:
        if isinstance(coord, str):
            return self._translate_column_coordinates_str(coord)
        return self._translate_column_coordinates_list(coord)

    def _translate_cell_coordinates(
        self,
        coord: tuple | list | str,
    ) -> tuple[int | None, int | None]:
        # we want an x,y result
        coord = convert_coordinates(coord)
        if len(coord) == 2:
            x, y = coord
        # If we got an area, take the first cell
        elif len(coord) == 4:
            x, y, _z, _t = coord
        else:
            raise ValueError(str(coord))
        if x and x < 0:
            x = increment(x, self.width)
        if y and y < 0:
            y = increment(y, self.height)
        return (x, y)

    def _compute_table_cache(self) -> None:
        idx_repeated_seq = self.elements_repeated_sequence(
            _XP_ROW, "table:number-rows-repeated"
        )
        self._table_cache.make_row_map(idx_repeated_seq)
        idx_repeated_seq = self.elements_repeated_sequence(
            _XP_COLUMN, "table:number-columns-repeated"
        )
        self._table_cache.make_col_map(idx_repeated_seq)

    def _update_width(self, row: Row) -> None:
        """Synchronize the number of columns if the row is bigger.

        Append, don't insert, not to disturb the current layout.
        """
        diff = row.width - self.width
        if diff > 0:
            self.append_column(Column(repeated=diff))

    def _get_formatted_text_normal(self, context: dict | None) -> str:
        result = []
        for row in self.iter_rows():
            for cell in row.iter_cells():
                value = cell.get_value(try_get_text=False)
                # None ?
                if value is None:
                    # Try with get_formatted_text on the elements
                    value = []
                    for element in cell.children:
                        value.append(element.get_formatted_text(context))
                    value = "".join(value)
                else:
                    value = str(value)
                result.append(value)
                result.append("\n")
            result.append("\n")
        return "".join(result)

    def _get_formatted_text_rst(self, context: dict) -> str:
        context["no_img_level"] += 1
        # Strip the table => We must clone
        table: Table = self.clone  # type: ignore[assignment]
        table.rstrip(aggressive=True)

        # Fill the rows
        rows = []
        cols_nb = 0
        cols_size: dict[int, int] = {}
        for odf_row in table.iter_rows():
            row = []
            for i, cell in enumerate(odf_row.iter_cells()):
                value = cell.get_value(try_get_text=False)
                # None ?
                if value is None:
                    # Try with get_formatted_text on the elements
                    value = []
                    for element in cell.children:
                        value.append(element.get_formatted_text(context))
                    value = "".join(value)
                else:
                    value = str(value)
                value = value.strip()
                # Strip the empty columns
                if value:
                    cols_nb = max(cols_nb, i + 1)
                # Compute the size of each columns (at least 2)
                cols_size[i] = max(cols_size.get(i, 2), len(value))
                # Append
                row.append(value)
            rows.append(row)

        # Nothing ?
        if cols_nb == 0:
            return ""

        # Prevent a crash with empty columns (by example with images)
        for col, size in cols_size.items():
            if size == 0:
                cols_size[col] = 1

        # Update cols_size
        LINE_MAX = 100
        COL_MIN = 16

        free_size = LINE_MAX - (cols_nb - 1) * 3 - 4
        real_size = sum(cols_size[i] for i in range(cols_nb))
        if real_size > free_size:
            factor = float(free_size) / real_size

            for i in range(cols_nb):
                old_size = cols_size[i]

                # The cell is already small
                if old_size <= COL_MIN:
                    continue

                new_size = int(factor * old_size)

                if new_size < COL_MIN:
                    new_size = COL_MIN
                cols_size[i] = new_size

        # Convert !
        result: list[str] = [""]
        # Construct the first/last line
        line: list[str] = []
        for i in range(cols_nb):
            line.append("=" * cols_size[i])
            line.append(" ")
        line_str = "".join(line)

        # Add the lines
        result.append(line_str)
        for row in rows:
            # Wrap the row
            wrapped_row = []
            for i, value in enumerate(row[:cols_nb]):
                wrapped_value = []
                for part in value.split("\n"):
                    # Hack to handle correctly the lists or the directives
                    subsequent_indent = ""
                    part_lstripped = part.lstrip()
                    if part_lstripped.startswith("-") or part_lstripped.startswith(
                        ".."
                    ):
                        subsequent_indent = " " * (len(part) - len(part.lstrip()) + 2)
                    wrapped_part = wrap(
                        part, width=cols_size[i], subsequent_indent=subsequent_indent
                    )
                    if wrapped_part:
                        wrapped_value.extend(wrapped_part)
                    else:
                        wrapped_value.append("")
                wrapped_row.append(wrapped_value)

            # Append!
            for j in range(max([1] + [len(values) for values in wrapped_row])):
                txt_row: list[str] = []
                for i in range(cols_nb):
                    values = wrapped_row[i] if i < len(wrapped_row) else []

                    # An empty cell ?
                    if len(values) - 1 < j or not values[j]:
                        if i == 0 and j == 0:
                            txt_row.append("..")
                            txt_row.append(" " * (cols_size[i] - 1))
                        else:
                            txt_row.append(" " * (cols_size[i] + 1))
                        continue

                    # Not empty
                    value = values[j]
                    txt_row.append(value)
                    txt_row.append(" " * (cols_size[i] - len(value) + 1))
                result.append("".join(txt_row))

        result.append(line_str)
        result.append("")
        result.append("")
        result_str = "\n".join(result)

        context["no_img_level"] -= 1
        return result_str

    def _translate_x_from_any(self, x: str | int) -> int:
        return translate_from_any(x, self.width, 0)

    #
    # Public API
    #

    def append(self, something: Element | str) -> None:
        """Append a Row or Column to the table.

        This method dispatches the call to `append_row` or `append_column` based
        on the type of the provided element.

        Args:
            something (Element | str): The Row or Column to append.
        """
        if isinstance(something, Row):
            self.append_row(something)
        elif isinstance(something, Column):
            self.append_column(something)
        else:
            # probably still an error
            self._append(something)

    @property
    def height(self) -> int:
        """Get the current height of the table.

        Returns:
            The number of rows in the table.
        """
        return self._table_cache.height()

    @property
    def width(self) -> int:
        """Get the current width of the table, based on the column definitions.

        Note that individual rows may have different widths. It is recommended to
        use the Table API to maintain a consistent width.

        Returns:
            int: The number of columns in the table.
        """
        # Columns are our reference for user expected width
        return self._table_cache.width()

    @property
    def size(self) -> tuple[int, int]:
        """Get the current width and height of the table.

        Returns:
            A tuple containing the (width, height) of the table.
        """
        return self.width, self.height

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

        The name is required and cannot contain `[]*?:/` or `\\` characters.
        Apostrophes (`'`) are not allowed as the first or last character.
        """
        return self.get_attribute_string("table:name")

    @name.setter
    def name(self, name: str | None) -> None:
        name = table_name_check(name)
        # first, update named ranges
        # fixme : delete name ranges when deleting table, too.
        for named_range in self.get_named_ranges(table_name=self.name):
            named_range.set_table_name(name)
        self.set_attribute("table:name", name)

    @property
    def protected(self) -> bool:
        """Get or set the protected status of the table.

        Returns:
            bool: True if the table is protected, False otherwise.
        """
        return cast(bool, self.get_attribute("table:protected"))

    @protected.setter
    def protected(self, protect: bool) -> None:
        self.set_attribute("table:protected", protect)

    @property
    def protection_key(self) -> str | None:
        """Get or set the protection key for the table.

        Returns:
            str | None: The protection key (a hash value) as a string, or None
                if not set.
        """
        return cast(None | str, self.get_attribute("table:protection-key"))

    @protection_key.setter
    def protection_key(self, key: str) -> None:
        self.set_attribute("table:protection-key", key)

    @property
    def printable(self) -> bool:
        """Get or set the printable status of the table.

        Returns:
            bool: True if the table is printable, False otherwise.
        """
        return self._get_attribute_bool_default("table:print", True)

    @printable.setter
    def printable(self, printable: bool) -> None:
        self._set_attribute_bool_default("table:print", printable, True)

    @property
    def print_ranges(self) -> list[str]:
        """Get or set the print ranges for the table.

        Returns:
            list[str]: A list of strings representing the print ranges
                (e.g., ['A1:C5', 'E1:G5']).
        """
        print_ranges = cast(None | str, self.get_attribute("table:print-ranges"))
        if print_ranges is None:
            return []
        return print_ranges.split()

    @print_ranges.setter
    def print_ranges(self, ranges: list[str] | None) -> None:
        if isinstance(ranges, (list, tuple)):
            self.set_attribute("table:print-ranges", " ".join(ranges))
        else:
            self.set_attribute("table:print-ranges", ranges)

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

        Returns:
            str | None: The name of the style as a string, or None if not set.
        """
        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)

    def get_formatted_text(self, context: dict | None = None) -> str:
        """Return a formatted text representation of the table.

        If the `context` dictionary contains 'rst_mode': True, the table will
        be formatted as a reStructuredText grid table. Otherwise, it returns
        a simple string with cell values.

        Args:
            context: A dictionary of context variables for formatting.

        Returns:
            str: The formatted text content of the table.
        """
        if not context:
            context = {}
        if context.get("rst_mode"):
            return self._get_formatted_text_rst(context)
        return self._get_formatted_text_normal(context)

    def get_values(
        self,
        coord: tuple | list | str | None = None,
        cell_type: str | None = None,
        complete: bool = True,
        get_type: bool = False,
        flat: bool = False,
    ) -> list:
        """Get a matrix of values from the table, optionally from a specified area.

        Args:
            coord: The coordinates of the area
                to parse (e.g., "A1:C3" or (0, 0, 2, 2)). If None, the entire
                table is parsed.
            cell_type: Filters cells by their value type
                (e.g., 'boolean', 'float', 'string'). 'all' retrieves any
                non-empty cell.
            complete: If True (default), missing values in the specified
                area are replaced by None to ensure a complete matrix.
            get_type: If True, returns tuples of (value, odf_type). For
                empty cells with `complete=True`, this will be (None, None).
            flat: If True, returns a single flat list of values instead
                of a list of lists. Defaults to False.

        Returns:
            list: A list of lists of Python types representing cell values,
                or a flat list if `flat` is True.
        """
        if coord:
            x, y, z, t = self._translate_table_coordinates(coord)
        else:
            x = y = z = t = None
        data = []
        for row in self.iter_rows(start=y, end=t):
            if z is None:
                width = self.width
            else:
                width = min(z + 1, self.width)
            if x is not None:
                width -= x
            values = row.get_values(
                (x, z),
                cell_type=cell_type,
                complete=complete,
                get_type=get_type,
            )
            # complete row to match request width
            if complete:
                if get_type:
                    values.extend([(None, None)] * (width - len(values)))
                else:
                    values.extend([None] * (width - len(values)))
            if flat:
                data.extend(values)
            else:
                data.append(values)
        return data

    def iter_values(
        self,
        coord: tuple | list | str | None = None,
        cell_type: str | None = None,
        complete: bool = True,
        get_type: bool = False,
    ) -> Iterator[list]:
        """Yield lists of values of rows.

        Each yielded list contains the python values ot the cells of the row.

        Args:
            coord: The coordinates of the area to parse.
            cell_type: Filters cells by value type (e.g., 'float'). 'all'
                retrieves any non-empty cell. See `get_values` for more.
            complete: If True, missing values are replaced by None.
            get_type: If True, yields tuples of (value, odf_type).

        Yields:
            list: An iterator where each item is a list representing a row of
            cell values.
        """
        if coord:
            x, y, z, t = self._translate_table_coordinates(coord)
        else:
            x = y = z = t = None
        for row in self.iter_rows(start=y, end=t):
            if z is None:
                width = self.width
            else:
                width = min(z + 1, self.width)
            if x is not None:
                width -= x
            values = row.get_values(
                (x, z),
                cell_type=cell_type,
                complete=complete,
                get_type=get_type,
            )
            # complete row to match column width
            if complete:
                if get_type:
                    values.extend([(None, None)] * (width - len(values)))
                else:
                    values.extend([None] * (width - len(values)))
            yield values

    def set_values(
        self,
        values: list,
        coord: tuple | list | str | None = None,
        style: str | None = None,
        cell_type: str | None = None,
        currency: str | None = None,
    ) -> None:
        """Set cell values in the table, starting from a specified coordinate.

        The table is not cleared before this operation. To reset the table, call
        `table.clear()` first. The input `values` should be a list of lists,
        where each inner list represents a row.

        Args:
            values: A list of lists of Python types to set.
            coord: The coordinate of the top-left
                cell where values should be set (e.g., "A1" or (0, 0)).
                Defaults to "A1".
            style: The name of a cell style to apply.
            cell_type: The value type for the cells (e.g., 'float').
            currency: A three-letter currency code (e.g., 'USD').
        """
        if coord:
            x, y = self._translate_cell_coordinates(coord)
        else:
            x = y = 0
        if y is None:
            y = 0
        if x is None:
            x = 0
        y -= 1
        for row_values in values:
            y += 1
            if not row_values:
                continue
            row = self.get_row(y, clone=True)
            repeated = row.repeated or 1
            if repeated >= 2:
                row.repeated = None
            row.set_values(
                row_values,
                start=x,
                cell_type=cell_type,
                currency=currency,
                style=style,
            )
            self.set_row(y, row, clone=False)
            self._update_width(row)

    def rstrip(self, aggressive: bool = False) -> None:
        """Remove empty rows and right-side empty cells from the table in-place.

        A cell is considered empty if it has no value (or a value that evaluates
        to False) and no style.

        Args:
            aggressive: If True, empty cells with styles are also
                considered empty and will be removed.
        """
        # Step 1: remove empty rows below the table
        for row in reversed(self._get_rows()):
            if row.is_empty(aggressive=aggressive):
                row.parent.delete(row)  # type: ignore[union-attr]
            else:
                break
        # Step 2: rstrip remaining rows
        max_width = 0
        for row in self._get_rows():
            row.rstrip(aggressive=aggressive)
            # keep count of the biggest row
            max_width = max(max_width, row.width)
        # raz cache of rows
        self._table_cache.clear_row_indexes()
        # Step 3: trim columns to match max_width
        columns = self._get_columns()
        repeated_cols: list[EText] = cast(
            list[EText], self.xpath("table:table-column/@table:number-columns-repeated")
        )
        unrepeated = len(columns) - len(repeated_cols)
        column_width = sum(int(r) for r in repeated_cols) + unrepeated
        diff = column_width - max_width
        if diff > 0:
            for column in reversed(columns):  # pragma: nocover
                repeated = column.repeated or 1
                repeated = repeated - diff
                if repeated > 0:
                    column.repeated = repeated
                    break
                else:
                    column.parent.delete(column)  # type: ignore[union-attr]
                    diff = -repeated
                    if diff == 0:
                        break
        # raz cache of columns
        self._table_cache.clear_col_indexes()
        self._compute_table_cache()

    def optimize_width(self) -> None:
        """Remove empty rows and right-side empty cells in-place.

        This method keeps the repeated styles of empty cells but minimizes the
        row width to fit the actual content.
        """
        self._optimize_width_trim_rows()
        width = self._optimize_width_length()
        self._optimize_width_rstrip_rows(width)
        self._optimize_width_adapt_columns(width)

    def _optimize_width_trim_rows(self) -> None:
        count = -1  # to keep one empty row
        for row in reversed(self._get_rows()):
            if row.is_empty(aggressive=False):
                count += 1
            else:
                break
        if count > 0:
            for row in reversed(self._get_rows()):  # pragma: nocover
                row.parent.delete(row)  # type: ignore[union-attr]
                count -= 1
                if count <= 0:
                    break
        try:
            last_row = self._get_rows()[-1]
            last_row._set_repeated(None)
        except IndexError:
            pass
        # raz cache of rows
        self._table_cache.clear_row_indexes()

    def _optimize_width_length(self) -> int:
        try:
            return max(row.minimized_width() for row in self._get_rows())
        except ValueError:
            return 0

    def _optimize_width_rstrip_rows(self, width: int) -> None:
        for row in self._get_rows():
            row.force_width(width)

    def _optimize_width_adapt_columns(self, width: int) -> None:
        # trim columns to match minimal_width
        columns = self._get_columns()
        repeated_cols: list[EText] = cast(
            list[EText],
            self.xpath("table:table-column/@table:number-columns-repeated"),
        )
        unrepeated = len(columns) - len(repeated_cols)
        column_width = sum(int(r) for r in repeated_cols) + unrepeated
        diff = column_width - width
        if diff > 0:
            for column in reversed(columns):  # pragma: nocover
                repeated = column.repeated or 1
                repeated = repeated - diff
                if repeated > 0:
                    column.repeated = repeated
                    break
                else:
                    column.parent.delete(column)  # type: ignore[union-attr]
                    diff = -repeated
                    if diff == 0:
                        break
        # raz cache of columns
        self._table_cache.clear_col_indexes()
        self._compute_table_cache()

    def transpose(self, coord: tuple | list | str | None = None) -> None:
        """Swap rows and columns of the table in-place.

        Args:
            coord: The coordinates of a specific
                area to transpose. If None, the entire table is transposed.
                If the area is not square, some cells may be overwritten.
        """
        data = []
        if coord is None:
            for row in self.iter_rows():
                data.append(row.cells)
            transposed_data = zip_longest(*data)
            self.clear()
            for row_cells in transposed_data:
                row = Row()
                row.extend_cells(row_cells)
                self.append_row(row, clone=False)
            self._compute_table_cache()
        else:
            x, y, z, t = self._translate_table_coordinates(coord)
            if x is None:
                x = 0
            else:
                x = min(x, self.width - 1)
            if z is None:
                z = self.width - 1
            else:
                z = min(z, self.width - 1)
            if y is None:
                y = 0
            else:
                y = min(y, self.height - 1)
            if t is None:
                t = self.height - 1
            else:
                t = min(t, self.height - 1)
            for row in self.iter_rows(start=y, end=t):
                data.append(list(row.iter_cells(start=x, end=z)))
            transposed_data = zip_longest(*data)
            # clear locally
            w = z - x + 1
            h = t - y + 1
            if w != h:
                nones = [[None] * w for i in range(h)]
                self.set_values(nones, coord=(x, y, z, t))
            # put transposed
            self.set_cells(
                cast(Iterable[tuple[Cell]], transposed_data),
                (x, y, x + h - 1, y + w - 1),
            )
            self._compute_table_cache()

    def is_empty(self, aggressive: bool = False) -> bool:
        """Return True if every cell in the table is empty.

        A cell is considered empty if it has no value (or a value that evaluates
        to False, like an empty string) and no style.

        Args:
            aggressive: If True, empty cells with styles are also
                considered empty.

        Returns:
            bool: True if the table is empty, False otherwise.
        """
        return all(row.is_empty(aggressive=aggressive) for row in self._get_rows())

    #
    # Rows
    #

    @property
    def row_groups(self) -> list[RowGroup]:
        """Get the list of all RowGroup elements in the table.

        Returns:
            list[RowGroup]: A list of RowGroup elements.
        """
        return cast(list[RowGroup], self.get_elements(_XP_ROW_GROUP))

    def _get_rows(self) -> list[Row]:
        return cast(list[Row], self.get_elements(_XP_ROW))

    def iter_rows(
        self,
        start: int | None = None,
        end: int | None = None,
    ) -> Iterator[Row]:
        """Yield row elements, expanding repetitions.

        This method produces individual row objects. The same row
        object is yielded as many times as it is repeated. The yielded
        columns are copies; use `set_row()` to apply changes.

        Args:
            start: The starting row index (0-based). Defaults to 0.
            end: The ending row index (inclusive). Defaults to 2**32.

        Yields:
            Row: The next row element in the specified range.
        """
        if start is None:
            start = 0
        start = max(0, start)
        if end is None:
            end = 2**32
        if end < start:
            return
        y = -1
        for row in self._yield_odf_rows():
            y += 1
            if y < start:
                continue
            if y > end:
                return
            row.y = y
            yield row

    traverse = iter_rows

    def get_rows(
        self,
        coord: tuple | list | str | None = None,
        style: str | None = None,
        content: str | None = None,
    ) -> list[Row]:
        """Get a list of rows matching the specified criteria.

        Args:
            coord: The coordinates of the rows
                to retrieve (e.g., (0, 2) for the first three rows).
            style: The name of a style to filter rows by.
            content: A regular expression to match against the
                content of the rows.

        Returns:
            list[Row]: A list of matching Row elements.
        """
        if coord:
            _x, y, _z, t = self._translate_table_coordinates(coord)
        else:
            y = t = None
        # fixme : not clones ?
        if not content and not style:
            return list(self.iter_rows(start=y, end=t))
        rows = []
        for row in self.iter_rows(start=y, end=t):
            if content and not row.match(content):
                continue
            if style and style != row.style:
                continue
            rows.append(row)
        return rows

    @property
    def rows(self) -> list[Row]:
        """Get a list of all rows in the table.

        Returns:
            list[Row]: A list of Row elements.
        """
        # fixme : not clones ?
        return list(self.iter_rows())

    def _yield_odf_rows(self) -> Iterator[Row]:
        for row in self._get_rows():
            if row.repeated is None:
                yield row
            else:
                for _ in range(row.repeated):
                    row_copy = row.clone
                    row_copy.repeated = None
                    yield row_copy

    def _get_row2(self, y: int, clone: bool = True, create: bool = True) -> Row:
        if y >= self.height:
            if create:
                return Row()
            raise ValueError("Row not found")
        row = self._get_row2_base(y)
        if row is None:
            raise ValueError("Row not found")
        if clone:
            return row.clone
        return row

    def _get_row2_base(self, y: int) -> Row | None:
        idx = self._table_cache.row_idx(y)
        if idx is None:
            return None
        row: Row | None = self._table_cache.cached_row(idx)
        if row is None:
            row = self._get_element_idx2(_XP_ROW_IDX, idx)  # type: ignore[assignment]
            if row is None:
                return None
            self._table_cache.store_row(row, idx)
        return row

    def get_row(self, y: int | str, clone: bool = True, create: bool = True) -> Row:
        """Get the row at the given 'y' position (0-based).

        A copy of the row is returned; use `set_row()` to apply any changes.

        Args:
            y: The 0-based index or string representation of the row.
            clone: If True (default), a copy of the row is returned.
            create: If True (default) and the row does not exist, a new
                empty row is created.

        Returns:
            Row: The Row element at the specified position.
        """
        # fixme : keep repeat ? maybe an option to functions : "raw=False"
        y = self._translate_y_from_any(y)
        row = self._get_row2(y, clone=clone, create=create)
        if row is None:
            raise ValueError("Row not found")
        row.y = y
        return row

    def set_row(self, y: int | str, row: Row | None = None, clone: bool = True) -> Row:
        """Replace the row at the given position with a new one.

        Repetitions of the old row will be adjusted. If `row` is None, a new
        empty row is created.

        Args:
            y: The 0-based index of the row to replace.
            row: The new Row element to set.
            clone: If True (default), a copy of the provided row is used.

        Returns:
            Row: The newly set row, with its `y` attribute updated.
        """
        if row is None:
            row = Row()
            repeated = 1
            clone = False
        else:
            repeated = row.repeated or 1
        y = self._translate_y_from_any(y)
        row.y = y
        # Outside the defined table ?
        diff = y - self.height
        if diff == 0:
            row_back = self.append_row(row, _repeated=repeated, clone=clone)
        elif diff > 0:
            self.append_row(Row(repeated=diff), _repeated=diff, clone=clone)
            row_back = self.append_row(row, _repeated=repeated, clone=clone)
        else:
            # Inside the defined table
            row_back = self._table_cache.set_row_in_cache(y, row, self, clone=clone)
        # print self.serialize(True)
        # Update width if necessary
        self._update_width(row_back)
        return row_back

    def insert_row(
        self, y: int | str, row: Row | None = None, clone: bool = True
    ) -> Row:
        """Insert a row before the given 'y' position (0-based).

        If no `row` is provided, an empty one is created.

        Args:
            y: The 0-based index at which to insert the row.
            row: The Row element to insert.
            clone: If True (default), a copy of the provided row is used.

        Returns:
            Row: The newly inserted row, with its `y` attribute updated.
        """
        if row is None:
            row = Row()
            clone = False
        y = self._translate_y_from_any(y)
        diff = y - self.height
        if diff < 0:
            row_back = self._table_cache.insert_row_in_cache(y, row, self)
        elif diff == 0:
            row_back = self.append_row(row, clone=clone)
        else:
            self.append_row(Row(repeated=diff), _repeated=diff, clone=False)
            row_back = self.append_row(row, clone=clone)
        row_back.y = y
        # Update width if necessary
        self._update_width(row_back)
        return row_back

    def extend_rows(self, rows: list[Row] | None = None) -> None:
        """Append a list of rows to the end of the table.

        Args:
            rows: A list of Row elements to append.
        """
        if rows is None:
            rows = []
        self.extend(rows)
        self._compute_table_cache()
        # Update width if necessary
        width = self.width
        for row in self.iter_rows():
            if row.width > width:
                width = row.width
        diff = width - self.width
        if diff > 0:
            self.append_column(Column(repeated=diff))

    def append_row(
        self,
        row: Row | None = None,
        clone: bool = True,
        _repeated: int | None = None,
    ) -> Row:
        """Append a row to the end of the table.

        If no `row` is provided, an empty one is created. Note that columns are
        automatically created when the first row is inserted into an empty table,
        so it's best to insert a filled row first.

        Args:
            row: The Row element to append.
            clone: If True (default), a copy of the provided row is used.
            _repeated: The number of times the row is repeated.

        Returns:
            Row: The newly appended row, with its `y` attribute updated.
        """
        if row is None:
            row = Row()
            _repeated = 1
        elif clone:
            row = row.clone
        # Appending a repeated row accepted
        # Do not insert next to the last row because it could be in a group
        self._append(row)
        if _repeated is None:
            _repeated = row.repeated or 1
        self._table_cache.insert_row_map_once(_repeated)
        row.y = self.height - 1
        # Initialize columns
        if not self._get_columns():
            repeated = row.width
            self.insert(Column(repeated=repeated), position=0)
            self._compute_table_cache()
        # Update width if necessary
        self._update_width(row)
        return row

    def delete_row(self, y: int | str) -> None:
        """Delete the row at the given 'y' position (0-based).

        Args:
            y: The 0-based index of the row to delete.
        """
        y = self._translate_y_from_any(y)
        # Outside the defined table
        if y >= self.height:
            return
        # Inside the defined table
        self._table_cache.delete_row_in_cache(y, self)

    def get_row_values(
        self,
        y: int | str,
        cell_type: str | None = None,
        complete: bool = True,
        get_type: bool = False,
    ) -> list:
        """Get the list of Python values for the cells of the row at the given 'y' position.

        Args:
            y: The 0-based index of the row.
            cell_type: Filters cells by value type (e.g., 'float').
                'all' retrieves any non-empty cell.
            complete: If True (default), missing values are replaced by None.
            get_type: If True, returns tuples of (value, odf_type).

        Returns:
            list: A list of Python types or (value, odf_type) tuples.
        """
        values = self.get_row(y, clone=False).get_values(
            cell_type=cell_type, complete=complete, get_type=get_type
        )
        # complete row to match column width
        if complete:
            if get_type:
                values.extend([(None, None)] * (self.width - len(values)))
            else:
                values.extend([None] * (self.width - len(values)))
        return values

    def get_row_sub_elements(self, y: int | str) -> list[Any]:
        """Get the list of Element values for the cells of the row at the given 'y' position.

        Missing values are replaced by None.

        Args:
            y: The 0-based index of the row.

        Returns:
            list[Any]: A list of sub-elements from each cell in the row.
        """
        values = self.get_row(y, clone=False).get_sub_elements()
        values.extend([None] * (self.width - len(values)))
        return values

    def set_row_values(
        self,
        y: int | str,
        values: list,
        cell_type: str | None = None,
        currency: str | None = None,
        style: str | None = None,
    ) -> Row:
        """Set the values of all cells in the row at the given 'y' position.

        Args:
            y: The 0-based index of the row.
            values: A list of Python types to set as cell values.
            cell_type: The value type for the cells (e.g., 'float').
            currency: A three-letter currency code.
            style: The name of a cell style to apply.

        Returns:
            Row: The modified row, with its `y` attribute updated.
        """
        row = Row()  # needed if clones rows
        row.set_values(values, style=style, cell_type=cell_type, currency=currency)
        return self.set_row(y, row)  # needed if clones rows

    def set_row_cells(self, y: int | str, cells: list | None = None) -> Row:
        """Set all the cells of the row at the given 'y' position.

        Args:
            y: The 0-based index of the row.
            cells: A list of Cell elements to set.

        Returns:
            Row: The modified row, with its `y` attribute updated.
        """
        if cells is None:
            cells = []
        row = Row()  # needed if clones rows
        row.extend_cells(cells)
        return self.set_row(y, row)  # needed if clones rows

    def is_row_empty(self, y: int | str, aggressive: bool = False) -> bool:
        """Return True if every cell in the row at the given 'y' position is empty.

        A cell is considered empty if it has no value (or a value that evaluates
        to False, like an empty string) and no style.

        Args:
            y: The 0-based index of the row.
            aggressive: If True, empty cells with styles are also
                considered empty.

        Returns:
            bool: True if the row is empty, False otherwise.
        """
        return self.get_row(y, clone=False).is_empty(aggressive=aggressive)

    #
    # Cells
    #

    def get_cells(
        self,
        coord: tuple | list | str | None = None,
        cell_type: str | None = None,
        style: str | None = None,
        content: str | None = None,
        flat: bool = False,
    ) -> list:
        """Get a list of cells, optionally from a specified area and filtered by criteria.

        Args:
            coord: The coordinates of the area to parse.
            cell_type: Filters by value type. 'all' gets any non-empty cell.
            style: Filters by cell style name.
            content: A regex to match against cell content.
            flat: If True, returns a single flat list of cells. Defaults to False.

        Returns:
            list: A list of lists of Cell elements, or a flat list if `flat` is True.
        """
        if coord:
            x, y, z, t = self._translate_table_coordinates(coord)
        else:
            x = y = z = t = None
        if flat:
            cells: list[Cell] = []
            for row in self.iter_rows(start=y, end=t):
                row_cells = row.get_cells(
                    coord=(x, z),
                    cell_type=cell_type,
                    style=style,
                    content=content,
                )
                cells.extend(row_cells)
            return cells
        else:
            lcells: list[list[Cell]] = []
            for row in self.iter_rows(start=y, end=t):
                row_cells = row.get_cells(
                    coord=(x, z),
                    cell_type=cell_type,
                    style=style,
                    content=content,
                )
                lcells.append(row_cells)
            return lcells

    @property
    def cells(self) -> list:
        """Get all cells of the table as a list of lists.

        Returns:
            list: A list of lists, where each inner list contains the Cell
                elements of a row.
        """
        lcells: list[list[Cell]] = []
        for row in self.iter_rows():
            lcells.append(row.cells)
        return lcells

    def get_cell(
        self,
        coord: tuple | list | str,
        clone: bool = True,
        keep_repeated: bool = True,
    ) -> Cell:
        """Get the cell at the given coordinates (e.g., (0, 2) or "C1").

        A copy of the cell is returned by default; use `set_cell()` to apply changes.

        Args:
            coord: The 0-based (x, y) coordinates or an
                alphanumeric string like "A1".
            clone: If True (default), a copy of the cell is returned.
            keep_repeated: If True (default), retains the repeated
                property of the cell.

        Returns:
            Cell: The Cell element at the specified coordinates.
        """
        x, y = self._translate_cell_coordinates(coord)
        if x is None:
            raise ValueError
        if y is None:
            raise ValueError
        # Outside the defined table
        if y >= self.height:
            cell = Cell()
        else:
            # Inside the defined table
            row = self._get_row2_base(y)
            if row is None:
                raise ValueError
            read_cell = row.get_cell(x, clone=clone)
            if read_cell is None:
                raise ValueError
            cell = read_cell
            if not keep_repeated and cell.get_attribute(
                "table:number-columns-repeated"
            ):
                cell._set_repeated(None)
        cell.x = x
        cell.y = y
        return cell

    def get_value(
        self,
        coord: tuple | list | str,
        get_type: bool = False,
    ) -> Any:
        """Get the Python value of the cell at the given coordinates.

        Args:
            coord: The cell coordinates (e.g., "A1" or (0,0)).
            get_type: If True, returns a tuple of (value, odf_type).

        Returns:
            Any: The Python value of the cell, or a (value, type) tuple if
                `get_type` is True.
        """
        x, y = self._translate_cell_coordinates(coord)
        if x is None:
            raise ValueError
        if y is None:
            raise ValueError
        # Outside the defined table
        if y >= self.height:
            if get_type:
                return (None, None)
            return None
        else:
            # Inside the defined table
            row = self._get_row2_base(y)
            if row is None:
                raise ValueError
            cell = row._get_cell2_base(x)
            if cell is None:
                if get_type:
                    return (None, None)
                return None
            return cell.get_value(get_type=get_type)

    def set_cell(
        self,
        coord: tuple | list | str,
        cell: Cell | None = None,
        clone: bool = True,
    ) -> Cell:
        """Replace the cell at the given coordinates.

        If `cell` is None, an empty cell is created.

        Args:
            coord: The coordinates of the cell to replace.
            cell: The new Cell element to set.
            clone: If True (default), a copy of the provided cell is used.

        Returns:
            Cell: The newly set cell, with its `x` and `y` attributes updated.
        """
        if cell is None:
            cell = Cell()
            clone = False
        x, y = self._translate_cell_coordinates(coord)
        if x is None:
            raise ValueError
        if y is None:
            raise ValueError
        cell.x = x
        cell.y = y
        if y >= self.height:
            row = Row()
            cell_back = row.set_cell(x, cell, clone=clone)
            self.set_row(y, row, clone=False)
        else:
            row_read = self._get_row2_base(y)
            if row_read is None:
                raise ValueError
            row = row_read
            row.y = y
            repeated = row.repeated or 1
            if repeated > 1:
                row = row.clone
                row.repeated = None
                cell_back = row.set_cell(x, cell, clone=clone)
                self.set_row(y, row, clone=False)
            else:
                cell_back = row.set_cell(x, cell, clone=clone)
                # Update width if necessary, since we don't use set_row
                self._update_width(row)
        return cell_back

    def set_cells(
        self,
        cells: Iterable[list[Cell]] | Iterable[tuple[Cell]],
        coord: tuple | list | str | None = None,
        clone: bool = True,
    ) -> None:
        """Set a matrix of cells in the table, starting from a specified coordinate.

        The table is not cleared before this operation. The `cells` argument should
        be a list of lists, where each inner list represents a row.

        Args:
            cells: A list of lists
                of Cell elements.
            coord: The top-left coordinate for
                placing the cells. Defaults to "A1".
            clone: If True (default), copies of the provided cells are used.
        """
        if coord:
            x, y = self._translate_cell_coordinates(coord)
        else:
            x = y = 0
        if y is None:
            y = 0
        if x is None:
            x = 0
        y -= 1
        for row_cells in cells:
            y += 1
            if not row_cells:
                continue
            row = self.get_row(y, clone=True)
            repeated = row.repeated or 1
            if repeated >= 2:
                row.repeated = None
            row.set_cells(row_cells, start=x, clone=clone)
            self.set_row(y, row, clone=False)
            self._update_width(row)

    def set_value(
        self,
        coord: tuple | list | str,
        value: Any,
        cell_type: str | None = None,
        currency: str | None = None,
        style: str | None = None,
    ) -> None:
        """Set the Python value of the cell at the given coordinates.

        Args:
            coord: The coordinates of the cell.
            value: The Python value to set.
            cell_type: The value type (e.g., 'float', 'string').
            currency: A three-letter currency code.
            style: The name of a cell style to apply.
        """
        self.set_cell(
            coord,
            Cell(value, cell_type=cell_type, currency=currency, style=style),
            clone=False,
        )

    def set_cell_image(
        self,
        coord: tuple | list | str,
        image_frame: Frame,
        doc_type: str | None = None,
    ) -> None:
        """Deprecated. Use recipes to insert an image in a cell.

        This method provided a way to insert an image into a cell, but it is now
        deprecated. Please refer to the project's recipes for the recommended
        way to achieve this.

        Args:
            coord: The coordinates of the cell.
            image_frame: The Frame element containing the image.
            doc_type: The document type ('spreadsheet' or 'text').
        """
        warn("Table.set_cell_image() is deprecated", DeprecationWarning, stacklevel=2)
        # Test document type
        if doc_type is None:
            body = self.document_body
            if body is None:
                raise ValueError("document type not found")
            doc_type = {"office:spreadsheet": "spreadsheet", "office:text": "text"}.get(
                body.tag
            )
            if doc_type is None:
                raise ValueError("document type not supported for images")
        # We need the end address of the image
        x, y = self._translate_cell_coordinates(coord)
        if x is None:
            raise ValueError
        if y is None:
            raise ValueError
        cell = self.get_cell((x, y))
        image_frame = image_frame.clone  # type: ignore[assignment]
        # Remove any previous paragraph, frame, etc.
        for child in cell.children:
            cell.delete(child)
        # Now it all depends on the document type
        if doc_type == "spreadsheet":
            image_frame.anchor_type = "char"
            # The frame needs end coordinates
            width, height = image_frame.size
            image_frame.set_attribute("table:end-x", width)
            image_frame.set_attribute("table:end-y", height)
            # FIXME what happens when the address changes?
            address = f"{self.name}.{digit_to_alpha(x)}{y + 1}"
            image_frame.set_attribute("table:end-cell-address", address)
            # The frame is directly in the cell
            cell.append(image_frame)
        elif doc_type == "text":
            # The frame must be in a paragraph
            cell.set_value("")
            paragraph = cell.get_element("text:p")
            if paragraph is None:
                raise ValueError
            paragraph.append(image_frame)
        self.set_cell(coord, cell)

    def insert_cell(
        self,
        coord: tuple | list | str,
        cell: Cell | None = None,
        clone: bool = True,
    ) -> Cell:
        """Insert a cell at the given coordinates, shifting existing cells to the right.

        If `cell` is None, an empty cell is created.

        Args:
            coord: The (x, y) coordinates for insertion.
            cell: The Cell element to insert.
            clone: If True (default), a copy of the provided cell is used.

        Returns:
            Cell: The newly inserted cell, with its `x` and `y` attributes updated.
        """
        if cell is None:
            cell = Cell()
            clone = False
        if clone:
            cell = cell.clone
        x, y = self._translate_cell_coordinates(coord)
        if x is None:
            raise ValueError
        if y is None:
            raise ValueError
        row = self._get_row2(y, clone=True)
        row.y = y
        row.repeated = None
        cell_back = row.insert_cell(x, cell, clone=False)
        self.set_row(y, row, clone=False)
        # Update width if necessary
        self._update_width(row)
        return cell_back

    def append_cell(
        self,
        y: int | str,
        cell: Cell | None = None,
        clone: bool = True,
    ) -> Cell:
        """Append a cell to the end of the row at the given 'y' coordinate.

        If `cell` is None, an empty cell is created.

        Args:
            y: The 0-based index of the row to append to.
            cell: The Cell element to append.
            clone: If True (default), a copy of the provided cell is used.

        Returns:
            Cell: The newly appended cell, with its `x` and `y` attributes updated.
        """
        if cell is None:
            cell = Cell()
            clone = False
        if clone:
            cell = cell.clone
        y = self._translate_y_from_any(y)
        row = self._get_row2(y)
        row.y = y
        cell_back = row.append_cell(cell, clone=False)
        self.set_row(y, row)
        # Update width if necessary
        self._update_width(row)
        return cell_back

    def delete_cell(self, coord: tuple | list | str) -> None:
        """Delete the cell at the given coordinates, shifting subsequent cells to the left.

        To clear a cell's value without deleting it, use `set_value()` with an
        empty value.

        Args:
            coord: The coordinates of the cell to delete.
        """
        x, y = self._translate_cell_coordinates(coord)
        if x is None:
            raise ValueError
        if y is None:
            raise ValueError
        # Outside the defined table
        if y >= self.height:
            return
        # Inside the defined table
        row = self._get_row2_base(y)
        if row is None:
            raise ValueError
        row.delete_cell(x)
        # self.set_row(y, row)

    # Columns

    def _get_columns(self) -> list[Column]:
        return cast(list[Column], self.get_elements(_XP_COLUMN))

    def iter_columns(
        self,
        start: int | None = None,
        end: int | None = None,
    ) -> Iterator[Column]:
        """Yield column elements, expanding repetitions.

        This method produces individual column objects. The same column
        object is yielded as many times as it is repeated. The yielded
        columns are copies; use `set_column()` to apply changes.

        Args:
            start: The starting column index (0-based). Defaults to 0.
            end: The ending column index (inclusive). Defaults to 2**32.

        Yields:
            Column: The next column element in the specified range.
        """
        if start is None:
            start = 0
        start = max(0, start)
        if end is None:
            end = 2**32
        if end < start:
            return
        x = -1
        for column in self._yield_odf_columns():
            x += 1
            if x < start:
                continue
            if x > end:
                return
            column.x = x
            yield column

    traverse_columns = iter_columns

    def _yield_odf_columns(self) -> Iterator[Column]:
        for column in self._get_columns():
            if column.repeated is None:
                yield column
            else:
                for _ in range(column.repeated):
                    column_copy = column.clone
                    column_copy.repeated = None
                    yield column_copy

    def get_columns(
        self,
        coord: tuple | list | str | None = None,
        style: str | None = None,
    ) -> list[Column]:
        """Get a list of columns matching the specified criteria.

        The returned columns are copies; use `set_column()` to apply any changes.

        Args:
            coord: The coordinates of the columns
                to retrieve.
            style: The name of a style to filter columns by.

        Returns:
            list[Column]: A list of matching Column elements.
        """
        if coord:
            x, _y, _z, t = self._translate_column_coordinates(coord)
        else:
            x = t = None
        if not style:
            return list(self.iter_columns(start=x, end=t))
        columns = []
        for column in self.iter_columns(start=x, end=t):
            if style != column.style:
                continue
            columns.append(column)
        return columns

    def _get_column2(self, x: int) -> Column | None:
        # Outside the defined table
        if x >= self.width:
            return Column()
        idx = self._table_cache.col_idx(x)
        if idx is None:
            return None
        column = self._table_cache.cached_col(idx)
        if column is None:
            column = self._get_element_idx2(_XP_COLUMN_IDX, idx)  # type:ignore[assignment]
            if column is None:
                return None
            self._table_cache.store_col(column, idx)
        return column.clone

    @property
    def columns(self) -> list[Column]:
        """Get a list of all columns in the table.

        The returned columns are copies; use `set_column()` to apply any changes.

        Returns:
            A list of all Column elements.
        """
        return list(self.iter_columns())

    def get_column(self, x: int | str) -> Column:
        """Get the column at the given 'x' position (0-based or alphabetical).

        ODF columns primarily store style information, not cell content. A copy of
        the column is returned; use `set_column()` to apply any changes.

        Args:
            x: The 0-based index or alphabetical representation
                (e.g., "C") of the column.

        Returns:
            Column: The Column element at the specified position.
        """
        x = self._translate_x_from_any(x)
        column = self._get_column2(x)
        if column is None:
            raise ValueError
        column.x = x
        return column

    def set_column(
        self,
        x: int | str,
        column: Column | None = None,
    ) -> Column:
        """Replace the column at the given 'x' position.

        ODF columns primarily store style information.

        Args:
            x: The 0-based index or alphabetical representation
                of the column to replace.
            column: The new Column element to set. If None,
                an empty column is created.

        Returns:
            Column: The newly set column, with its `x` attribute updated.
        """
        x = self._translate_x_from_any(x)
        if column is None:
            column = Column()
            repeated = 1
        else:
            repeated = column.repeated or 1
        column.x = x
        # Outside the defined table ?
        diff = x - self.width
        if diff == 0:
            column_back = self.append_column(column, _repeated=repeated)
        elif diff > 0:
            self.append_column(Column(repeated=diff), _repeated=diff)
            column_back = self.append_column(column, _repeated=repeated)
        else:
            # Inside the defined table
            column_back = self._table_cache.set_col_in_cache(x, column, self)
        return column_back

    def insert_column(
        self,
        x: int | str,
        column: Column | None = None,
    ) -> Column:
        """Insert a column before the given 'x' position.

        If no `column` is provided, an empty one is created.

        Args:
            x: The 0-based index at which to insert the column.
            column: The Column element to insert.

        Returns:
            Column: The newly inserted column, with its `x` attribute updated.
        """
        if column is None:
            column = Column()
        x = self._translate_x_from_any(x)
        diff = x - self.width
        if diff < 0:
            column_back = self._table_cache.insert_col_in_cache(x, column, self)
        elif diff == 0:
            column_back = self.append_column(column.clone)
        else:
            self.append_column(Column(repeated=diff), _repeated=diff)
            column_back = self.append_column(column.clone)
        column_back.x = x
        # Repetitions are accepted
        repeated = column.repeated or 1
        # Update width on every row
        for row in self._get_rows():
            if row.width > x:
                row.insert_cell(x, Cell(repeated=repeated))
            # Shorter rows don't need insert
            # Longer rows shouldn't exist!
        return column_back

    def append_column(
        self,
        column: Column | None = None,
        _repeated: int | None = None,
    ) -> Column:
        """Append a column to the end of the table.

        If no `column` is provided, an empty one is created. ODF columns do not
        contain cells, only style information.

        Args:
            column: The Column element to append.
            _repeated: The number of times the column is repeated.

        Returns:
            Column: The newly appended column, with its `x` attribute updated.
        """
        if column is None:
            column = Column()
            _repeated = 1
        else:
            column = column.clone
        odf_idx = self._table_cache.col_map_length() - 1
        if odf_idx < 0:
            position = 0
        else:
            last_column = self._get_element_idx2(_XP_COLUMN_IDX, odf_idx)
            if last_column is None:
                raise ValueError
            position = self.index(last_column) + 1
        column.x = self.width
        self.insert(column, position=position)
        # Repetitions are accepted
        if _repeated is None:
            _repeated = column.repeated or 1
        self._table_cache.insert_col_map_once(_repeated)
        # No need to update row widths
        return column

    def delete_column(self, x: int | str) -> None:
        """Delete the column at the given position.

        Args:
            x: The 0-based index or alphabetical representation
                of the column to delete.
        """
        x = self._translate_x_from_any(x)
        # Outside the defined table
        if x >= self.width:
            return
        # Inside the defined table
        self._table_cache.delete_col_in_cache(x, self)
        # Update width
        width = self.width
        for row in self._get_rows():
            if row.width >= width:
                row.delete_cell(x)

    def get_column_cells(
        self,
        x: int | str,
        style: str | None = None,
        content: str | None = None,
        cell_type: str | None = None,
        complete: bool = False,
    ) -> list[Cell | None]:
        """Get a list of cells from the column at the given 'x' position.

        Args:
            x: The 0-based index or alphabetical representation
                of the column.
            style: Filters by cell style name.
            content: A regex to match against cell content.
            cell_type: Filters by value type. 'all' gets any
                non-empty cell.
            complete: If True, missing cells are represented by None.

        Returns:
            list[Cell | None]: A list of Cell elements or None.
        """
        x = self._translate_x_from_any(x)
        if cell_type:
            cell_type = cell_type.lower().strip()
        cells: list[Cell | None] = []
        if not style and not content and not cell_type:
            for row in self.iter_rows():
                cells.append(row.get_cell(x, clone=True))
            return cells
        for row in self.iter_rows():
            cell = row.get_cell(x, clone=True)
            if cell is None:
                raise ValueError
            # Filter the cells by cell_type
            if cell_type:
                ctype = cell.type
                if not ctype or not (ctype == cell_type or cell_type == "all"):
                    if complete:
                        cells.append(None)
                    continue
            # Filter the cells with the regex
            if content and not cell.match(content):
                if complete:
                    cells.append(None)
                continue
            # Filter the cells with the style
            if style and style != cell.style:
                if complete:
                    cells.append(None)
                continue
            cells.append(cell)
        return cells

    def get_column_values(
        self,
        x: int | str,
        cell_type: str | None = None,
        complete: bool = True,
        get_type: bool = False,
    ) -> list[Any]:
        """Get the list of Python values for the cells in the column at the given 'x' position.

        Args:
            x: The 0-based index or alphabetical representation of the column.
            cell_type: Filters by value type. 'all' gets any non-empty cell.
            complete: If True (default), missing values are replaced by None.
            get_type: If True, returns tuples of (value, odf_type).

        Returns:
            list[Any]: A list of Python values or (value, odf_type) tuples.
        """
        cells = self.get_column_cells(
            x, style=None, content=None, cell_type=cell_type, complete=complete
        )
        values: list[Any] = []
        for cell in cells:
            if cell is None:
                if complete:
                    if get_type:
                        values.append((None, None))
                    else:
                        values.append(None)
                continue
            if cell_type:
                ctype = cell.type
                if not ctype or not (ctype == cell_type or cell_type == "all"):
                    if complete:
                        if get_type:
                            values.append((None, None))
                        else:
                            values.append(None)
                    continue
            values.append(cell.get_value(get_type=get_type))
        return values

    def set_column_cells(self, x: int | str, cells: list[Cell]) -> None:
        """Set the list of cells for the column at the given 'x' position.

        The provided list of cells must have the same length as the table's height.

        Args:
            x: The 0-based index or alphabetical representation
                of the column.
            cells: A list of Cell elements to set.
        """
        height = self.height
        if len(cells) != height:
            raise ValueError(f"col mismatch: {height} cells expected")
        cells_iterator = iter(cells)
        for y, row in enumerate(self.iter_rows()):
            row.set_cell(x, next(cells_iterator))
            self.set_row(y, row)

    def set_column_values(
        self,
        x: int | str,
        values: list,
        cell_type: str | None = None,
        currency: str | None = None,
        style: str | None = None,
    ) -> None:
        """Set the list of Python values for the cells in the column at the given 'x' position.

        The provided list of values must have the same length as the table's height.

        Args:
            x: The 0-based index or alphabetical representation of the column.
            values: A list of Python types to set as cell values.
            cell_type: The value type for the cells.
            currency: A three-letter currency code.
            style: The name of a cell style to apply.
        """
        cells = [
            Cell(value, cell_type=cell_type, currency=currency, style=style)
            for value in values
        ]
        self.set_column_cells(x, cells)

    def is_column_empty(self, x: int | str, aggressive: bool = False) -> bool:
        """Return True if every cell in the column at the 'x' position is empty.

        A cell is considered empty if it has no value (or a value that evaluates
        to False) and no style.

        Args:
            x: The 0-based index or alphabetical representation of the column.
            aggressive: If True, empty cells with styles are also considered empty.

        Returns:
            bool: True if the column is empty, False otherwise.
        """
        for cell in self.get_column_cells(x):
            if cell is None:
                continue
            if not cell.is_empty(aggressive=aggressive):
                return False
        return True

    # Named Range
    def _local_named_ranges(self) -> list[NamedRange]:
        """(internal) Return the list of local Name Ranges."""
        return cast(
            list[NamedRange],
            self.get_elements("descendant::table:named-expressions/table:named-range"),
        )

    def _local_named_range(self, name: str) -> NamedRange | None:
        """(internal) Return the local Name Range of the specified name."""
        named_range = self.get_elements(
            f'descendant::table:named-expressions/table:named-range[@table:name="{name}"][1]'
        )
        if named_range:
            return cast(NamedRange, named_range[0])
        else:
            return None

    def _local_append_named_range(self, named_range: NamedRange) -> None:
        """(internal) Append the named range to the current table."""
        named_expressions = cast(
            None | TableNamedExpressions,
            self.get_element(TableNamedExpressions._tag),
        )
        if not named_expressions:
            named_expressions = TableNamedExpressions()
            self._xml_append(named_expressions)
        # exists ?
        current = named_expressions.get_element(
            f'table:named-range[@table:name="{named_range.name}"][1]'
        )
        if current:
            named_expressions.delete(current)
        named_expressions._xml_append(named_range)

    def _local_set_named_range(
        self, name: str, crange: str | tuple | list, usage: str | None = None
    ) -> None:
        """(internal) Create a Named Range element and insert it in the current
        table.
        """
        named_range = NamedRange(name, crange, self.name, usage)
        self._local_append_named_range(named_range)

    def _local_delete_named_range(self, name: str) -> None:
        """(internal) Delete the Named Range of specified name."""
        named_range = self._local_named_range(name)
        if not named_range:
            return
        named_range.delete()
        named_expressions = cast(
            None | TableNamedExpressions,
            self.get_element(TableNamedExpressions._tag),
        )
        if not named_expressions:
            return
        if named_expressions.is_empty():
            self.delete(named_expressions)

    def get_named_ranges(
        self,
        table_name: str | list[str] | None = None,
        global_scope: bool = True,
    ) -> list[NamedRange]:
        """Return a list of named ranges, optionally filtered by scope and table name.

        Named ranges can be local to a table or global to the document. Global
        named ranges are stored at the body level, so this method should not be
        called on a cloned table if access to global named ranges is required.

        Args:
            table_name: A name or list of names
                of tables to filter by.
            global_scope: If True (default), searches the entire document.
                If False, searches only the current table.

        Returns:
            list[NamedRange]: A list of matching NamedRange elements.
        """
        if global_scope:
            body = self.document_body
            if not body or not body.allow_named_range:
                return []
            named_ranges = body.get_named_ranges()  # type: ignore[attr-defined]
        else:
            named_ranges = self._local_named_ranges()
        if not table_name:
            return named_ranges  # type: ignore[no-any-return]
        filter_ = []
        if isinstance(table_name, str):
            filter_.append(table_name)
        elif isiterable(table_name):
            filter_.extend(table_name)
        else:
            msg = f"table_name must be string or Iterable, not {type(table_name)!r}"
            raise ValueError(msg)
        return [nr for nr in named_ranges if nr.table_name in filter_]

    def get_named_range(
        self, name: str, global_scope: bool = True
    ) -> NamedRange | None:
        """Return the named range with the specified name.

        Named ranges can be local or global. Global named ranges are stored at
        the body level, so do not call this on a cloned table for global access.

        Args:
            name: The name of the named range object.
            global_scope: If True (default), searches the entire document.
                If False, searches only the current table.

        Returns:
            NamedRange | None: The matching NamedRange element, or None if not found.
        """
        if global_scope:
            body = self.document_body
            if not body:
                raise ValueError("Table is not inside a document")
            if not body.allow_named_range:
                return None
            nr: NamedRange | None = body.get_named_range(name)  # type: ignore[attr-defined]

        else:
            nr = self._local_named_range(name)
        return nr

    def append_named_range(
        self, named_range: NamedRange, global_scope: bool = True
    ) -> None:
        """Append a named range to the document, replacing any existing one with the same name.

        Named ranges can be local or global. Global named ranges are stored at
        the body level, so do not call this on a cloned table for global access.

        Args:
            named_range: The NamedRange element to append.
            global_scope: If True (default), appends to the document body.
                If False, appends to the current table.
        """
        if global_scope:
            body = self.document_body
            if not body:
                raise ValueError("Table is not inside a document")
            if not body.allow_named_range:
                msg = (
                    "Document must be of type Chart, Drawing, "
                    "Presentation, Spreadsheet or Text"
                )
                raise TypeError(msg)
            body.append_named_range(named_range)  # type: ignore[attr-defined]
        else:
            self._local_append_named_range(named_range)

    def set_named_range(
        self,
        name: str,
        crange: str | tuple | list,
        table_name: str | None = None,
        usage: str | None = None,
        global_scope: bool = True,
    ) -> None:
        """Create and insert a named range, replacing any existing one with the same name.

        Named ranges can be local or global. Global named ranges are stored at
        the body level, so do not call this on a cloned table for global access.

        Args:
            name: The name of the named range.
            crange: The cell or area coordinates.
            table_name: The name of the table. Defaults to the
                current table's name if `global_scope` is True.
            usage: The usage type ('print-range', 'filter', etc.).
            global_scope: If True (default), inserts into the document body.
                If False, inserts into the current table.
        """
        name = name.strip()
        if not name:
            raise ValueError("Name required")
        if global_scope:
            body = self.document_body
            if not body:
                raise ValueError("Table is not inside a document")
            if not body.allow_named_range:
                msg = (
                    "Document must be of type Chart, Drawing, "
                    "Presentation, Spreadsheet or Text"
                )
                raise TypeError(msg)
            if not table_name:
                table_name = self.name
            body.set_named_range(  # type: ignore[attr-defined]
                name=name,
                crange=crange,
                table_name=table_name,
                usage=usage,
            )
        else:
            self._local_set_named_range(name=name, crange=crange, usage=usage)

    def delete_named_range(self, name: str, global_scope: bool = True) -> None:
        """Delete the named range with the specified name.

        Named ranges can be local or global. Global named ranges are stored at
        the body level, so do not call this on a cloned table for global access.

        Args:
            name: The name of the named range to delete.
            global_scope: If True (default), searches the entire document.
                If False, searches only the current table.
        """
        name = name.strip()
        if not name:
            raise ValueError("Name required")
        if global_scope:
            body = self.document_body
            if not body:
                raise ValueError("Table is not inside a document")
            if not body.allow_named_range:
                msg = (
                    "Document must be of type Chart, Drawing, "
                    "Presentation, Spreadsheet or Text"
                )
                raise TypeError(msg)
            body.delete_named_range(name)  # type: ignore[attr-defined]
        else:
            self._local_delete_named_range(name)

    #
    # Cell span
    #

    def set_span(
        self,
        area: str | tuple | list,
        merge: bool = False,
    ) -> bool:
        """Create a cell span, spanning the first cell of the area over columns and/or rows.

        It is not allowed to apply a span to an area where a cell already belongs
        to a previous span. If the area defines only one cell, this method does nothing.

        Args:
            area: The cell or area coordinates (e.g., "A1:B2").
            merge: If True, concatenates the text of covered cells into the
                first cell. If False (default), text in covered cells is preserved
                but may not be displayed by office applications.

        Returns:
            bool: True if the span was successfully created, False otherwise.
        """
        # get area
        digits = convert_coordinates(area)
        if len(digits) == 4:
            x, y, z, t = digits
        else:
            x, y = digits
            z, t = digits
        start = x, y
        end = z, t
        if start == end:
            # one cell : do nothing
            return False
        if x is None:
            raise ValueError
        if y is None:
            raise ValueError
        if z is None:
            raise ValueError
        if t is None:
            raise ValueError
        # check for previous span
        good = True
        # Check boundaries and empty cells : need to crate non existent cells
        # so don't use get_cells directly, but get_cell
        cells = []
        for yy in range(y, t + 1):
            row_cells = []
            for xx in range(x, z + 1):
                row_cells.append(
                    self.get_cell((xx, yy), clone=True, keep_repeated=False)
                )
            cells.append(row_cells)
        for row in cells:
            for cell in row:
                if cell.is_spanned():
                    good = False
                    break
            if not good:
                break
        if not good:
            return False
        # Check boundaries
        # if z >= self.width or t >= self.height:
        #    self.set_cell(coord = end)
        #    print area, z, t
        #    cells = self.get_cells((x, y, z, t))
        #    print cells
        # do it:
        if merge:
            val_list = []
            for row in cells:
                for cell in row:
                    if cell.is_empty(aggressive=True):
                        continue
                    val = cell.get_value()
                    if val is not None:
                        if isinstance(val, str):
                            val.strip()
                        if val != "":
                            val_list.append(val)
                        cell.clear()
            if val_list:
                if len(val_list) == 1:
                    cells[0][0].set_value(val_list[0])  # type: ignore[arg-type]
                else:
                    value = " ".join([str(v) for v in val_list if v])
                    cells[0][0].set_value(value)
        cols = z - x + 1
        cells[0][0].set_attribute("table:number-columns-spanned", str(cols))
        rows = t - y + 1
        cells[0][0].set_attribute("table:number-rows-spanned", str(rows))
        for cell in cells[0][1:]:
            cell.tag = "table:covered-table-cell"
        for row in cells[1:]:
            for cell in row:
                cell.tag = "table:covered-table-cell"
        # replace cells in table
        self.set_cells(cells, coord=start, clone=False)
        return True

    def del_span(self, area: str | tuple | list) -> bool:
        """Delete a cell span.

        The `area` should specify the top-left cell of the spanned area.

        Args:
            area: The coordinates of the top-left cell
                of the spanned area.

        Returns:
            bool: True if the span was successfully deleted, False otherwise.
        """
        # get area
        digits = convert_coordinates(area)
        if len(digits) == 4:
            x, y, _z, _t = digits
        else:
            x, y = digits
        if x is None:
            raise ValueError
        if y is None:
            raise ValueError
        start = x, y
        # check for previous span
        cell0 = self.get_cell(start)
        nb_cols = cell0.get_attribute_integer("table:number-columns-spanned")
        if nb_cols is None:
            return False
        nb_rows = cell0.get_attribute_integer("table:number-rows-spanned")
        if nb_rows is None:
            return False
        z = x + nb_cols - 1
        t = y + nb_rows - 1
        cells = self.get_cells((x, y, z, t))
        cells[0][0].del_attribute("table:number-columns-spanned")
        cells[0][0].del_attribute("table:number-rows-spanned")
        for cell in cells[0][1:]:
            cell.tag = "table:table-cell"
        for row in cells[1:]:
            for cell in row:
                cell.tag = "table:table-cell"
        # replace cells in table
        self.set_cells(cells, coord=start, clone=False)
        return True

    # Utilities

    def to_csv(
        self,
        path_or_file: str | Path | None = None,
        dialect: str = "excel",
        **fmtparams: Any,
    ) -> str | None:
        """Export the table as a CSV string or file.

        Args:
            path_or_file: The path to save the CSV file to.
                If None, the CSV content is returned as a string.
            dialect: The CSV dialect to use (e.g., 'excel', 'unix').
            **fmtparams: Additional keyword arguments to pass to the
                `csv.writer` method.

        Returns:
            str | None: The CSV content as a string if `path_or_file` is None,
                otherwise None.
        """

        def write_content(csv_writer: object) -> None:
            for values in self.iter_values():
                line = []
                for value in values:
                    if value is None:
                        value = ""
                    line.append(value)
                csv_writer.writerow(line)  # type: ignore[attr-defined]

        content = StringIO(newline="")
        csv_writer = csv.writer(content, dialect=dialect, **fmtparams)
        write_content(csv_writer)
        if path_or_file:
            # windows fix: write file as binary
            Path(path_or_file).write_bytes(content.getvalue().encode())
            return None
        return content.getvalue()

    @classmethod
    def from_csv(
        cls,
        content: str,
        name: str,
        style: str | None = None,
        **fmtparams: Any,
    ) -> Table:
        """Import a CSV string into a new Table object.

        The CSV format can be auto-detected to a certain extent. Use `**fmtparams`
        to define `csv.reader` parameters for more control.

        Args:
            content: The CSV content as a string.
            name: The name of the table to create.
            style: The style to apply to the table.
            **fmtparams: Additional keyword arguments for the `csv.reader` method.

        Returns:
            Table: A new Table object populated with the CSV data.
        """
        data = content.splitlines(True)
        # Sniff the dialect
        sample = "".join(data[:2048])
        dialect = csv.Sniffer().sniff(sample)
        # Make the rows
        reader = csv.reader(data, dialect=dialect, **fmtparams)
        table = cls(name, style=style)
        encoding = fmtparams.get("encoding", "utf-8")
        for line in reader:
            row = Row()
            # rstrip line
            while line and not line[-1].strip():
                line.pop()
            for value in line:
                cell = Cell(_get_python_value(value, encoding))
                row.append_cell(cell, clone=False)
            table.append_row(row, clone=False)
        return table

_append class-attribute instance-attribute

_append = append

_table_cache instance-attribute

_table_cache = TableCache()

_tag class-attribute instance-attribute

_tag = 'table:table'

cells property

cells: list

Get all cells of the table as a list of lists.

Returns:

Name Type Description
list list

A list of lists, where each inner list contains the Cell elements of a row.

columns property

columns: list[Column]

Get a list of all columns in the table.

The returned columns are copies; use set_column() to apply any changes.

Returns:

Type Description
list[Column]

A list of all Column elements.

height property

height: int

Get the current height of the table.

Returns:

Type Description
int

The number of rows in the table.

name property writable

name: str | None

Get or set the name of the table.

The name is required and cannot contain []*?:/ or \ characters. Apostrophes (') are not allowed as the first or last character.

print_ranges property writable

print_ranges: list[str]

Get or set the print ranges for the table.

Returns:

Type Description
list[str]

list[str]: A list of strings representing the print ranges (e.g., [‘A1:C5’, ‘E1:G5’]).

printable property writable

printable: bool

Get or set the printable status of the table.

Returns:

Name Type Description
bool bool

True if the table is printable, False otherwise.

protected property writable

protected: bool

Get or set the protected status of the table.

Returns:

Name Type Description
bool bool

True if the table is protected, False otherwise.

protection_key property writable

protection_key: str | None

Get or set the protection key for the table.

Returns:

Type Description
str | None

str | None: The protection key (a hash value) as a string, or None if not set.

row_groups property

row_groups: list[RowGroup]

Get the list of all RowGroup elements in the table.

Returns:

Type Description
list[RowGroup]

list[RowGroup]: A list of RowGroup elements.

rows property

rows: list[Row]

Get a list of all rows in the table.

Returns:

Type Description
list[Row]

list[Row]: A list of Row elements.

size property

size: tuple[int, int]

Get the current width and height of the table.

Returns:

Type Description
tuple[int, int]

A tuple containing the (width, height) of the table.

style property writable

style: str | None

Get or set the style name of the table.

Returns:

Type Description
str | None

str | None: The name of the style as a string, or None if not set.

traverse class-attribute instance-attribute

traverse = iter_rows

traverse_columns class-attribute instance-attribute

traverse_columns = iter_columns

width property

width: int

Get the current width of the table, based on the column definitions.

Note that individual rows may have different widths. It is recommended to use the Table API to maintain a consistent width.

Returns:

Name Type Description
int int

The number of columns in the table.

__init__

__init__(
    name: str | None = None,
    width: int | str | None = None,
    height: int | str | None = None,
    protected: bool = False,
    protection_key: str | None = None,
    printable: bool = True,
    print_ranges: list[str] | None = None,
    style: str | None = None,
    **kwargs: Any,
) -> None

Initializes a Table element.

The table can optionally be pre-filled with a specified number of rows and cells.

Parameters:

Name Type Description Default
name str | None

The name of the table. It is required and cannot contain specific characters like []*?:/\. Apostrophes are also forbidden as the first or last character.

None
width int | str | None

The initial number of columns for the table.

None
height int | str | None

The initial number of rows for the table.

None
protected bool

If True, the table is protected. A protection_key must be provided if this is True.

False
protection_key str | None

A hash value of the password for table protection.

None
printable bool

If False, the table will not be printed. Defaults to True.

True
print_ranges list[str] | None

A list of cell ranges (e.g., ['E6:K12', 'P6:R12']) or a raw string specifying the print ranges.

None
style str | None

The name of the style to apply to the table.

None
**kwargs Any

Additional keyword arguments for the Element base class.

{}

Raises:

Type Description
ValueError

If protected is True but protection_key is not provided.

Note

Directly manipulating the XML tree while using the table API may lead to inconsistencies.

Source code in odfdo/table.py
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
def __init__(
    self,
    name: str | None = None,
    width: int | str | None = None,
    height: int | str | None = None,
    protected: bool = False,
    protection_key: str | None = None,
    printable: bool = True,
    print_ranges: list[str] | None = None,
    style: str | None = None,
    **kwargs: Any,
) -> None:
    """Initializes a Table element.

    The table can optionally be pre-filled with a specified number of rows
    and cells.

    Args:
        name: The name of the table. It is required and
            cannot contain specific characters like `[]*?:/\\`.
            Apostrophes are also forbidden as the first or last character.
        width: The initial number of columns for the table.
        height: The initial number of rows for the table.
        protected: If True, the table is protected. A `protection_key`
            must be provided if this is True.
        protection_key: A hash value of the password for
            table protection.
        printable: If False, the table will not be printed. Defaults to True.
        print_ranges: A list of cell ranges
            (e.g., `['E6:K12', 'P6:R12']`) or a raw string specifying the
            print ranges.
        style: The name of the style to apply to the table.
        **kwargs: Additional keyword arguments for the Element base class.

    Raises:
        ValueError: If `protected` is True but `protection_key` is not provided.

    Note:
        Directly manipulating the XML tree while using the table API may lead
        to inconsistencies.
    """
    super().__init__(**kwargs)
    self._table_cache = TableCache()
    if self._do_init:
        self.name = name or ""
        if protected:
            self.protected = protected
            if protection_key is None:
                raise ValueError(
                    "a protection_key must be provided for protected tables"
                )
            self.protection_key = protection_key
        if not printable:
            self.printable = printable
        if print_ranges:
            self.print_ranges = print_ranges
        if style:
            self.style = style
        # Prefill the table
        if width is not None or height is not None:
            width = int(width or 1)
            height = int(height or 1)
            # Column groups for style information
            columns = Column(repeated=width)
            self._append(columns)
            for _i in range(height):
                row = Row(width)
                self._append(row)
    self._compute_table_cache()

__str__

__str__() -> str
Source code in odfdo/table.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def __str__(self) -> str:
    def write_content(csv_writer: object) -> None:
        for values in self.iter_values():
            line = []
            for value in values:
                if value is None:
                    value = ""
                if isinstance(value, str):
                    value = value.strip()
                line.append(value)
            csv_writer.writerow(line)  # type: ignore[attr-defined]

    out = StringIO(newline=os.linesep)
    csv_writer = csv.writer(
        out,
        delimiter=" ",
        doublequote=False,
        escapechar="\\",
        lineterminator=os.linesep,
        quotechar='"',
        quoting=csv.QUOTE_NONNUMERIC,
    )
    write_content(csv_writer)
    return out.getvalue()

_compute_table_cache

_compute_table_cache() -> None
Source code in odfdo/table.py
419
420
421
422
423
424
425
426
427
def _compute_table_cache(self) -> None:
    idx_repeated_seq = self.elements_repeated_sequence(
        _XP_ROW, "table:number-rows-repeated"
    )
    self._table_cache.make_row_map(idx_repeated_seq)
    idx_repeated_seq = self.elements_repeated_sequence(
        _XP_COLUMN, "table:number-columns-repeated"
    )
    self._table_cache.make_col_map(idx_repeated_seq)

_get_column2

_get_column2(x: int) -> Column | None
Source code in odfdo/table.py
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
def _get_column2(self, x: int) -> Column | None:
    # Outside the defined table
    if x >= self.width:
        return Column()
    idx = self._table_cache.col_idx(x)
    if idx is None:
        return None
    column = self._table_cache.cached_col(idx)
    if column is None:
        column = self._get_element_idx2(_XP_COLUMN_IDX, idx)  # type:ignore[assignment]
        if column is None:
            return None
        self._table_cache.store_col(column, idx)
    return column.clone

_get_columns

_get_columns() -> list[Column]
Source code in odfdo/table.py
1896
1897
def _get_columns(self) -> list[Column]:
    return cast(list[Column], self.get_elements(_XP_COLUMN))

_get_formatted_text_normal

_get_formatted_text_normal(context: dict | None) -> str
Source code in odfdo/table.py
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
def _get_formatted_text_normal(self, context: dict | None) -> str:
    result = []
    for row in self.iter_rows():
        for cell in row.iter_cells():
            value = cell.get_value(try_get_text=False)
            # None ?
            if value is None:
                # Try with get_formatted_text on the elements
                value = []
                for element in cell.children:
                    value.append(element.get_formatted_text(context))
                value = "".join(value)
            else:
                value = str(value)
            result.append(value)
            result.append("\n")
        result.append("\n")
    return "".join(result)

_get_formatted_text_rst

_get_formatted_text_rst(context: dict) -> str
Source code in odfdo/table.py
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
def _get_formatted_text_rst(self, context: dict) -> str:
    context["no_img_level"] += 1
    # Strip the table => We must clone
    table: Table = self.clone  # type: ignore[assignment]
    table.rstrip(aggressive=True)

    # Fill the rows
    rows = []
    cols_nb = 0
    cols_size: dict[int, int] = {}
    for odf_row in table.iter_rows():
        row = []
        for i, cell in enumerate(odf_row.iter_cells()):
            value = cell.get_value(try_get_text=False)
            # None ?
            if value is None:
                # Try with get_formatted_text on the elements
                value = []
                for element in cell.children:
                    value.append(element.get_formatted_text(context))
                value = "".join(value)
            else:
                value = str(value)
            value = value.strip()
            # Strip the empty columns
            if value:
                cols_nb = max(cols_nb, i + 1)
            # Compute the size of each columns (at least 2)
            cols_size[i] = max(cols_size.get(i, 2), len(value))
            # Append
            row.append(value)
        rows.append(row)

    # Nothing ?
    if cols_nb == 0:
        return ""

    # Prevent a crash with empty columns (by example with images)
    for col, size in cols_size.items():
        if size == 0:
            cols_size[col] = 1

    # Update cols_size
    LINE_MAX = 100
    COL_MIN = 16

    free_size = LINE_MAX - (cols_nb - 1) * 3 - 4
    real_size = sum(cols_size[i] for i in range(cols_nb))
    if real_size > free_size:
        factor = float(free_size) / real_size

        for i in range(cols_nb):
            old_size = cols_size[i]

            # The cell is already small
            if old_size <= COL_MIN:
                continue

            new_size = int(factor * old_size)

            if new_size < COL_MIN:
                new_size = COL_MIN
            cols_size[i] = new_size

    # Convert !
    result: list[str] = [""]
    # Construct the first/last line
    line: list[str] = []
    for i in range(cols_nb):
        line.append("=" * cols_size[i])
        line.append(" ")
    line_str = "".join(line)

    # Add the lines
    result.append(line_str)
    for row in rows:
        # Wrap the row
        wrapped_row = []
        for i, value in enumerate(row[:cols_nb]):
            wrapped_value = []
            for part in value.split("\n"):
                # Hack to handle correctly the lists or the directives
                subsequent_indent = ""
                part_lstripped = part.lstrip()
                if part_lstripped.startswith("-") or part_lstripped.startswith(
                    ".."
                ):
                    subsequent_indent = " " * (len(part) - len(part.lstrip()) + 2)
                wrapped_part = wrap(
                    part, width=cols_size[i], subsequent_indent=subsequent_indent
                )
                if wrapped_part:
                    wrapped_value.extend(wrapped_part)
                else:
                    wrapped_value.append("")
            wrapped_row.append(wrapped_value)

        # Append!
        for j in range(max([1] + [len(values) for values in wrapped_row])):
            txt_row: list[str] = []
            for i in range(cols_nb):
                values = wrapped_row[i] if i < len(wrapped_row) else []

                # An empty cell ?
                if len(values) - 1 < j or not values[j]:
                    if i == 0 and j == 0:
                        txt_row.append("..")
                        txt_row.append(" " * (cols_size[i] - 1))
                    else:
                        txt_row.append(" " * (cols_size[i] + 1))
                    continue

                # Not empty
                value = values[j]
                txt_row.append(value)
                txt_row.append(" " * (cols_size[i] - len(value) + 1))
            result.append("".join(txt_row))

    result.append(line_str)
    result.append("")
    result.append("")
    result_str = "\n".join(result)

    context["no_img_level"] -= 1
    return result_str

_get_row2

_get_row2(
    y: int, clone: bool = True, create: bool = True
) -> Row
Source code in odfdo/table.py
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
def _get_row2(self, y: int, clone: bool = True, create: bool = True) -> Row:
    if y >= self.height:
        if create:
            return Row()
        raise ValueError("Row not found")
    row = self._get_row2_base(y)
    if row is None:
        raise ValueError("Row not found")
    if clone:
        return row.clone
    return row

_get_row2_base

_get_row2_base(y: int) -> Row | None
Source code in odfdo/table.py
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
def _get_row2_base(self, y: int) -> Row | None:
    idx = self._table_cache.row_idx(y)
    if idx is None:
        return None
    row: Row | None = self._table_cache.cached_row(idx)
    if row is None:
        row = self._get_element_idx2(_XP_ROW_IDX, idx)  # type: ignore[assignment]
        if row is None:
            return None
        self._table_cache.store_row(row, idx)
    return row

_get_rows

_get_rows() -> list[Row]
Source code in odfdo/table.py
1100
1101
def _get_rows(self) -> list[Row]:
    return cast(list[Row], self.get_elements(_XP_ROW))

_local_append_named_range

_local_append_named_range(named_range: NamedRange) -> None

(internal) Append the named range to the current table.

Source code in odfdo/table.py
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
def _local_append_named_range(self, named_range: NamedRange) -> None:
    """(internal) Append the named range to the current table."""
    named_expressions = cast(
        None | TableNamedExpressions,
        self.get_element(TableNamedExpressions._tag),
    )
    if not named_expressions:
        named_expressions = TableNamedExpressions()
        self._xml_append(named_expressions)
    # exists ?
    current = named_expressions.get_element(
        f'table:named-range[@table:name="{named_range.name}"][1]'
    )
    if current:
        named_expressions.delete(current)
    named_expressions._xml_append(named_range)

_local_delete_named_range

_local_delete_named_range(name: str) -> None

(internal) Delete the Named Range of specified name.

Source code in odfdo/table.py
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
def _local_delete_named_range(self, name: str) -> None:
    """(internal) Delete the Named Range of specified name."""
    named_range = self._local_named_range(name)
    if not named_range:
        return
    named_range.delete()
    named_expressions = cast(
        None | TableNamedExpressions,
        self.get_element(TableNamedExpressions._tag),
    )
    if not named_expressions:
        return
    if named_expressions.is_empty():
        self.delete(named_expressions)

_local_named_range

_local_named_range(name: str) -> NamedRange | None

(internal) Return the local Name Range of the specified name.

Source code in odfdo/table.py
2322
2323
2324
2325
2326
2327
2328
2329
2330
def _local_named_range(self, name: str) -> NamedRange | None:
    """(internal) Return the local Name Range of the specified name."""
    named_range = self.get_elements(
        f'descendant::table:named-expressions/table:named-range[@table:name="{name}"][1]'
    )
    if named_range:
        return cast(NamedRange, named_range[0])
    else:
        return None

_local_named_ranges

_local_named_ranges() -> list[NamedRange]

(internal) Return the list of local Name Ranges.

Source code in odfdo/table.py
2315
2316
2317
2318
2319
2320
def _local_named_ranges(self) -> list[NamedRange]:
    """(internal) Return the list of local Name Ranges."""
    return cast(
        list[NamedRange],
        self.get_elements("descendant::table:named-expressions/table:named-range"),
    )

_local_set_named_range

_local_set_named_range(
    name: str,
    crange: str | tuple | list,
    usage: str | None = None,
) -> None

(internal) Create a Named Range element and insert it in the current table.

Source code in odfdo/table.py
2349
2350
2351
2352
2353
2354
2355
2356
def _local_set_named_range(
    self, name: str, crange: str | tuple | list, usage: str | None = None
) -> None:
    """(internal) Create a Named Range element and insert it in the current
    table.
    """
    named_range = NamedRange(name, crange, self.name, usage)
    self._local_append_named_range(named_range)

_optimize_width_adapt_columns

_optimize_width_adapt_columns(width: int) -> None
Source code in odfdo/table.py
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
def _optimize_width_adapt_columns(self, width: int) -> None:
    # trim columns to match minimal_width
    columns = self._get_columns()
    repeated_cols: list[EText] = cast(
        list[EText],
        self.xpath("table:table-column/@table:number-columns-repeated"),
    )
    unrepeated = len(columns) - len(repeated_cols)
    column_width = sum(int(r) for r in repeated_cols) + unrepeated
    diff = column_width - width
    if diff > 0:
        for column in reversed(columns):  # pragma: nocover
            repeated = column.repeated or 1
            repeated = repeated - diff
            if repeated > 0:
                column.repeated = repeated
                break
            else:
                column.parent.delete(column)  # type: ignore[union-attr]
                diff = -repeated
                if diff == 0:
                    break
    # raz cache of columns
    self._table_cache.clear_col_indexes()
    self._compute_table_cache()

_optimize_width_length

_optimize_width_length() -> int
Source code in odfdo/table.py
983
984
985
986
987
def _optimize_width_length(self) -> int:
    try:
        return max(row.minimized_width() for row in self._get_rows())
    except ValueError:
        return 0

_optimize_width_rstrip_rows

_optimize_width_rstrip_rows(width: int) -> None
Source code in odfdo/table.py
989
990
991
def _optimize_width_rstrip_rows(self, width: int) -> None:
    for row in self._get_rows():
        row.force_width(width)

_optimize_width_trim_rows

_optimize_width_trim_rows() -> None
Source code in odfdo/table.py
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
def _optimize_width_trim_rows(self) -> None:
    count = -1  # to keep one empty row
    for row in reversed(self._get_rows()):
        if row.is_empty(aggressive=False):
            count += 1
        else:
            break
    if count > 0:
        for row in reversed(self._get_rows()):  # pragma: nocover
            row.parent.delete(row)  # type: ignore[union-attr]
            count -= 1
            if count <= 0:
                break
    try:
        last_row = self._get_rows()[-1]
        last_row._set_repeated(None)
    except IndexError:
        pass
    # raz cache of rows
    self._table_cache.clear_row_indexes()

_translate_cell_coordinates

_translate_cell_coordinates(
    coord: tuple | list | str,
) -> tuple[int | None, int | None]
Source code in odfdo/table.py
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
def _translate_cell_coordinates(
    self,
    coord: tuple | list | str,
) -> tuple[int | None, int | None]:
    # we want an x,y result
    coord = convert_coordinates(coord)
    if len(coord) == 2:
        x, y = coord
    # If we got an area, take the first cell
    elif len(coord) == 4:
        x, y, _z, _t = coord
    else:
        raise ValueError(str(coord))
    if x and x < 0:
        x = increment(x, self.width)
    if y and y < 0:
        y = increment(y, self.height)
    return (x, y)

_translate_column_coordinates

_translate_column_coordinates(
    coord: tuple | list | str,
) -> tuple[int | None, ...]
Source code in odfdo/table.py
392
393
394
395
396
397
398
def _translate_column_coordinates(
    self,
    coord: tuple | list | str,
) -> tuple[int | None, ...]:
    if isinstance(coord, str):
        return self._translate_column_coordinates_str(coord)
    return self._translate_column_coordinates_list(coord)

_translate_column_coordinates_list

_translate_column_coordinates_list(
    coord: tuple | list,
) -> tuple[int | None, ...]
Source code in odfdo/table.py
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
def _translate_column_coordinates_list(
    self,
    coord: tuple | list,
) -> tuple[int | None, ...]:
    width = self.width
    height = self.height
    # assuming we got int values
    if len(coord) == 1:
        # It is a column
        x = coord[0]
        if x and x < 0:
            x = increment(x, width)
        return (x, None, x, None)
    if len(coord) == 2:
        # It is a column range, not a cell, because context is table
        x = coord[0]
        if x and x < 0:
            x = increment(x, width)
        z = coord[1]
        if z and z < 0:
            z = increment(z, width)
        return (x, None, z, None)
    # should be 4 int
    x, y, z, t = coord
    if x and x < 0:
        x = increment(x, width)
    if y and y < 0:
        y = increment(y, height)
    if z and z < 0:
        z = increment(z, width)
    if t and t < 0:
        t = increment(t, height)
    return (x, y, z, t)

_translate_column_coordinates_str

_translate_column_coordinates_str(
    coord_str: str,
) -> tuple[int | None, ...]
Source code in odfdo/table.py
345
346
347
348
349
350
351
352
353
354
355
356
def _translate_column_coordinates_str(
    self,
    coord_str: str,
) -> tuple[int | None, ...]:
    coord = convert_coordinates(coord_str)
    # resulting coord has never <0 value
    if len(coord) == 2:
        x, y = coord
        # extent to an area :
        return (x, y, x, y)
    x, y, z, t = coord
    return (x, y, z, t)

_translate_table_coordinates

_translate_table_coordinates(
    coord: tuple | list | str,
) -> tuple[int | None, ...]
Source code in odfdo/table.py
337
338
339
340
341
342
343
def _translate_table_coordinates(
    self,
    coord: tuple | list | str,
) -> tuple[int | None, ...]:
    if isinstance(coord, str):
        return self._translate_table_coordinates_str(coord)
    return self._translate_table_coordinates_list(coord)

_translate_table_coordinates_list

_translate_table_coordinates_list(
    coord: tuple | list,
) -> tuple[int | None, ...]
Source code in odfdo/table.py
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
def _translate_table_coordinates_list(
    self,
    coord: tuple | list,
) -> tuple[int | None, ...]:
    height = self.height
    width = self.width
    # assuming we got int values
    if len(coord) == 1:
        # It is a row
        y = coord[0]
        if y and y < 0:
            y = increment(y, height)
        return (None, y, None, y)
    if len(coord) == 2:
        # It is a row range, not a cell, because context is table
        y = coord[0]
        if y and y < 0:
            y = increment(y, height)
        t = coord[1]
        if t and t < 0:
            t = increment(t, height)
        return (None, y, None, t)
    # should be 4 int
    x, y, z, t = coord
    if x and x < 0:
        x = increment(x, width)
    if y and y < 0:
        y = increment(y, height)
    if z and z < 0:
        z = increment(z, width)
    if t and t < 0:
        t = increment(t, height)
    return (x, y, z, t)

_translate_table_coordinates_str

_translate_table_coordinates_str(
    coord_str: str,
) -> tuple[int | None, ...]
Source code in odfdo/table.py
324
325
326
327
328
329
330
331
332
333
334
335
def _translate_table_coordinates_str(
    self,
    coord_str: str,
) -> tuple[int | None, ...]:
    coord = convert_coordinates(coord_str)
    # resulting coord has never <0 value
    if len(coord) == 2:
        x, y = coord
        # extent to an area :
        return (x, y, x, y)
    x, y, z, t = coord
    return (x, y, z, t)

_translate_x_from_any

_translate_x_from_any(x: str | int) -> int
Source code in odfdo/table.py
583
584
def _translate_x_from_any(self, x: str | int) -> int:
    return translate_from_any(x, self.width, 0)

_translate_y_from_any

_translate_y_from_any(y: str | int) -> int

Translate a ‘y’ coordinate from any format to a 0-based integer index.

Parameters:

Name Type Description Default
y str | int

The Y-coordinate, which can be a 1-based integer or a string.

required

Returns:

Name Type Description
int int

The 0-based integer Y-coordinate.

Source code in odfdo/table.py
278
279
280
281
282
283
284
285
286
287
288
def _translate_y_from_any(self, y: str | int) -> int:
    """Translate a 'y' coordinate from any format to a 0-based integer index.

    Args:
        y: The Y-coordinate, which can be a 1-based integer or a string.

    Returns:
        int: The 0-based integer Y-coordinate.
    """
    # "3" (counting from 1) -> 2 (counting from 0)
    return translate_from_any(y, self.height, 1)

_update_width

_update_width(row: Row) -> None

Synchronize the number of columns if the row is bigger.

Append, don’t insert, not to disturb the current layout.

Source code in odfdo/table.py
429
430
431
432
433
434
435
436
def _update_width(self, row: Row) -> None:
    """Synchronize the number of columns if the row is bigger.

    Append, don't insert, not to disturb the current layout.
    """
    diff = row.width - self.width
    if diff > 0:
        self.append_column(Column(repeated=diff))

_yield_odf_columns

_yield_odf_columns() -> Iterator[Column]
Source code in odfdo/table.py
1936
1937
1938
1939
1940
1941
1942
1943
1944
def _yield_odf_columns(self) -> Iterator[Column]:
    for column in self._get_columns():
        if column.repeated is None:
            yield column
        else:
            for _ in range(column.repeated):
                column_copy = column.clone
                column_copy.repeated = None
                yield column_copy

_yield_odf_rows

_yield_odf_rows() -> Iterator[Row]
Source code in odfdo/table.py
1184
1185
1186
1187
1188
1189
1190
1191
1192
def _yield_odf_rows(self) -> Iterator[Row]:
    for row in self._get_rows():
        if row.repeated is None:
            yield row
        else:
            for _ in range(row.repeated):
                row_copy = row.clone
                row_copy.repeated = None
                yield row_copy

append

append(something: Element | str) -> None

Append a Row or Column to the table.

This method dispatches the call to append_row or append_column based on the type of the provided element.

Parameters:

Name Type Description Default
something Element | str

The Row or Column to append.

required
Source code in odfdo/table.py
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
def append(self, something: Element | str) -> None:
    """Append a Row or Column to the table.

    This method dispatches the call to `append_row` or `append_column` based
    on the type of the provided element.

    Args:
        something (Element | str): The Row or Column to append.
    """
    if isinstance(something, Row):
        self.append_row(something)
    elif isinstance(something, Column):
        self.append_column(something)
    else:
        # probably still an error
        self._append(something)

append_cell

append_cell(
    y: int | str,
    cell: Cell | None = None,
    clone: bool = True,
) -> Cell

Append a cell to the end of the row at the given ‘y’ coordinate.

If cell is None, an empty cell is created.

Parameters:

Name Type Description Default
y int | str

The 0-based index of the row to append to.

required
cell Cell | None

The Cell element to append.

None
clone bool

If True (default), a copy of the provided cell is used.

True

Returns:

Name Type Description
Cell Cell

The newly appended cell, with its x and y attributes updated.

Source code in odfdo/table.py
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
def append_cell(
    self,
    y: int | str,
    cell: Cell | None = None,
    clone: bool = True,
) -> Cell:
    """Append a cell to the end of the row at the given 'y' coordinate.

    If `cell` is None, an empty cell is created.

    Args:
        y: The 0-based index of the row to append to.
        cell: The Cell element to append.
        clone: If True (default), a copy of the provided cell is used.

    Returns:
        Cell: The newly appended cell, with its `x` and `y` attributes updated.
    """
    if cell is None:
        cell = Cell()
        clone = False
    if clone:
        cell = cell.clone
    y = self._translate_y_from_any(y)
    row = self._get_row2(y)
    row.y = y
    cell_back = row.append_cell(cell, clone=False)
    self.set_row(y, row)
    # Update width if necessary
    self._update_width(row)
    return cell_back

append_column

append_column(
    column: Column | None = None,
    _repeated: int | None = None,
) -> Column

Append a column to the end of the table.

If no column is provided, an empty one is created. ODF columns do not contain cells, only style information.

Parameters:

Name Type Description Default
column Column | None

The Column element to append.

None
_repeated int | None

The number of times the column is repeated.

None

Returns:

Name Type Description
Column Column

The newly appended column, with its x attribute updated.

Source code in odfdo/table.py
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
def append_column(
    self,
    column: Column | None = None,
    _repeated: int | None = None,
) -> Column:
    """Append a column to the end of the table.

    If no `column` is provided, an empty one is created. ODF columns do not
    contain cells, only style information.

    Args:
        column: The Column element to append.
        _repeated: The number of times the column is repeated.

    Returns:
        Column: The newly appended column, with its `x` attribute updated.
    """
    if column is None:
        column = Column()
        _repeated = 1
    else:
        column = column.clone
    odf_idx = self._table_cache.col_map_length() - 1
    if odf_idx < 0:
        position = 0
    else:
        last_column = self._get_element_idx2(_XP_COLUMN_IDX, odf_idx)
        if last_column is None:
            raise ValueError
        position = self.index(last_column) + 1
    column.x = self.width
    self.insert(column, position=position)
    # Repetitions are accepted
    if _repeated is None:
        _repeated = column.repeated or 1
    self._table_cache.insert_col_map_once(_repeated)
    # No need to update row widths
    return column

append_named_range

append_named_range(
    named_range: NamedRange, global_scope: bool = True
) -> None

Append a named range to the document, replacing any existing one with the same name.

Named ranges can be local or global. Global named ranges are stored at the body level, so do not call this on a cloned table for global access.

Parameters:

Name Type Description Default
named_range NamedRange

The NamedRange element to append.

required
global_scope bool

If True (default), appends to the document body. If False, appends to the current table.

True
Source code in odfdo/table.py
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
def append_named_range(
    self, named_range: NamedRange, global_scope: bool = True
) -> None:
    """Append a named range to the document, replacing any existing one with the same name.

    Named ranges can be local or global. Global named ranges are stored at
    the body level, so do not call this on a cloned table for global access.

    Args:
        named_range: The NamedRange element to append.
        global_scope: If True (default), appends to the document body.
            If False, appends to the current table.
    """
    if global_scope:
        body = self.document_body
        if not body:
            raise ValueError("Table is not inside a document")
        if not body.allow_named_range:
            msg = (
                "Document must be of type Chart, Drawing, "
                "Presentation, Spreadsheet or Text"
            )
            raise TypeError(msg)
        body.append_named_range(named_range)  # type: ignore[attr-defined]
    else:
        self._local_append_named_range(named_range)

append_row

append_row(
    row: Row | None = None,
    clone: bool = True,
    _repeated: int | None = None,
) -> Row

Append a row to the end of the table.

If no row is provided, an empty one is created. Note that columns are automatically created when the first row is inserted into an empty table, so it’s best to insert a filled row first.

Parameters:

Name Type Description Default
row Row | None

The Row element to append.

None
clone bool

If True (default), a copy of the provided row is used.

True
_repeated int | None

The number of times the row is repeated.

None

Returns:

Name Type Description
Row Row

The newly appended row, with its y attribute updated.

Source code in odfdo/table.py
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
def append_row(
    self,
    row: Row | None = None,
    clone: bool = True,
    _repeated: int | None = None,
) -> Row:
    """Append a row to the end of the table.

    If no `row` is provided, an empty one is created. Note that columns are
    automatically created when the first row is inserted into an empty table,
    so it's best to insert a filled row first.

    Args:
        row: The Row element to append.
        clone: If True (default), a copy of the provided row is used.
        _repeated: The number of times the row is repeated.

    Returns:
        Row: The newly appended row, with its `y` attribute updated.
    """
    if row is None:
        row = Row()
        _repeated = 1
    elif clone:
        row = row.clone
    # Appending a repeated row accepted
    # Do not insert next to the last row because it could be in a group
    self._append(row)
    if _repeated is None:
        _repeated = row.repeated or 1
    self._table_cache.insert_row_map_once(_repeated)
    row.y = self.height - 1
    # Initialize columns
    if not self._get_columns():
        repeated = row.width
        self.insert(Column(repeated=repeated), position=0)
        self._compute_table_cache()
    # Update width if necessary
    self._update_width(row)
    return row

clear

clear() -> None

Remove all children, text content, and attributes from the table element.

Source code in odfdo/table.py
273
274
275
276
def clear(self) -> None:
    """Remove all children, text content, and attributes from the table element."""
    self._xml_element.clear()
    self._table_cache = TableCache()

del_span

del_span(area: str | tuple | list) -> bool

Delete a cell span.

The area should specify the top-left cell of the spanned area.

Parameters:

Name Type Description Default
area str | tuple | list

The coordinates of the top-left cell of the spanned area.

required

Returns:

Name Type Description
bool bool

True if the span was successfully deleted, False otherwise.

Source code in odfdo/table.py
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
def del_span(self, area: str | tuple | list) -> bool:
    """Delete a cell span.

    The `area` should specify the top-left cell of the spanned area.

    Args:
        area: The coordinates of the top-left cell
            of the spanned area.

    Returns:
        bool: True if the span was successfully deleted, False otherwise.
    """
    # get area
    digits = convert_coordinates(area)
    if len(digits) == 4:
        x, y, _z, _t = digits
    else:
        x, y = digits
    if x is None:
        raise ValueError
    if y is None:
        raise ValueError
    start = x, y
    # check for previous span
    cell0 = self.get_cell(start)
    nb_cols = cell0.get_attribute_integer("table:number-columns-spanned")
    if nb_cols is None:
        return False
    nb_rows = cell0.get_attribute_integer("table:number-rows-spanned")
    if nb_rows is None:
        return False
    z = x + nb_cols - 1
    t = y + nb_rows - 1
    cells = self.get_cells((x, y, z, t))
    cells[0][0].del_attribute("table:number-columns-spanned")
    cells[0][0].del_attribute("table:number-rows-spanned")
    for cell in cells[0][1:]:
        cell.tag = "table:table-cell"
    for row in cells[1:]:
        for cell in row:
            cell.tag = "table:table-cell"
    # replace cells in table
    self.set_cells(cells, coord=start, clone=False)
    return True

delete_cell

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

Delete the cell at the given coordinates, shifting subsequent cells to the left.

To clear a cell’s value without deleting it, use set_value() with an empty value.

Parameters:

Name Type Description Default
coord tuple | list | str

The coordinates of the cell to delete.

required
Source code in odfdo/table.py
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
def delete_cell(self, coord: tuple | list | str) -> None:
    """Delete the cell at the given coordinates, shifting subsequent cells to the left.

    To clear a cell's value without deleting it, use `set_value()` with an
    empty value.

    Args:
        coord: The coordinates of the cell to delete.
    """
    x, y = self._translate_cell_coordinates(coord)
    if x is None:
        raise ValueError
    if y is None:
        raise ValueError
    # Outside the defined table
    if y >= self.height:
        return
    # Inside the defined table
    row = self._get_row2_base(y)
    if row is None:
        raise ValueError
    row.delete_cell(x)

delete_column

delete_column(x: int | str) -> None

Delete the column at the given position.

Parameters:

Name Type Description Default
x int | str

The 0-based index or alphabetical representation of the column to delete.

required
Source code in odfdo/table.py
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
def delete_column(self, x: int | str) -> None:
    """Delete the column at the given position.

    Args:
        x: The 0-based index or alphabetical representation
            of the column to delete.
    """
    x = self._translate_x_from_any(x)
    # Outside the defined table
    if x >= self.width:
        return
    # Inside the defined table
    self._table_cache.delete_col_in_cache(x, self)
    # Update width
    width = self.width
    for row in self._get_rows():
        if row.width >= width:
            row.delete_cell(x)

delete_named_range

delete_named_range(
    name: str, global_scope: bool = True
) -> None

Delete the named range with the specified name.

Named ranges can be local or global. Global named ranges are stored at the body level, so do not call this on a cloned table for global access.

Parameters:

Name Type Description Default
name str

The name of the named range to delete.

required
global_scope bool

If True (default), searches the entire document. If False, searches only the current table.

True
Source code in odfdo/table.py
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
def delete_named_range(self, name: str, global_scope: bool = True) -> None:
    """Delete the named range with the specified name.

    Named ranges can be local or global. Global named ranges are stored at
    the body level, so do not call this on a cloned table for global access.

    Args:
        name: The name of the named range to delete.
        global_scope: If True (default), searches the entire document.
            If False, searches only the current table.
    """
    name = name.strip()
    if not name:
        raise ValueError("Name required")
    if global_scope:
        body = self.document_body
        if not body:
            raise ValueError("Table is not inside a document")
        if not body.allow_named_range:
            msg = (
                "Document must be of type Chart, Drawing, "
                "Presentation, Spreadsheet or Text"
            )
            raise TypeError(msg)
        body.delete_named_range(name)  # type: ignore[attr-defined]
    else:
        self._local_delete_named_range(name)

delete_row

delete_row(y: int | str) -> None

Delete the row at the given ‘y’ position (0-based).

Parameters:

Name Type Description Default
y int | str

The 0-based index of the row to delete.

required
Source code in odfdo/table.py
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
def delete_row(self, y: int | str) -> None:
    """Delete the row at the given 'y' position (0-based).

    Args:
        y: The 0-based index of the row to delete.
    """
    y = self._translate_y_from_any(y)
    # Outside the defined table
    if y >= self.height:
        return
    # Inside the defined table
    self._table_cache.delete_row_in_cache(y, self)

extend_rows

extend_rows(rows: list[Row] | None = None) -> None

Append a list of rows to the end of the table.

Parameters:

Name Type Description Default
rows list[Row] | None

A list of Row elements to append.

None
Source code in odfdo/table.py
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
def extend_rows(self, rows: list[Row] | None = None) -> None:
    """Append a list of rows to the end of the table.

    Args:
        rows: A list of Row elements to append.
    """
    if rows is None:
        rows = []
    self.extend(rows)
    self._compute_table_cache()
    # Update width if necessary
    width = self.width
    for row in self.iter_rows():
        if row.width > width:
            width = row.width
    diff = width - self.width
    if diff > 0:
        self.append_column(Column(repeated=diff))

from_csv classmethod

from_csv(
    content: str,
    name: str,
    style: str | None = None,
    **fmtparams: Any,
) -> Table

Import a CSV string into a new Table object.

The CSV format can be auto-detected to a certain extent. Use **fmtparams to define csv.reader parameters for more control.

Parameters:

Name Type Description Default
content str

The CSV content as a string.

required
name str

The name of the table to create.

required
style str | None

The style to apply to the table.

None
**fmtparams Any

Additional keyword arguments for the csv.reader method.

{}

Returns:

Name Type Description
Table Table

A new Table object populated with the CSV data.

Source code in odfdo/table.py
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
@classmethod
def from_csv(
    cls,
    content: str,
    name: str,
    style: str | None = None,
    **fmtparams: Any,
) -> Table:
    """Import a CSV string into a new Table object.

    The CSV format can be auto-detected to a certain extent. Use `**fmtparams`
    to define `csv.reader` parameters for more control.

    Args:
        content: The CSV content as a string.
        name: The name of the table to create.
        style: The style to apply to the table.
        **fmtparams: Additional keyword arguments for the `csv.reader` method.

    Returns:
        Table: A new Table object populated with the CSV data.
    """
    data = content.splitlines(True)
    # Sniff the dialect
    sample = "".join(data[:2048])
    dialect = csv.Sniffer().sniff(sample)
    # Make the rows
    reader = csv.reader(data, dialect=dialect, **fmtparams)
    table = cls(name, style=style)
    encoding = fmtparams.get("encoding", "utf-8")
    for line in reader:
        row = Row()
        # rstrip line
        while line and not line[-1].strip():
            line.pop()
        for value in line:
            cell = Cell(_get_python_value(value, encoding))
            row.append_cell(cell, clone=False)
        table.append_row(row, clone=False)
    return table

get_cell

get_cell(
    coord: tuple | list | str,
    clone: bool = True,
    keep_repeated: bool = True,
) -> Cell

Get the cell at the given coordinates (e.g., (0, 2) or “C1”).

A copy of the cell is returned by default; use set_cell() to apply changes.

Parameters:

Name Type Description Default
coord tuple | list | str

The 0-based (x, y) coordinates or an alphanumeric string like “A1”.

required
clone bool

If True (default), a copy of the cell is returned.

True
keep_repeated bool

If True (default), retains the repeated property of the cell.

True

Returns:

Name Type Description
Cell Cell

The Cell element at the specified coordinates.

Source code in odfdo/table.py
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
def get_cell(
    self,
    coord: tuple | list | str,
    clone: bool = True,
    keep_repeated: bool = True,
) -> Cell:
    """Get the cell at the given coordinates (e.g., (0, 2) or "C1").

    A copy of the cell is returned by default; use `set_cell()` to apply changes.

    Args:
        coord: The 0-based (x, y) coordinates or an
            alphanumeric string like "A1".
        clone: If True (default), a copy of the cell is returned.
        keep_repeated: If True (default), retains the repeated
            property of the cell.

    Returns:
        Cell: The Cell element at the specified coordinates.
    """
    x, y = self._translate_cell_coordinates(coord)
    if x is None:
        raise ValueError
    if y is None:
        raise ValueError
    # Outside the defined table
    if y >= self.height:
        cell = Cell()
    else:
        # Inside the defined table
        row = self._get_row2_base(y)
        if row is None:
            raise ValueError
        read_cell = row.get_cell(x, clone=clone)
        if read_cell is None:
            raise ValueError
        cell = read_cell
        if not keep_repeated and cell.get_attribute(
            "table:number-columns-repeated"
        ):
            cell._set_repeated(None)
    cell.x = x
    cell.y = y
    return cell

get_cells

get_cells(
    coord: tuple | list | str | None = None,
    cell_type: str | None = None,
    style: str | None = None,
    content: str | None = None,
    flat: bool = False,
) -> list

Get a list of cells, optionally from a specified area and filtered by criteria.

Parameters:

Name Type Description Default
coord tuple | list | str | None

The coordinates of the area to parse.

None
cell_type str | None

Filters by value type. ‘all’ gets any non-empty cell.

None
style str | None

Filters by cell style name.

None
content str | None

A regex to match against cell content.

None
flat bool

If True, returns a single flat list of cells. Defaults to False.

False

Returns:

Name Type Description
list list

A list of lists of Cell elements, or a flat list if flat is True.

Source code in odfdo/table.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
def get_cells(
    self,
    coord: tuple | list | str | None = None,
    cell_type: str | None = None,
    style: str | None = None,
    content: str | None = None,
    flat: bool = False,
) -> list:
    """Get a list of cells, optionally from a specified area and filtered by criteria.

    Args:
        coord: The coordinates of the area to parse.
        cell_type: Filters by value type. 'all' gets any non-empty cell.
        style: Filters by cell style name.
        content: A regex to match against cell content.
        flat: If True, returns a single flat list of cells. Defaults to False.

    Returns:
        list: A list of lists of Cell elements, or a flat list if `flat` is True.
    """
    if coord:
        x, y, z, t = self._translate_table_coordinates(coord)
    else:
        x = y = z = t = None
    if flat:
        cells: list[Cell] = []
        for row in self.iter_rows(start=y, end=t):
            row_cells = row.get_cells(
                coord=(x, z),
                cell_type=cell_type,
                style=style,
                content=content,
            )
            cells.extend(row_cells)
        return cells
    else:
        lcells: list[list[Cell]] = []
        for row in self.iter_rows(start=y, end=t):
            row_cells = row.get_cells(
                coord=(x, z),
                cell_type=cell_type,
                style=style,
                content=content,
            )
            lcells.append(row_cells)
        return lcells

get_column

get_column(x: int | str) -> Column

Get the column at the given ‘x’ position (0-based or alphabetical).

ODF columns primarily store style information, not cell content. A copy of the column is returned; use set_column() to apply any changes.

Parameters:

Name Type Description Default
x int | str

The 0-based index or alphabetical representation (e.g., “C”) of the column.

required

Returns:

Name Type Description
Column Column

The Column element at the specified position.

Source code in odfdo/table.py
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
def get_column(self, x: int | str) -> Column:
    """Get the column at the given 'x' position (0-based or alphabetical).

    ODF columns primarily store style information, not cell content. A copy of
    the column is returned; use `set_column()` to apply any changes.

    Args:
        x: The 0-based index or alphabetical representation
            (e.g., "C") of the column.

    Returns:
        Column: The Column element at the specified position.
    """
    x = self._translate_x_from_any(x)
    column = self._get_column2(x)
    if column is None:
        raise ValueError
    column.x = x
    return column

get_column_cells

get_column_cells(
    x: int | str,
    style: str | None = None,
    content: str | None = None,
    cell_type: str | None = None,
    complete: bool = False,
) -> list[Cell | None]

Get a list of cells from the column at the given ‘x’ position.

Parameters:

Name Type Description Default
x int | str

The 0-based index or alphabetical representation of the column.

required
style str | None

Filters by cell style name.

None
content str | None

A regex to match against cell content.

None
cell_type str | None

Filters by value type. ‘all’ gets any non-empty cell.

None
complete bool

If True, missing cells are represented by None.

False

Returns:

Type Description
list[Cell | None]

list[Cell | None]: A list of Cell elements or None.

Source code in odfdo/table.py
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
def get_column_cells(
    self,
    x: int | str,
    style: str | None = None,
    content: str | None = None,
    cell_type: str | None = None,
    complete: bool = False,
) -> list[Cell | None]:
    """Get a list of cells from the column at the given 'x' position.

    Args:
        x: The 0-based index or alphabetical representation
            of the column.
        style: Filters by cell style name.
        content: A regex to match against cell content.
        cell_type: Filters by value type. 'all' gets any
            non-empty cell.
        complete: If True, missing cells are represented by None.

    Returns:
        list[Cell | None]: A list of Cell elements or None.
    """
    x = self._translate_x_from_any(x)
    if cell_type:
        cell_type = cell_type.lower().strip()
    cells: list[Cell | None] = []
    if not style and not content and not cell_type:
        for row in self.iter_rows():
            cells.append(row.get_cell(x, clone=True))
        return cells
    for row in self.iter_rows():
        cell = row.get_cell(x, clone=True)
        if cell is None:
            raise ValueError
        # Filter the cells by cell_type
        if cell_type:
            ctype = cell.type
            if not ctype or not (ctype == cell_type or cell_type == "all"):
                if complete:
                    cells.append(None)
                continue
        # Filter the cells with the regex
        if content and not cell.match(content):
            if complete:
                cells.append(None)
            continue
        # Filter the cells with the style
        if style and style != cell.style:
            if complete:
                cells.append(None)
            continue
        cells.append(cell)
    return cells

get_column_values

get_column_values(
    x: int | str,
    cell_type: str | None = None,
    complete: bool = True,
    get_type: bool = False,
) -> list[Any]

Get the list of Python values for the cells in the column at the given ‘x’ position.

Parameters:

Name Type Description Default
x int | str

The 0-based index or alphabetical representation of the column.

required
cell_type str | None

Filters by value type. ‘all’ gets any non-empty cell.

None
complete bool

If True (default), missing values are replaced by None.

True
get_type bool

If True, returns tuples of (value, odf_type).

False

Returns:

Type Description
list[Any]

list[Any]: A list of Python values or (value, odf_type) tuples.

Source code in odfdo/table.py
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
def get_column_values(
    self,
    x: int | str,
    cell_type: str | None = None,
    complete: bool = True,
    get_type: bool = False,
) -> list[Any]:
    """Get the list of Python values for the cells in the column at the given 'x' position.

    Args:
        x: The 0-based index or alphabetical representation of the column.
        cell_type: Filters by value type. 'all' gets any non-empty cell.
        complete: If True (default), missing values are replaced by None.
        get_type: If True, returns tuples of (value, odf_type).

    Returns:
        list[Any]: A list of Python values or (value, odf_type) tuples.
    """
    cells = self.get_column_cells(
        x, style=None, content=None, cell_type=cell_type, complete=complete
    )
    values: list[Any] = []
    for cell in cells:
        if cell is None:
            if complete:
                if get_type:
                    values.append((None, None))
                else:
                    values.append(None)
            continue
        if cell_type:
            ctype = cell.type
            if not ctype or not (ctype == cell_type or cell_type == "all"):
                if complete:
                    if get_type:
                        values.append((None, None))
                    else:
                        values.append(None)
                continue
        values.append(cell.get_value(get_type=get_type))
    return values

get_columns

get_columns(
    coord: tuple | list | str | None = None,
    style: str | None = None,
) -> list[Column]

Get a list of columns matching the specified criteria.

The returned columns are copies; use set_column() to apply any changes.

Parameters:

Name Type Description Default
coord tuple | list | str | None

The coordinates of the columns to retrieve.

None
style str | None

The name of a style to filter columns by.

None

Returns:

Type Description
list[Column]

list[Column]: A list of matching Column elements.

Source code in odfdo/table.py
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
def get_columns(
    self,
    coord: tuple | list | str | None = None,
    style: str | None = None,
) -> list[Column]:
    """Get a list of columns matching the specified criteria.

    The returned columns are copies; use `set_column()` to apply any changes.

    Args:
        coord: The coordinates of the columns
            to retrieve.
        style: The name of a style to filter columns by.

    Returns:
        list[Column]: A list of matching Column elements.
    """
    if coord:
        x, _y, _z, t = self._translate_column_coordinates(coord)
    else:
        x = t = None
    if not style:
        return list(self.iter_columns(start=x, end=t))
    columns = []
    for column in self.iter_columns(start=x, end=t):
        if style != column.style:
            continue
        columns.append(column)
    return columns

get_elements

get_elements(xpath_query: XPath | str) -> list[Element]

Get a list of elements matching the XPath query.

The query is applied to the current table element.

Parameters:

Name Type Description Default
xpath_query XPath | str

The XPath query string or a compiled XPath object.

required

Returns:

Type Description
list[Element]

list[Element]: A list of matching elements, cloned from the original XML tree.

Source code in odfdo/table.py
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
def get_elements(self, xpath_query: XPath | str) -> list[Element]:
    """Get a list of elements matching the XPath query.

    The query is applied to the current table element.

    Args:
        xpath_query: The XPath query string or a compiled
            XPath object.

    Returns:
        list[Element]: A list of matching elements, cloned from the
            original XML tree.
    """
    if isinstance(xpath_query, str):
        elements = xpath_return_elements(
            xpath_compile(xpath_query),
            self._xml_element,
        )
    else:
        elements = xpath_return_elements(
            xpath_query,
            self._xml_element,
        )
    cache = (self._table_cache, None)
    return [Element.from_tag_for_clone(e, cache) for e in elements]

get_formatted_text

get_formatted_text(context: dict | None = None) -> str

Return a formatted text representation of the table.

If the context dictionary contains ‘rst_mode’: True, the table will be formatted as a reStructuredText grid table. Otherwise, it returns a simple string with cell values.

Parameters:

Name Type Description Default
context dict | None

A dictionary of context variables for formatting.

None

Returns:

Name Type Description
str str

The formatted text content of the table.

Source code in odfdo/table.py
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
def get_formatted_text(self, context: dict | None = None) -> str:
    """Return a formatted text representation of the table.

    If the `context` dictionary contains 'rst_mode': True, the table will
    be formatted as a reStructuredText grid table. Otherwise, it returns
    a simple string with cell values.

    Args:
        context: A dictionary of context variables for formatting.

    Returns:
        str: The formatted text content of the table.
    """
    if not context:
        context = {}
    if context.get("rst_mode"):
        return self._get_formatted_text_rst(context)
    return self._get_formatted_text_normal(context)

get_named_range

get_named_range(
    name: str, global_scope: bool = True
) -> NamedRange | None

Return the named range with the specified name.

Named ranges can be local or global. Global named ranges are stored at the body level, so do not call this on a cloned table for global access.

Parameters:

Name Type Description Default
name str

The name of the named range object.

required
global_scope bool

If True (default), searches the entire document. If False, searches only the current table.

True

Returns:

Type Description
NamedRange | None

NamedRange | None: The matching NamedRange element, or None if not found.

Source code in odfdo/table.py
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
def get_named_range(
    self, name: str, global_scope: bool = True
) -> NamedRange | None:
    """Return the named range with the specified name.

    Named ranges can be local or global. Global named ranges are stored at
    the body level, so do not call this on a cloned table for global access.

    Args:
        name: The name of the named range object.
        global_scope: If True (default), searches the entire document.
            If False, searches only the current table.

    Returns:
        NamedRange | None: The matching NamedRange element, or None if not found.
    """
    if global_scope:
        body = self.document_body
        if not body:
            raise ValueError("Table is not inside a document")
        if not body.allow_named_range:
            return None
        nr: NamedRange | None = body.get_named_range(name)  # type: ignore[attr-defined]

    else:
        nr = self._local_named_range(name)
    return nr

get_named_ranges

get_named_ranges(
    table_name: str | list[str] | None = None,
    global_scope: bool = True,
) -> list[NamedRange]

Return a list of named ranges, optionally filtered by scope and table name.

Named ranges can be local to a table or global to the document. Global named ranges are stored at the body level, so this method should not be called on a cloned table if access to global named ranges is required.

Parameters:

Name Type Description Default
table_name str | list[str] | None

A name or list of names of tables to filter by.

None
global_scope bool

If True (default), searches the entire document. If False, searches only the current table.

True

Returns:

Type Description
list[NamedRange]

list[NamedRange]: A list of matching NamedRange elements.

Source code in odfdo/table.py
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
def get_named_ranges(
    self,
    table_name: str | list[str] | None = None,
    global_scope: bool = True,
) -> list[NamedRange]:
    """Return a list of named ranges, optionally filtered by scope and table name.

    Named ranges can be local to a table or global to the document. Global
    named ranges are stored at the body level, so this method should not be
    called on a cloned table if access to global named ranges is required.

    Args:
        table_name: A name or list of names
            of tables to filter by.
        global_scope: If True (default), searches the entire document.
            If False, searches only the current table.

    Returns:
        list[NamedRange]: A list of matching NamedRange elements.
    """
    if global_scope:
        body = self.document_body
        if not body or not body.allow_named_range:
            return []
        named_ranges = body.get_named_ranges()  # type: ignore[attr-defined]
    else:
        named_ranges = self._local_named_ranges()
    if not table_name:
        return named_ranges  # type: ignore[no-any-return]
    filter_ = []
    if isinstance(table_name, str):
        filter_.append(table_name)
    elif isiterable(table_name):
        filter_.extend(table_name)
    else:
        msg = f"table_name must be string or Iterable, not {type(table_name)!r}"
        raise ValueError(msg)
    return [nr for nr in named_ranges if nr.table_name in filter_]

get_row

get_row(
    y: int | str, clone: bool = True, create: bool = True
) -> Row

Get the row at the given ‘y’ position (0-based).

A copy of the row is returned; use set_row() to apply any changes.

Parameters:

Name Type Description Default
y int | str

The 0-based index or string representation of the row.

required
clone bool

If True (default), a copy of the row is returned.

True
create bool

If True (default) and the row does not exist, a new empty row is created.

True

Returns:

Name Type Description
Row Row

The Row element at the specified position.

Source code in odfdo/table.py
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
def get_row(self, y: int | str, clone: bool = True, create: bool = True) -> Row:
    """Get the row at the given 'y' position (0-based).

    A copy of the row is returned; use `set_row()` to apply any changes.

    Args:
        y: The 0-based index or string representation of the row.
        clone: If True (default), a copy of the row is returned.
        create: If True (default) and the row does not exist, a new
            empty row is created.

    Returns:
        Row: The Row element at the specified position.
    """
    # fixme : keep repeat ? maybe an option to functions : "raw=False"
    y = self._translate_y_from_any(y)
    row = self._get_row2(y, clone=clone, create=create)
    if row is None:
        raise ValueError("Row not found")
    row.y = y
    return row

get_row_sub_elements

get_row_sub_elements(y: int | str) -> list[Any]

Get the list of Element values for the cells of the row at the given ‘y’ position.

Missing values are replaced by None.

Parameters:

Name Type Description Default
y int | str

The 0-based index of the row.

required

Returns:

Type Description
list[Any]

list[Any]: A list of sub-elements from each cell in the row.

Source code in odfdo/table.py
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
def get_row_sub_elements(self, y: int | str) -> list[Any]:
    """Get the list of Element values for the cells of the row at the given 'y' position.

    Missing values are replaced by None.

    Args:
        y: The 0-based index of the row.

    Returns:
        list[Any]: A list of sub-elements from each cell in the row.
    """
    values = self.get_row(y, clone=False).get_sub_elements()
    values.extend([None] * (self.width - len(values)))
    return values

get_row_values

get_row_values(
    y: int | str,
    cell_type: str | None = None,
    complete: bool = True,
    get_type: bool = False,
) -> list

Get the list of Python values for the cells of the row at the given ‘y’ position.

Parameters:

Name Type Description Default
y int | str

The 0-based index of the row.

required
cell_type str | None

Filters cells by value type (e.g., ‘float’). ‘all’ retrieves any non-empty cell.

None
complete bool

If True (default), missing values are replaced by None.

True
get_type bool

If True, returns tuples of (value, odf_type).

False

Returns:

Name Type Description
list list

A list of Python types or (value, odf_type) tuples.

Source code in odfdo/table.py
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
def get_row_values(
    self,
    y: int | str,
    cell_type: str | None = None,
    complete: bool = True,
    get_type: bool = False,
) -> list:
    """Get the list of Python values for the cells of the row at the given 'y' position.

    Args:
        y: The 0-based index of the row.
        cell_type: Filters cells by value type (e.g., 'float').
            'all' retrieves any non-empty cell.
        complete: If True (default), missing values are replaced by None.
        get_type: If True, returns tuples of (value, odf_type).

    Returns:
        list: A list of Python types or (value, odf_type) tuples.
    """
    values = self.get_row(y, clone=False).get_values(
        cell_type=cell_type, complete=complete, get_type=get_type
    )
    # complete row to match column width
    if complete:
        if get_type:
            values.extend([(None, None)] * (self.width - len(values)))
        else:
            values.extend([None] * (self.width - len(values)))
    return values

get_rows

get_rows(
    coord: tuple | list | str | None = None,
    style: str | None = None,
    content: str | None = None,
) -> list[Row]

Get a list of rows matching the specified criteria.

Parameters:

Name Type Description Default
coord tuple | list | str | None

The coordinates of the rows to retrieve (e.g., (0, 2) for the first three rows).

None
style str | None

The name of a style to filter rows by.

None
content str | None

A regular expression to match against the content of the rows.

None

Returns:

Type Description
list[Row]

list[Row]: A list of matching Row elements.

Source code in odfdo/table.py
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
def get_rows(
    self,
    coord: tuple | list | str | None = None,
    style: str | None = None,
    content: str | None = None,
) -> list[Row]:
    """Get a list of rows matching the specified criteria.

    Args:
        coord: The coordinates of the rows
            to retrieve (e.g., (0, 2) for the first three rows).
        style: The name of a style to filter rows by.
        content: A regular expression to match against the
            content of the rows.

    Returns:
        list[Row]: A list of matching Row elements.
    """
    if coord:
        _x, y, _z, t = self._translate_table_coordinates(coord)
    else:
        y = t = None
    # fixme : not clones ?
    if not content and not style:
        return list(self.iter_rows(start=y, end=t))
    rows = []
    for row in self.iter_rows(start=y, end=t):
        if content and not row.match(content):
            continue
        if style and style != row.style:
            continue
        rows.append(row)
    return rows

get_value

get_value(
    coord: tuple | list | str, get_type: bool = False
) -> Any

Get the Python value of the cell at the given coordinates.

Parameters:

Name Type Description Default
coord tuple | list | str

The cell coordinates (e.g., “A1” or (0,0)).

required
get_type bool

If True, returns a tuple of (value, odf_type).

False

Returns:

Name Type Description
Any Any

The Python value of the cell, or a (value, type) tuple if get_type is True.

Source code in odfdo/table.py
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
def get_value(
    self,
    coord: tuple | list | str,
    get_type: bool = False,
) -> Any:
    """Get the Python value of the cell at the given coordinates.

    Args:
        coord: The cell coordinates (e.g., "A1" or (0,0)).
        get_type: If True, returns a tuple of (value, odf_type).

    Returns:
        Any: The Python value of the cell, or a (value, type) tuple if
            `get_type` is True.
    """
    x, y = self._translate_cell_coordinates(coord)
    if x is None:
        raise ValueError
    if y is None:
        raise ValueError
    # Outside the defined table
    if y >= self.height:
        if get_type:
            return (None, None)
        return None
    else:
        # Inside the defined table
        row = self._get_row2_base(y)
        if row is None:
            raise ValueError
        cell = row._get_cell2_base(x)
        if cell is None:
            if get_type:
                return (None, None)
            return None
        return cell.get_value(get_type=get_type)

get_values

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

Get a matrix of values from the table, optionally from a specified area.

Parameters:

Name Type Description Default
coord tuple | list | str | None

The coordinates of the area to parse (e.g., “A1:C3” or (0, 0, 2, 2)). If None, the entire table is parsed.

None
cell_type str | None

Filters cells by their value type (e.g., ‘boolean’, ‘float’, ‘string’). ‘all’ retrieves any non-empty cell.

None
complete bool

If True (default), missing values in the specified area are replaced by None to ensure a complete matrix.

True
get_type bool

If True, returns tuples of (value, odf_type). For empty cells with complete=True, this will be (None, None).

False
flat bool

If True, returns a single flat list of values instead of a list of lists. Defaults to False.

False

Returns:

Name Type Description
list list

A list of lists of Python types representing cell values, or a flat list if flat is True.

Source code in odfdo/table.py
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
def get_values(
    self,
    coord: tuple | list | str | None = None,
    cell_type: str | None = None,
    complete: bool = True,
    get_type: bool = False,
    flat: bool = False,
) -> list:
    """Get a matrix of values from the table, optionally from a specified area.

    Args:
        coord: The coordinates of the area
            to parse (e.g., "A1:C3" or (0, 0, 2, 2)). If None, the entire
            table is parsed.
        cell_type: Filters cells by their value type
            (e.g., 'boolean', 'float', 'string'). 'all' retrieves any
            non-empty cell.
        complete: If True (default), missing values in the specified
            area are replaced by None to ensure a complete matrix.
        get_type: If True, returns tuples of (value, odf_type). For
            empty cells with `complete=True`, this will be (None, None).
        flat: If True, returns a single flat list of values instead
            of a list of lists. Defaults to False.

    Returns:
        list: A list of lists of Python types representing cell values,
            or a flat list if `flat` is True.
    """
    if coord:
        x, y, z, t = self._translate_table_coordinates(coord)
    else:
        x = y = z = t = None
    data = []
    for row in self.iter_rows(start=y, end=t):
        if z is None:
            width = self.width
        else:
            width = min(z + 1, self.width)
        if x is not None:
            width -= x
        values = row.get_values(
            (x, z),
            cell_type=cell_type,
            complete=complete,
            get_type=get_type,
        )
        # complete row to match request width
        if complete:
            if get_type:
                values.extend([(None, None)] * (width - len(values)))
            else:
                values.extend([None] * (width - len(values)))
        if flat:
            data.extend(values)
        else:
            data.append(values)
    return data

insert_cell

insert_cell(
    coord: tuple | list | str,
    cell: Cell | None = None,
    clone: bool = True,
) -> Cell

Insert a cell at the given coordinates, shifting existing cells to the right.

If cell is None, an empty cell is created.

Parameters:

Name Type Description Default
coord tuple | list | str

The (x, y) coordinates for insertion.

required
cell Cell | None

The Cell element to insert.

None
clone bool

If True (default), a copy of the provided cell is used.

True

Returns:

Name Type Description
Cell Cell

The newly inserted cell, with its x and y attributes updated.

Source code in odfdo/table.py
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
def insert_cell(
    self,
    coord: tuple | list | str,
    cell: Cell | None = None,
    clone: bool = True,
) -> Cell:
    """Insert a cell at the given coordinates, shifting existing cells to the right.

    If `cell` is None, an empty cell is created.

    Args:
        coord: The (x, y) coordinates for insertion.
        cell: The Cell element to insert.
        clone: If True (default), a copy of the provided cell is used.

    Returns:
        Cell: The newly inserted cell, with its `x` and `y` attributes updated.
    """
    if cell is None:
        cell = Cell()
        clone = False
    if clone:
        cell = cell.clone
    x, y = self._translate_cell_coordinates(coord)
    if x is None:
        raise ValueError
    if y is None:
        raise ValueError
    row = self._get_row2(y, clone=True)
    row.y = y
    row.repeated = None
    cell_back = row.insert_cell(x, cell, clone=False)
    self.set_row(y, row, clone=False)
    # Update width if necessary
    self._update_width(row)
    return cell_back

insert_column

insert_column(
    x: int | str, column: Column | None = None
) -> Column

Insert a column before the given ‘x’ position.

If no column is provided, an empty one is created.

Parameters:

Name Type Description Default
x int | str

The 0-based index at which to insert the column.

required
column Column | None

The Column element to insert.

None

Returns:

Name Type Description
Column Column

The newly inserted column, with its x attribute updated.

Source code in odfdo/table.py
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
def insert_column(
    self,
    x: int | str,
    column: Column | None = None,
) -> Column:
    """Insert a column before the given 'x' position.

    If no `column` is provided, an empty one is created.

    Args:
        x: The 0-based index at which to insert the column.
        column: The Column element to insert.

    Returns:
        Column: The newly inserted column, with its `x` attribute updated.
    """
    if column is None:
        column = Column()
    x = self._translate_x_from_any(x)
    diff = x - self.width
    if diff < 0:
        column_back = self._table_cache.insert_col_in_cache(x, column, self)
    elif diff == 0:
        column_back = self.append_column(column.clone)
    else:
        self.append_column(Column(repeated=diff), _repeated=diff)
        column_back = self.append_column(column.clone)
    column_back.x = x
    # Repetitions are accepted
    repeated = column.repeated or 1
    # Update width on every row
    for row in self._get_rows():
        if row.width > x:
            row.insert_cell(x, Cell(repeated=repeated))
        # Shorter rows don't need insert
        # Longer rows shouldn't exist!
    return column_back

insert_row

insert_row(
    y: int | str, row: Row | None = None, clone: bool = True
) -> Row

Insert a row before the given ‘y’ position (0-based).

If no row is provided, an empty one is created.

Parameters:

Name Type Description Default
y int | str

The 0-based index at which to insert the row.

required
row Row | None

The Row element to insert.

None
clone bool

If True (default), a copy of the provided row is used.

True

Returns:

Name Type Description
Row Row

The newly inserted row, with its y attribute updated.

Source code in odfdo/table.py
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
def insert_row(
    self, y: int | str, row: Row | None = None, clone: bool = True
) -> Row:
    """Insert a row before the given 'y' position (0-based).

    If no `row` is provided, an empty one is created.

    Args:
        y: The 0-based index at which to insert the row.
        row: The Row element to insert.
        clone: If True (default), a copy of the provided row is used.

    Returns:
        Row: The newly inserted row, with its `y` attribute updated.
    """
    if row is None:
        row = Row()
        clone = False
    y = self._translate_y_from_any(y)
    diff = y - self.height
    if diff < 0:
        row_back = self._table_cache.insert_row_in_cache(y, row, self)
    elif diff == 0:
        row_back = self.append_row(row, clone=clone)
    else:
        self.append_row(Row(repeated=diff), _repeated=diff, clone=False)
        row_back = self.append_row(row, clone=clone)
    row_back.y = y
    # Update width if necessary
    self._update_width(row_back)
    return row_back

is_column_empty

is_column_empty(
    x: int | str, aggressive: bool = False
) -> bool

Return True if every cell in the column at the ‘x’ position is empty.

A cell is considered empty if it has no value (or a value that evaluates to False) and no style.

Parameters:

Name Type Description Default
x int | str

The 0-based index or alphabetical representation of the column.

required
aggressive bool

If True, empty cells with styles are also considered empty.

False

Returns:

Name Type Description
bool bool

True if the column is empty, False otherwise.

Source code in odfdo/table.py
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
def is_column_empty(self, x: int | str, aggressive: bool = False) -> bool:
    """Return True if every cell in the column at the 'x' position is empty.

    A cell is considered empty if it has no value (or a value that evaluates
    to False) and no style.

    Args:
        x: The 0-based index or alphabetical representation of the column.
        aggressive: If True, empty cells with styles are also considered empty.

    Returns:
        bool: True if the column is empty, False otherwise.
    """
    for cell in self.get_column_cells(x):
        if cell is None:
            continue
        if not cell.is_empty(aggressive=aggressive):
            return False
    return True

is_empty

is_empty(aggressive: bool = False) -> bool

Return True if every cell in the table is empty.

A cell is considered empty if it has no value (or a value that evaluates to False, like an empty string) and no style.

Parameters:

Name Type Description Default
aggressive bool

If True, empty cells with styles are also considered empty.

False

Returns:

Name Type Description
bool bool

True if the table is empty, False otherwise.

Source code in odfdo/table.py
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
def is_empty(self, aggressive: bool = False) -> bool:
    """Return True if every cell in the table is empty.

    A cell is considered empty if it has no value (or a value that evaluates
    to False, like an empty string) and no style.

    Args:
        aggressive: If True, empty cells with styles are also
            considered empty.

    Returns:
        bool: True if the table is empty, False otherwise.
    """
    return all(row.is_empty(aggressive=aggressive) for row in self._get_rows())

is_row_empty

is_row_empty(
    y: int | str, aggressive: bool = False
) -> bool

Return True if every cell in the row at the given ‘y’ position is empty.

A cell is considered empty if it has no value (or a value that evaluates to False, like an empty string) and no style.

Parameters:

Name Type Description Default
y int | str

The 0-based index of the row.

required
aggressive bool

If True, empty cells with styles are also considered empty.

False

Returns:

Name Type Description
bool bool

True if the row is empty, False otherwise.

Source code in odfdo/table.py
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
def is_row_empty(self, y: int | str, aggressive: bool = False) -> bool:
    """Return True if every cell in the row at the given 'y' position is empty.

    A cell is considered empty if it has no value (or a value that evaluates
    to False, like an empty string) and no style.

    Args:
        y: The 0-based index of the row.
        aggressive: If True, empty cells with styles are also
            considered empty.

    Returns:
        bool: True if the row is empty, False otherwise.
    """
    return self.get_row(y, clone=False).is_empty(aggressive=aggressive)

iter_columns

iter_columns(
    start: int | None = None, end: int | None = None
) -> Iterator[Column]

Yield column elements, expanding repetitions.

This method produces individual column objects. The same column object is yielded as many times as it is repeated. The yielded columns are copies; use set_column() to apply changes.

Parameters:

Name Type Description Default
start int | None

The starting column index (0-based). Defaults to 0.

None
end int | None

The ending column index (inclusive). Defaults to 2**32.

None

Yields:

Name Type Description
Column Column

The next column element in the specified range.

Source code in odfdo/table.py
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
def iter_columns(
    self,
    start: int | None = None,
    end: int | None = None,
) -> Iterator[Column]:
    """Yield column elements, expanding repetitions.

    This method produces individual column objects. The same column
    object is yielded as many times as it is repeated. The yielded
    columns are copies; use `set_column()` to apply changes.

    Args:
        start: The starting column index (0-based). Defaults to 0.
        end: The ending column index (inclusive). Defaults to 2**32.

    Yields:
        Column: The next column element in the specified range.
    """
    if start is None:
        start = 0
    start = max(0, start)
    if end is None:
        end = 2**32
    if end < start:
        return
    x = -1
    for column in self._yield_odf_columns():
        x += 1
        if x < start:
            continue
        if x > end:
            return
        column.x = x
        yield column

iter_rows

iter_rows(
    start: int | None = None, end: int | None = None
) -> Iterator[Row]

Yield row elements, expanding repetitions.

This method produces individual row objects. The same row object is yielded as many times as it is repeated. The yielded columns are copies; use set_row() to apply changes.

Parameters:

Name Type Description Default
start int | None

The starting row index (0-based). Defaults to 0.

None
end int | None

The ending row index (inclusive). Defaults to 2**32.

None

Yields:

Name Type Description
Row Row

The next row element in the specified range.

Source code in odfdo/table.py
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
def iter_rows(
    self,
    start: int | None = None,
    end: int | None = None,
) -> Iterator[Row]:
    """Yield row elements, expanding repetitions.

    This method produces individual row objects. The same row
    object is yielded as many times as it is repeated. The yielded
    columns are copies; use `set_row()` to apply changes.

    Args:
        start: The starting row index (0-based). Defaults to 0.
        end: The ending row index (inclusive). Defaults to 2**32.

    Yields:
        Row: The next row element in the specified range.
    """
    if start is None:
        start = 0
    start = max(0, start)
    if end is None:
        end = 2**32
    if end < start:
        return
    y = -1
    for row in self._yield_odf_rows():
        y += 1
        if y < start:
            continue
        if y > end:
            return
        row.y = y
        yield row

iter_values

iter_values(
    coord: tuple | list | str | None = None,
    cell_type: str | None = None,
    complete: bool = True,
    get_type: bool = False,
) -> Iterator[list]

Yield lists of values of rows.

Each yielded list contains the python values ot the cells of the row.

Parameters:

Name Type Description Default
coord tuple | list | str | None

The coordinates of the area to parse.

None
cell_type str | None

Filters cells by value type (e.g., ‘float’). ‘all’ retrieves any non-empty cell. See get_values for more.

None
complete bool

If True, missing values are replaced by None.

True
get_type bool

If True, yields tuples of (value, odf_type).

False

Yields:

Name Type Description
list list

An iterator where each item is a list representing a row of

list

cell values.

Source code in odfdo/table.py
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
def iter_values(
    self,
    coord: tuple | list | str | None = None,
    cell_type: str | None = None,
    complete: bool = True,
    get_type: bool = False,
) -> Iterator[list]:
    """Yield lists of values of rows.

    Each yielded list contains the python values ot the cells of the row.

    Args:
        coord: The coordinates of the area to parse.
        cell_type: Filters cells by value type (e.g., 'float'). 'all'
            retrieves any non-empty cell. See `get_values` for more.
        complete: If True, missing values are replaced by None.
        get_type: If True, yields tuples of (value, odf_type).

    Yields:
        list: An iterator where each item is a list representing a row of
        cell values.
    """
    if coord:
        x, y, z, t = self._translate_table_coordinates(coord)
    else:
        x = y = z = t = None
    for row in self.iter_rows(start=y, end=t):
        if z is None:
            width = self.width
        else:
            width = min(z + 1, self.width)
        if x is not None:
            width -= x
        values = row.get_values(
            (x, z),
            cell_type=cell_type,
            complete=complete,
            get_type=get_type,
        )
        # complete row to match column width
        if complete:
            if get_type:
                values.extend([(None, None)] * (width - len(values)))
            else:
                values.extend([None] * (width - len(values)))
        yield values

optimize_width

optimize_width() -> None

Remove empty rows and right-side empty cells in-place.

This method keeps the repeated styles of empty cells but minimizes the row width to fit the actual content.

Source code in odfdo/table.py
951
952
953
954
955
956
957
958
959
960
def optimize_width(self) -> None:
    """Remove empty rows and right-side empty cells in-place.

    This method keeps the repeated styles of empty cells but minimizes the
    row width to fit the actual content.
    """
    self._optimize_width_trim_rows()
    width = self._optimize_width_length()
    self._optimize_width_rstrip_rows(width)
    self._optimize_width_adapt_columns(width)

rstrip

rstrip(aggressive: bool = False) -> None

Remove empty rows and right-side empty cells from the table in-place.

A cell is considered empty if it has no value (or a value that evaluates to False) and no style.

Parameters:

Name Type Description Default
aggressive bool

If True, empty cells with styles are also considered empty and will be removed.

False
Source code in odfdo/table.py
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
def rstrip(self, aggressive: bool = False) -> None:
    """Remove empty rows and right-side empty cells from the table in-place.

    A cell is considered empty if it has no value (or a value that evaluates
    to False) and no style.

    Args:
        aggressive: If True, empty cells with styles are also
            considered empty and will be removed.
    """
    # Step 1: remove empty rows below the table
    for row in reversed(self._get_rows()):
        if row.is_empty(aggressive=aggressive):
            row.parent.delete(row)  # type: ignore[union-attr]
        else:
            break
    # Step 2: rstrip remaining rows
    max_width = 0
    for row in self._get_rows():
        row.rstrip(aggressive=aggressive)
        # keep count of the biggest row
        max_width = max(max_width, row.width)
    # raz cache of rows
    self._table_cache.clear_row_indexes()
    # Step 3: trim columns to match max_width
    columns = self._get_columns()
    repeated_cols: list[EText] = cast(
        list[EText], self.xpath("table:table-column/@table:number-columns-repeated")
    )
    unrepeated = len(columns) - len(repeated_cols)
    column_width = sum(int(r) for r in repeated_cols) + unrepeated
    diff = column_width - max_width
    if diff > 0:
        for column in reversed(columns):  # pragma: nocover
            repeated = column.repeated or 1
            repeated = repeated - diff
            if repeated > 0:
                column.repeated = repeated
                break
            else:
                column.parent.delete(column)  # type: ignore[union-attr]
                diff = -repeated
                if diff == 0:
                    break
    # raz cache of columns
    self._table_cache.clear_col_indexes()
    self._compute_table_cache()

set_cell

set_cell(
    coord: tuple | list | str,
    cell: Cell | None = None,
    clone: bool = True,
) -> Cell

Replace the cell at the given coordinates.

If cell is None, an empty cell is created.

Parameters:

Name Type Description Default
coord tuple | list | str

The coordinates of the cell to replace.

required
cell Cell | None

The new Cell element to set.

None
clone bool

If True (default), a copy of the provided cell is used.

True

Returns:

Name Type Description
Cell Cell

The newly set cell, with its x and y attributes updated.

Source code in odfdo/table.py
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
def set_cell(
    self,
    coord: tuple | list | str,
    cell: Cell | None = None,
    clone: bool = True,
) -> Cell:
    """Replace the cell at the given coordinates.

    If `cell` is None, an empty cell is created.

    Args:
        coord: The coordinates of the cell to replace.
        cell: The new Cell element to set.
        clone: If True (default), a copy of the provided cell is used.

    Returns:
        Cell: The newly set cell, with its `x` and `y` attributes updated.
    """
    if cell is None:
        cell = Cell()
        clone = False
    x, y = self._translate_cell_coordinates(coord)
    if x is None:
        raise ValueError
    if y is None:
        raise ValueError
    cell.x = x
    cell.y = y
    if y >= self.height:
        row = Row()
        cell_back = row.set_cell(x, cell, clone=clone)
        self.set_row(y, row, clone=False)
    else:
        row_read = self._get_row2_base(y)
        if row_read is None:
            raise ValueError
        row = row_read
        row.y = y
        repeated = row.repeated or 1
        if repeated > 1:
            row = row.clone
            row.repeated = None
            cell_back = row.set_cell(x, cell, clone=clone)
            self.set_row(y, row, clone=False)
        else:
            cell_back = row.set_cell(x, cell, clone=clone)
            # Update width if necessary, since we don't use set_row
            self._update_width(row)
    return cell_back

set_cell_image

set_cell_image(
    coord: tuple | list | str,
    image_frame: Frame,
    doc_type: str | None = None,
) -> None

Deprecated. Use recipes to insert an image in a cell.

This method provided a way to insert an image into a cell, but it is now deprecated. Please refer to the project’s recipes for the recommended way to achieve this.

Parameters:

Name Type Description Default
coord tuple | list | str

The coordinates of the cell.

required
image_frame Frame

The Frame element containing the image.

required
doc_type str | None

The document type (‘spreadsheet’ or ‘text’).

None
Source code in odfdo/table.py
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
def set_cell_image(
    self,
    coord: tuple | list | str,
    image_frame: Frame,
    doc_type: str | None = None,
) -> None:
    """Deprecated. Use recipes to insert an image in a cell.

    This method provided a way to insert an image into a cell, but it is now
    deprecated. Please refer to the project's recipes for the recommended
    way to achieve this.

    Args:
        coord: The coordinates of the cell.
        image_frame: The Frame element containing the image.
        doc_type: The document type ('spreadsheet' or 'text').
    """
    warn("Table.set_cell_image() is deprecated", DeprecationWarning, stacklevel=2)
    # Test document type
    if doc_type is None:
        body = self.document_body
        if body is None:
            raise ValueError("document type not found")
        doc_type = {"office:spreadsheet": "spreadsheet", "office:text": "text"}.get(
            body.tag
        )
        if doc_type is None:
            raise ValueError("document type not supported for images")
    # We need the end address of the image
    x, y = self._translate_cell_coordinates(coord)
    if x is None:
        raise ValueError
    if y is None:
        raise ValueError
    cell = self.get_cell((x, y))
    image_frame = image_frame.clone  # type: ignore[assignment]
    # Remove any previous paragraph, frame, etc.
    for child in cell.children:
        cell.delete(child)
    # Now it all depends on the document type
    if doc_type == "spreadsheet":
        image_frame.anchor_type = "char"
        # The frame needs end coordinates
        width, height = image_frame.size
        image_frame.set_attribute("table:end-x", width)
        image_frame.set_attribute("table:end-y", height)
        # FIXME what happens when the address changes?
        address = f"{self.name}.{digit_to_alpha(x)}{y + 1}"
        image_frame.set_attribute("table:end-cell-address", address)
        # The frame is directly in the cell
        cell.append(image_frame)
    elif doc_type == "text":
        # The frame must be in a paragraph
        cell.set_value("")
        paragraph = cell.get_element("text:p")
        if paragraph is None:
            raise ValueError
        paragraph.append(image_frame)
    self.set_cell(coord, cell)

set_cells

set_cells(
    cells: Iterable[list[Cell]] | Iterable[tuple[Cell]],
    coord: tuple | list | str | None = None,
    clone: bool = True,
) -> None

Set a matrix of cells in the table, starting from a specified coordinate.

The table is not cleared before this operation. The cells argument should be a list of lists, where each inner list represents a row.

Parameters:

Name Type Description Default
cells Iterable[list[Cell]] | Iterable[tuple[Cell]]

A list of lists of Cell elements.

required
coord tuple | list | str | None

The top-left coordinate for placing the cells. Defaults to “A1”.

None
clone bool

If True (default), copies of the provided cells are used.

True
Source code in odfdo/table.py
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
def set_cells(
    self,
    cells: Iterable[list[Cell]] | Iterable[tuple[Cell]],
    coord: tuple | list | str | None = None,
    clone: bool = True,
) -> None:
    """Set a matrix of cells in the table, starting from a specified coordinate.

    The table is not cleared before this operation. The `cells` argument should
    be a list of lists, where each inner list represents a row.

    Args:
        cells: A list of lists
            of Cell elements.
        coord: The top-left coordinate for
            placing the cells. Defaults to "A1".
        clone: If True (default), copies of the provided cells are used.
    """
    if coord:
        x, y = self._translate_cell_coordinates(coord)
    else:
        x = y = 0
    if y is None:
        y = 0
    if x is None:
        x = 0
    y -= 1
    for row_cells in cells:
        y += 1
        if not row_cells:
            continue
        row = self.get_row(y, clone=True)
        repeated = row.repeated or 1
        if repeated >= 2:
            row.repeated = None
        row.set_cells(row_cells, start=x, clone=clone)
        self.set_row(y, row, clone=False)
        self._update_width(row)

set_column

set_column(
    x: int | str, column: Column | None = None
) -> Column

Replace the column at the given ‘x’ position.

ODF columns primarily store style information.

Parameters:

Name Type Description Default
x int | str

The 0-based index or alphabetical representation of the column to replace.

required
column Column | None

The new Column element to set. If None, an empty column is created.

None

Returns:

Name Type Description
Column Column

The newly set column, with its x attribute updated.

Source code in odfdo/table.py
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
def set_column(
    self,
    x: int | str,
    column: Column | None = None,
) -> Column:
    """Replace the column at the given 'x' position.

    ODF columns primarily store style information.

    Args:
        x: The 0-based index or alphabetical representation
            of the column to replace.
        column: The new Column element to set. If None,
            an empty column is created.

    Returns:
        Column: The newly set column, with its `x` attribute updated.
    """
    x = self._translate_x_from_any(x)
    if column is None:
        column = Column()
        repeated = 1
    else:
        repeated = column.repeated or 1
    column.x = x
    # Outside the defined table ?
    diff = x - self.width
    if diff == 0:
        column_back = self.append_column(column, _repeated=repeated)
    elif diff > 0:
        self.append_column(Column(repeated=diff), _repeated=diff)
        column_back = self.append_column(column, _repeated=repeated)
    else:
        # Inside the defined table
        column_back = self._table_cache.set_col_in_cache(x, column, self)
    return column_back

set_column_cells

set_column_cells(x: int | str, cells: list[Cell]) -> None

Set the list of cells for the column at the given ‘x’ position.

The provided list of cells must have the same length as the table’s height.

Parameters:

Name Type Description Default
x int | str

The 0-based index or alphabetical representation of the column.

required
cells list[Cell]

A list of Cell elements to set.

required
Source code in odfdo/table.py
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
def set_column_cells(self, x: int | str, cells: list[Cell]) -> None:
    """Set the list of cells for the column at the given 'x' position.

    The provided list of cells must have the same length as the table's height.

    Args:
        x: The 0-based index or alphabetical representation
            of the column.
        cells: A list of Cell elements to set.
    """
    height = self.height
    if len(cells) != height:
        raise ValueError(f"col mismatch: {height} cells expected")
    cells_iterator = iter(cells)
    for y, row in enumerate(self.iter_rows()):
        row.set_cell(x, next(cells_iterator))
        self.set_row(y, row)

set_column_values

set_column_values(
    x: int | str,
    values: list,
    cell_type: str | None = None,
    currency: str | None = None,
    style: str | None = None,
) -> None

Set the list of Python values for the cells in the column at the given ‘x’ position.

The provided list of values must have the same length as the table’s height.

Parameters:

Name Type Description Default
x int | str

The 0-based index or alphabetical representation of the column.

required
values list

A list of Python types to set as cell values.

required
cell_type str | None

The value type for the cells.

None
currency str | None

A three-letter currency code.

None
style str | None

The name of a cell style to apply.

None
Source code in odfdo/table.py
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
def set_column_values(
    self,
    x: int | str,
    values: list,
    cell_type: str | None = None,
    currency: str | None = None,
    style: str | None = None,
) -> None:
    """Set the list of Python values for the cells in the column at the given 'x' position.

    The provided list of values must have the same length as the table's height.

    Args:
        x: The 0-based index or alphabetical representation of the column.
        values: A list of Python types to set as cell values.
        cell_type: The value type for the cells.
        currency: A three-letter currency code.
        style: The name of a cell style to apply.
    """
    cells = [
        Cell(value, cell_type=cell_type, currency=currency, style=style)
        for value in values
    ]
    self.set_column_cells(x, cells)

set_named_range

set_named_range(
    name: str,
    crange: str | tuple | list,
    table_name: str | None = None,
    usage: str | None = None,
    global_scope: bool = True,
) -> None

Create and insert a named range, replacing any existing one with the same name.

Named ranges can be local or global. Global named ranges are stored at the body level, so do not call this on a cloned table for global access.

Parameters:

Name Type Description Default
name str

The name of the named range.

required
crange str | tuple | list

The cell or area coordinates.

required
table_name str | None

The name of the table. Defaults to the current table’s name if global_scope is True.

None
usage str | None

The usage type (‘print-range’, ‘filter’, etc.).

None
global_scope bool

If True (default), inserts into the document body. If False, inserts into the current table.

True
Source code in odfdo/table.py
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
def set_named_range(
    self,
    name: str,
    crange: str | tuple | list,
    table_name: str | None = None,
    usage: str | None = None,
    global_scope: bool = True,
) -> None:
    """Create and insert a named range, replacing any existing one with the same name.

    Named ranges can be local or global. Global named ranges are stored at
    the body level, so do not call this on a cloned table for global access.

    Args:
        name: The name of the named range.
        crange: The cell or area coordinates.
        table_name: The name of the table. Defaults to the
            current table's name if `global_scope` is True.
        usage: The usage type ('print-range', 'filter', etc.).
        global_scope: If True (default), inserts into the document body.
            If False, inserts into the current table.
    """
    name = name.strip()
    if not name:
        raise ValueError("Name required")
    if global_scope:
        body = self.document_body
        if not body:
            raise ValueError("Table is not inside a document")
        if not body.allow_named_range:
            msg = (
                "Document must be of type Chart, Drawing, "
                "Presentation, Spreadsheet or Text"
            )
            raise TypeError(msg)
        if not table_name:
            table_name = self.name
        body.set_named_range(  # type: ignore[attr-defined]
            name=name,
            crange=crange,
            table_name=table_name,
            usage=usage,
        )
    else:
        self._local_set_named_range(name=name, crange=crange, usage=usage)

set_row

set_row(
    y: int | str, row: Row | None = None, clone: bool = True
) -> Row

Replace the row at the given position with a new one.

Repetitions of the old row will be adjusted. If row is None, a new empty row is created.

Parameters:

Name Type Description Default
y int | str

The 0-based index of the row to replace.

required
row Row | None

The new Row element to set.

None
clone bool

If True (default), a copy of the provided row is used.

True

Returns:

Name Type Description
Row Row

The newly set row, with its y attribute updated.

Source code in odfdo/table.py
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
def set_row(self, y: int | str, row: Row | None = None, clone: bool = True) -> Row:
    """Replace the row at the given position with a new one.

    Repetitions of the old row will be adjusted. If `row` is None, a new
    empty row is created.

    Args:
        y: The 0-based index of the row to replace.
        row: The new Row element to set.
        clone: If True (default), a copy of the provided row is used.

    Returns:
        Row: The newly set row, with its `y` attribute updated.
    """
    if row is None:
        row = Row()
        repeated = 1
        clone = False
    else:
        repeated = row.repeated or 1
    y = self._translate_y_from_any(y)
    row.y = y
    # Outside the defined table ?
    diff = y - self.height
    if diff == 0:
        row_back = self.append_row(row, _repeated=repeated, clone=clone)
    elif diff > 0:
        self.append_row(Row(repeated=diff), _repeated=diff, clone=clone)
        row_back = self.append_row(row, _repeated=repeated, clone=clone)
    else:
        # Inside the defined table
        row_back = self._table_cache.set_row_in_cache(y, row, self, clone=clone)
    # print self.serialize(True)
    # Update width if necessary
    self._update_width(row_back)
    return row_back

set_row_cells

set_row_cells(
    y: int | str, cells: list | None = None
) -> Row

Set all the cells of the row at the given ‘y’ position.

Parameters:

Name Type Description Default
y int | str

The 0-based index of the row.

required
cells list | None

A list of Cell elements to set.

None

Returns:

Name Type Description
Row Row

The modified row, with its y attribute updated.

Source code in odfdo/table.py
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
def set_row_cells(self, y: int | str, cells: list | None = None) -> Row:
    """Set all the cells of the row at the given 'y' position.

    Args:
        y: The 0-based index of the row.
        cells: A list of Cell elements to set.

    Returns:
        Row: The modified row, with its `y` attribute updated.
    """
    if cells is None:
        cells = []
    row = Row()  # needed if clones rows
    row.extend_cells(cells)
    return self.set_row(y, row)  # needed if clones rows

set_row_values

set_row_values(
    y: int | str,
    values: list,
    cell_type: str | None = None,
    currency: str | None = None,
    style: str | None = None,
) -> Row

Set the values of all cells in the row at the given ‘y’ position.

Parameters:

Name Type Description Default
y int | str

The 0-based index of the row.

required
values list

A list of Python types to set as cell values.

required
cell_type str | None

The value type for the cells (e.g., ‘float’).

None
currency str | None

A three-letter currency code.

None
style str | None

The name of a cell style to apply.

None

Returns:

Name Type Description
Row Row

The modified row, with its y attribute updated.

Source code in odfdo/table.py
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
def set_row_values(
    self,
    y: int | str,
    values: list,
    cell_type: str | None = None,
    currency: str | None = None,
    style: str | None = None,
) -> Row:
    """Set the values of all cells in the row at the given 'y' position.

    Args:
        y: The 0-based index of the row.
        values: A list of Python types to set as cell values.
        cell_type: The value type for the cells (e.g., 'float').
        currency: A three-letter currency code.
        style: The name of a cell style to apply.

    Returns:
        Row: The modified row, with its `y` attribute updated.
    """
    row = Row()  # needed if clones rows
    row.set_values(values, style=style, cell_type=cell_type, currency=currency)
    return self.set_row(y, row)  # needed if clones rows

set_span

set_span(
    area: str | tuple | list, merge: bool = False
) -> bool

Create a cell span, spanning the first cell of the area over columns and/or rows.

It is not allowed to apply a span to an area where a cell already belongs to a previous span. If the area defines only one cell, this method does nothing.

Parameters:

Name Type Description Default
area str | tuple | list

The cell or area coordinates (e.g., “A1:B2”).

required
merge bool

If True, concatenates the text of covered cells into the first cell. If False (default), text in covered cells is preserved but may not be displayed by office applications.

False

Returns:

Name Type Description
bool bool

True if the span was successfully created, False otherwise.

Source code in odfdo/table.py
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
def set_span(
    self,
    area: str | tuple | list,
    merge: bool = False,
) -> bool:
    """Create a cell span, spanning the first cell of the area over columns and/or rows.

    It is not allowed to apply a span to an area where a cell already belongs
    to a previous span. If the area defines only one cell, this method does nothing.

    Args:
        area: The cell or area coordinates (e.g., "A1:B2").
        merge: If True, concatenates the text of covered cells into the
            first cell. If False (default), text in covered cells is preserved
            but may not be displayed by office applications.

    Returns:
        bool: True if the span was successfully created, False otherwise.
    """
    # get area
    digits = convert_coordinates(area)
    if len(digits) == 4:
        x, y, z, t = digits
    else:
        x, y = digits
        z, t = digits
    start = x, y
    end = z, t
    if start == end:
        # one cell : do nothing
        return False
    if x is None:
        raise ValueError
    if y is None:
        raise ValueError
    if z is None:
        raise ValueError
    if t is None:
        raise ValueError
    # check for previous span
    good = True
    # Check boundaries and empty cells : need to crate non existent cells
    # so don't use get_cells directly, but get_cell
    cells = []
    for yy in range(y, t + 1):
        row_cells = []
        for xx in range(x, z + 1):
            row_cells.append(
                self.get_cell((xx, yy), clone=True, keep_repeated=False)
            )
        cells.append(row_cells)
    for row in cells:
        for cell in row:
            if cell.is_spanned():
                good = False
                break
        if not good:
            break
    if not good:
        return False
    # Check boundaries
    # if z >= self.width or t >= self.height:
    #    self.set_cell(coord = end)
    #    print area, z, t
    #    cells = self.get_cells((x, y, z, t))
    #    print cells
    # do it:
    if merge:
        val_list = []
        for row in cells:
            for cell in row:
                if cell.is_empty(aggressive=True):
                    continue
                val = cell.get_value()
                if val is not None:
                    if isinstance(val, str):
                        val.strip()
                    if val != "":
                        val_list.append(val)
                    cell.clear()
        if val_list:
            if len(val_list) == 1:
                cells[0][0].set_value(val_list[0])  # type: ignore[arg-type]
            else:
                value = " ".join([str(v) for v in val_list if v])
                cells[0][0].set_value(value)
    cols = z - x + 1
    cells[0][0].set_attribute("table:number-columns-spanned", str(cols))
    rows = t - y + 1
    cells[0][0].set_attribute("table:number-rows-spanned", str(rows))
    for cell in cells[0][1:]:
        cell.tag = "table:covered-table-cell"
    for row in cells[1:]:
        for cell in row:
            cell.tag = "table:covered-table-cell"
    # replace cells in table
    self.set_cells(cells, coord=start, clone=False)
    return True

set_value

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

Set the Python value of the cell at the given coordinates.

Parameters:

Name Type Description Default
coord tuple | list | str

The coordinates of the cell.

required
value Any

The Python value to set.

required
cell_type str | None

The value type (e.g., ‘float’, ‘string’).

None
currency str | None

A three-letter currency code.

None
style str | None

The name of a cell style to apply.

None
Source code in odfdo/table.py
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
def set_value(
    self,
    coord: tuple | list | str,
    value: Any,
    cell_type: str | None = None,
    currency: str | None = None,
    style: str | None = None,
) -> None:
    """Set the Python value of the cell at the given coordinates.

    Args:
        coord: The coordinates of the cell.
        value: The Python value to set.
        cell_type: The value type (e.g., 'float', 'string').
        currency: A three-letter currency code.
        style: The name of a cell style to apply.
    """
    self.set_cell(
        coord,
        Cell(value, cell_type=cell_type, currency=currency, style=style),
        clone=False,
    )

set_values

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

Set cell values in the table, starting from a specified coordinate.

The table is not cleared before this operation. To reset the table, call table.clear() first. The input values should be a list of lists, where each inner list represents a row.

Parameters:

Name Type Description Default
values list

A list of lists of Python types to set.

required
coord tuple | list | str | None

The coordinate of the top-left cell where values should be set (e.g., “A1” or (0, 0)). Defaults to “A1”.

None
style str | None

The name of a cell style to apply.

None
cell_type str | None

The value type for the cells (e.g., ‘float’).

None
currency str | None

A three-letter currency code (e.g., ‘USD’).

None
Source code in odfdo/table.py
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
def set_values(
    self,
    values: list,
    coord: tuple | list | str | None = None,
    style: str | None = None,
    cell_type: str | None = None,
    currency: str | None = None,
) -> None:
    """Set cell values in the table, starting from a specified coordinate.

    The table is not cleared before this operation. To reset the table, call
    `table.clear()` first. The input `values` should be a list of lists,
    where each inner list represents a row.

    Args:
        values: A list of lists of Python types to set.
        coord: The coordinate of the top-left
            cell where values should be set (e.g., "A1" or (0, 0)).
            Defaults to "A1".
        style: The name of a cell style to apply.
        cell_type: The value type for the cells (e.g., 'float').
        currency: A three-letter currency code (e.g., 'USD').
    """
    if coord:
        x, y = self._translate_cell_coordinates(coord)
    else:
        x = y = 0
    if y is None:
        y = 0
    if x is None:
        x = 0
    y -= 1
    for row_values in values:
        y += 1
        if not row_values:
            continue
        row = self.get_row(y, clone=True)
        repeated = row.repeated or 1
        if repeated >= 2:
            row.repeated = None
        row.set_values(
            row_values,
            start=x,
            cell_type=cell_type,
            currency=currency,
            style=style,
        )
        self.set_row(y, row, clone=False)
        self._update_width(row)

to_csv

to_csv(
    path_or_file: str | Path | None = None,
    dialect: str = "excel",
    **fmtparams: Any,
) -> str | None

Export the table as a CSV string or file.

Parameters:

Name Type Description Default
path_or_file str | Path | None

The path to save the CSV file to. If None, the CSV content is returned as a string.

None
dialect str

The CSV dialect to use (e.g., ‘excel’, ‘unix’).

'excel'
**fmtparams Any

Additional keyword arguments to pass to the csv.writer method.

{}

Returns:

Type Description
str | None

str | None: The CSV content as a string if path_or_file is None, otherwise None.

Source code in odfdo/table.py
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
def to_csv(
    self,
    path_or_file: str | Path | None = None,
    dialect: str = "excel",
    **fmtparams: Any,
) -> str | None:
    """Export the table as a CSV string or file.

    Args:
        path_or_file: The path to save the CSV file to.
            If None, the CSV content is returned as a string.
        dialect: The CSV dialect to use (e.g., 'excel', 'unix').
        **fmtparams: Additional keyword arguments to pass to the
            `csv.writer` method.

    Returns:
        str | None: The CSV content as a string if `path_or_file` is None,
            otherwise None.
    """

    def write_content(csv_writer: object) -> None:
        for values in self.iter_values():
            line = []
            for value in values:
                if value is None:
                    value = ""
                line.append(value)
            csv_writer.writerow(line)  # type: ignore[attr-defined]

    content = StringIO(newline="")
    csv_writer = csv.writer(content, dialect=dialect, **fmtparams)
    write_content(csv_writer)
    if path_or_file:
        # windows fix: write file as binary
        Path(path_or_file).write_bytes(content.getvalue().encode())
        return None
    return content.getvalue()

transpose

transpose(coord: tuple | list | str | None = None) -> None

Swap rows and columns of the table in-place.

Parameters:

Name Type Description Default
coord tuple | list | str | None

The coordinates of a specific area to transpose. If None, the entire table is transposed. If the area is not square, some cells may be overwritten.

None
Source code in odfdo/table.py
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
def transpose(self, coord: tuple | list | str | None = None) -> None:
    """Swap rows and columns of the table in-place.

    Args:
        coord: The coordinates of a specific
            area to transpose. If None, the entire table is transposed.
            If the area is not square, some cells may be overwritten.
    """
    data = []
    if coord is None:
        for row in self.iter_rows():
            data.append(row.cells)
        transposed_data = zip_longest(*data)
        self.clear()
        for row_cells in transposed_data:
            row = Row()
            row.extend_cells(row_cells)
            self.append_row(row, clone=False)
        self._compute_table_cache()
    else:
        x, y, z, t = self._translate_table_coordinates(coord)
        if x is None:
            x = 0
        else:
            x = min(x, self.width - 1)
        if z is None:
            z = self.width - 1
        else:
            z = min(z, self.width - 1)
        if y is None:
            y = 0
        else:
            y = min(y, self.height - 1)
        if t is None:
            t = self.height - 1
        else:
            t = min(t, self.height - 1)
        for row in self.iter_rows(start=y, end=t):
            data.append(list(row.iter_cells(start=x, end=z)))
        transposed_data = zip_longest(*data)
        # clear locally
        w = z - x + 1
        h = t - y + 1
        if w != h:
            nones = [[None] * w for i in range(h)]
            self.set_values(nones, coord=(x, y, z, t))
        # put transposed
        self.set_cells(
            cast(Iterable[tuple[Cell]], transposed_data),
            (x, y, x + h - 1, y + w - 1),
        )
        self._compute_table_cache()

_get_python_value

_get_python_value(
    data: str | bytes | int | float | bool, encoding: str
) -> Any

Guess the most appropriate Python type to load data, with regard to ODF types.

This function attempts to convert data (typically from a CSV analyzer) into a Python integer, float, Date, DateTime, Duration, or Boolean. If none of these conversions are successful, the data is returned as a string.

Parameters:

Name Type Description Default
data str | bytes | int | float | bool

The input data.

required
encoding str

The encoding to use if data is bytes.

required

Returns:

Name Type Description
Any Any

The data converted to its guessed Python type, or a string.

Source code in odfdo/table.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
def _get_python_value(data: str | bytes | int | float | bool, encoding: str) -> Any:
    """Guess the most appropriate Python type to load data, with regard to ODF types.

    This function attempts to convert data (typically from a CSV analyzer)
    into a Python integer, float, Date, DateTime, Duration, or Boolean. If
    none of these conversions are successful, the data is returned as a string.

    Args:
        data: The input data.
        encoding: The encoding to use if `data` is bytes.

    Returns:
        Any: The data converted to its guessed Python type, or a string.
    """
    if isinstance(data, bytes):
        data = data.decode(encoding)
    if isinstance(data, (float, int, bool)):
        return data
    # An int ?
    try:
        return int(data)
    except ValueError:
        pass
    # A float ?
    try:
        return float(data)
    except ValueError:
        pass
    # A Date ?
    try:
        return Date.decode(data)
    except ValueError:
        pass
    # A DateTime ?
    try:
        # Two tests: "yyyy-mm-dd hh:mm:ss" or "yyyy-mm-ddThh:mm:ss"
        return DateTime.decode(data.replace(" ", "T"))
    except ValueError:
        pass
    # A Duration ?
    try:
        return Duration.decode(data)
    except ValueError:
        pass
    # A Boolean ?
    try:
        # "True" or "False" with a .lower
        return Boolean.decode(data.lower())
    except ValueError:
        pass
    # So a string
    return data

import_from_csv

import_from_csv(
    path_or_file: str | Path | object,
    name: str,
    style: str | None = None,
    **fmtparams: Any,
) -> Table

Import a CSV file or file-like object into a new Table.

The CSV format can be auto-detected to a certain extent. Use **fmtparams to define csv.reader parameters for more control.

Parameters:

Name Type Description Default
path_or_file str | Path | object

The path to a CSV file or a file-like object to read from.

required
name str

The name of the table to create.

required
style str | None

The style to apply to the table.

None
**fmtparams Any

Additional keyword arguments for the csv.reader method.

{}

Returns:

Name Type Description
Table Table

A new Table object populated with the CSV data.

Source code in odfdo/table.py
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
def import_from_csv(
    path_or_file: str | Path | object,
    name: str,
    style: str | None = None,
    **fmtparams: Any,
) -> Table:
    """Import a CSV file or file-like object into a new Table.

    The CSV format can be auto-detected to a certain extent. Use `**fmtparams`
    to define `csv.reader` parameters for more control.

    Args:
        path_or_file: The path to a CSV file or a
            file-like object to read from.
        name: The name of the table to create.
        style: The style to apply to the table.
        **fmtparams: Additional keyword arguments for the `csv.reader` method.

    Returns:
        Table: A new Table object populated with the CSV data.
    """
    if isinstance(path_or_file, (str, Path)):
        content_b: str | bytes = Path(path_or_file).read_bytes()
    elif isinstance(path_or_file, StringIO):
        content_b = path_or_file.getvalue()
    else:
        # Leave the file we were given open
        content_b = path_or_file.read()  # type: ignore[attr-defined]
    if isinstance(content_b, bytes):
        content = content_b.decode()
    else:
        content = content_b
    return Table.from_csv(content=content, name=name, style=style, **fmtparams)