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,

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__

Initialize 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

append_row

Append a row to the end of the table.

clear

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

del_span

Delete a cell span.

delete_cell

Delete the cell at the given coordinates, shifting subsequent

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.

from_dict

Create a new Table object from a dictionary or list of

from_json

Import JSON content 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

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

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

get_row

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

get_row_sub_elements

Get the list of cell contents for the row at index “y” or Row

get_row_values

Get the list of Python values for the cells of the row at the

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

insert_cell

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

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

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

iter_columns

Yield column elements, expanding repetitions.

iter_rows

Yield row elements, expanding repetitions.

iter_values

Yield lists of values of rows.

lstrip

Remove top empty rows and left-side empty cells from the table

normalize_columns

Ensure that table:table-column definitions cover the full width of

optimize_height

Remove bottom empty rows in-place.

optimize_width

Remove right-side empty cells in-place.

rstrip

Remove empty rows and right-side empty cells from the table

set_cell

Replace the cell at the given coordinates.

set_cell_image

Insert an image in a cell (deprecated, use recipes instead).

set_cells

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

set_column

Replace the column at the given ‘x’ position.

set_column_cells

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

set_column_values

Set the Python values for the cells in the column at the given ‘x’

set_named_range

Create and insert a named range, replacing any existing one with

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

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.

strip

Remove empty rows and columns from top, bottom, left, and right

to_csv

Export the table as a CSV string or file.

to_dict

Export table data as a Python dictionary or list of dictionaries.

to_json

Export the table values as a JSON string or file.

to_markdown

Export the table content as a Markdown string.

transpose

Swap rows and columns of the table in-place.

Attributes:

Name Type Description
cells list[list[Cell]]

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

columns list[Column]

Get a list of all columns in the table.

headers list[CellValue | None]

Return the first row of table values (column headers) after rstrip.

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.

shape tuple[int, int]

Return the dimensions (rows, columns) of the table after rstrip

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
values list[list[CellValue | None]]

Get or set the matrix of cell values of the table.

width int

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

Source code in odfdo/table.py
 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
2769
2770
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
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
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:
        """Initialize a Table element.

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

        The `Table.name` attribute is not mandatory (per ODF 1.4 standard).
        However, an unnamed table is not recommended for spreadsheet tables:
        such tables cannot support named cell ranges or be referenced by
        formulas, and loading the document with certain tools (such as
        LibreOffice) will result in a default name being assigned to unnamed
        tables. Similarly, having multiple tables with the same name or no
        name is discouraged for the same reasons. Finally, setting table name
        to None on a table with named ranges is not a good idea, as existing
        named ranges will remain pending with their previous table name.

        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:
            if name is not None:
                # allow tables with no names. Tables with no names can not
                # have named ranges
                self.name = name
            if protected:
                self.protected = protected
                if protection_key is None:
                    msg = "A protection_key must be provided for protected tables"
                    raise ValueError(msg)
                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)

        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 (preserving table name if set).
        """
        name = self.name
        self._xml_element.clear()
        if name:
            self.name = name
        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)
        if self._table_cache.col_map_length() == 0 and self._table_cache.height() > 0:
            self.normalize_columns()

    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._table_cache.width()
        if diff > 0:
            self.append_column(Column(repeated=diff))
        self._table_cache.cached_width = None

    def normalize_columns(self) -> None:
        """Ensure that table:table-column definitions cover the full width of
        the rows.

        If the table lacks table:table-column elements or if the existing
        columns do not cover the maximum width of the rows, default column
        definitions are appended to match the maximum row width.
        """
        rows = self._get_rows()
        if not rows:
            return
        max_row_width = max((row.width for row in rows), default=0)
        col_width = self._table_cache.width()
        diff = max_row_width - col_width
        if diff > 0:
            self.append_column(Column(repeated=diff))
        self._table_cache.cached_width = None

    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
        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(("-", "..")):
                        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, str_or_element: 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:
            str_or_element (Element | str): The Row or Column to append.

        """
        if isinstance(str_or_element, Row):
            self.append_row(str_or_element)
        elif isinstance(str_or_element, Column):
            self.append_column(str_or_element)
        else:
            # probably still an error
            self._append(str_or_element)

    @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 and row contents.

        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.

        """
        cached = self._table_cache.cached_width
        if cached is not None:
            return cached
        # known columns width
        col_width = self._table_cache.width()
        if self._table_cache.height() == 0:
            self._table_cache.cached_width = col_width
            return col_width
        # secure computation (do not trust table-column computation)
        rows = self._get_rows()
        max_row_width = max(
            col_width, max((row.width for row in rows), default=col_width)
        )
        self._table_cache.cached_width = max_row_width
        return max_row_width

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

        Example:
            | reference | color | price |
            |-----------|-------|-------|
            | ref01     | white | 10,00 |
            | ref02     | blue  | 20,50 |
            | ref03     | red   | 25,75 |

        >>> table.size
        (3, 4)

        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:
        if name is None:
            # Setting table name to None on a table with named ranges is not a
            #  good idea, as existing named ranges will remain pending with
            # their previous table name.
            self.del_attribute("table:name")
            return
        valid_name = table_name_check(name)
        # first, update named ranges if table already had a name
        # fixme : delete name ranges when deleting table, too.
        if self.name:
            for named_range in self.get_named_ranges(table_name=self.name):
                named_range.set_table_name(valid_name)
        self.set_attribute("table:name", valid_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("str | None", 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("str | None", 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

    @property
    def values(self) -> list[list[CellValue | None]]:
        """Get or set the matrix of cell values of the table.

        When getting, the type of each cell value is inferred from the
        'office:value-type' attribute.

        When setting, the type of the provided Python value determines the
        'office:value-type' of each cell. If the provided values do not cover
        the entire area of the table, the previous values are retained.
        Objects of type "str" are not treated as iterables.

        Note: the cell style content is kept when using cell values.
        To ensure an absolute empty table, use Table.clear().

        Example:
            | reference | color | price |
            |-----------|-------|-------|
            | ref01     | white | 10,00 |
            | ref02     | blue  | 20,50 |
            | ref03     | red   | 25,75 |

        >>> table.values
        [['reference', 'color', 'price'], ['ref01', 'white', 10], ['ref02',
        'blue', Decimal('20.5')], ['ref03', 'red', Decimal('25.75')]]

        Returns:
            list[list[CellValue | None]]:
                The 2D matrix of values of cells in their appropriate Python
                type.

        """
        return self.get_values()

    @values.setter
    def values(self, values: Iterable[Iterable[CellValue | None]]) -> None:
        self.set_values(values)

    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: Iterable[Iterable[CellValue | None]],
        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 an iterable
        of iterables, where each inner iterable represents a row. If the
        provided values do not cover the entire area of the table, the
        previous values are retained. Objects of type "str" are not treated
        as iterables.

        Args:
            values: An iterable of iterables 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
        if not isiterable(values):
            # guard against str iterable
            values = [values]  # ty: ignore
        for row_values in values:
            y += 1
            if row_values is None:
                continue
            val_list: Any
            # isiterable excludes str and bytes, avoiding splitting strings into chars
            if isiterable(row_values):
                val_list = list(row_values)
                if not val_list:
                    continue
            else:
                val_list = row_values
            row = self.get_row(y, clone=True)
            repeated = row.repeated or 1
            if repeated >= 2:
                row.repeated = None
            row.set_values(
                val_list,
                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 (value is None) 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)
            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
                column.parent.delete(column)
                diff = -repeated
                if diff == 0:
                    break
        # raz cache of columns
        self._table_cache.clear_col_indexes()
        self._compute_table_cache()

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

        A cell is considered empty if it has no value (value is None) and no
        style (or style is ignored when `aggressive=True`).

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

        """
        # Step 1: remove empty rows at the top of the table
        while True:
            rows = self._get_rows()
            if not rows:
                break
            if rows[0].is_empty(aggressive=aggressive):
                row0 = rows[0]
                row0.parent.delete(row0)
                self._table_cache.clear_row_indexes()
            else:
                break

        rows = self._get_rows()
        if not rows:
            self._compute_table_cache()
            return

        # Step 2: find minimum leading empty cells across all rows
        min_leading_empty: int = 2**30
        for row in rows:
            leading = 0
            for cell in row._get_cells():
                if cell.is_empty(aggressive=aggressive):
                    leading += cell.repeated or 1
                else:
                    break
            if leading < min_leading_empty:
                min_leading_empty = leading
                if min_leading_empty == 0:
                    break

        # Step 3: delete min_leading_empty columns from the left
        if min_leading_empty > 0:
            for _ in range(min_leading_empty):
                self.delete_column(0)

        self._table_cache.clear_row_indexes()
        self._table_cache.clear_col_indexes()
        self._compute_table_cache()

    def strip(self, aggressive: bool = False) -> None:
        """Remove empty rows and columns from top, bottom, left, and right
        in-place.

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

        """
        self.rstrip(aggressive=aggressive)
        self.lstrip(aggressive=aggressive)

    def optimize_height(self) -> None:
        """Remove bottom empty rows in-place.

        This method keeps the repeated styles of empty cells but minimizes the
        table height to fit the actual content.
        """
        self._optimize_height_trim_rows()

    def optimize_width(self) -> None:
        """Remove 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.
        """
        width = self._optimize_width_length()
        self._optimize_width_rstrip_rows(width)
        self._optimize_width_adapt_columns(width)

    def _optimize_height_trim_rows(self) -> None:
        for row in reversed(self._get_rows()):
            if not row.has_values():
                if row.repeated:
                    row._set_repeated(None)
            else:
                break
        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)
                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()
        self._compute_table_cache()

    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
                column.parent.delete(column)
                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.

        """
        if self.width == 0 or self.height == 0:
            return
        data = []
        if coord is None:
            data = [row.cells for row in self.iter_rows()]
            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 (value is None) 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()
            msg = "Row not found"
            raise ValueError(msg)
        row = self._get_row2_base(y)
        if row is None:
            msg = "Row not found"
            raise ValueError(msg)
        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)  # ty: ignore[invalid-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).

        By default, 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)
        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: Iterable[Row] | None = None) -> None:
        """Append a list of rows to the end of the table.

        Args:
            rows: An iterable of Row elements to append.

        """
        if rows is None:
            rows = []
        self.extend(rows)
        self._compute_table_cache()
        # Update width if necessary
        self.normalize_columns()

    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[CellValue | tuple[CellValue | None, str | None] | None]:
        """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 | Row) -> list[Any]:
        """Get the list of cell contents for the row at index "y" or Row
        object (internal).

        The list is padded to "table.width".

        For each column in the row:
        - If the cell contains non-empty child text elements ("<text:p>"),
          returns the list of child elements "[Element, ...]".
        - If the cell is empty or contains non-text content, returns the
          Cell object itself.
        - If the column index extends beyond the row boundary up to
          "table.width", returns "[]".

        Args:
            y: The row index (0-based) or Row element.

        Returns:
            list[Any]: A list of child element lists, Cell objects, or []
                padded to match the table's width.

        """
        row = y if isinstance(y, Row) else self.get_row(y, clone=False)
        cells = row.get_cells()
        values: list[Any] = []
        for cell in cells:
            children = cell.children
            if children and any(getattr(e, "inner_text", "").strip() for e in children):
                values.append(children)
            else:
                values.append(cell)
        if len(values) < self.width:
            values.extend([[]] * (self.width - len(values)))
        return values

    def set_row_values(
        self,
        y: int | str,
        values: Iterable[CellValue | None],
        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: An iterable 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 = self.get_row(y)
        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: Iterable[Cell] | 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: An iterable 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 (value is None) 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
        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[list[Cell]]:
        """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.

        """
        return [row.cells for row in self.iter_rows()]

    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,
    ) -> CellValue | tuple[CellValue | None, str | None] | None:
        """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:
            CellValue | tuple[CellValue | None, str | None] | None:
                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
        # 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[Iterable[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 an iterable of iterables, where each inner iterable
        represents a row.

        Args:
            cells: An iterable of iterables 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
        if not isiterable(cells):
            cells = [cells]  # ty: ignore
        for row_cells in cells:
            y += 1
            if row_cells is None:
                continue
            cell_list: Any
            # isiterable excludes str and bytes, and returns False for single Cell
            if isiterable(row_cells):
                cell_list = list(row_cells)
                if not cell_list:
                    continue
            else:
                cell_list = [row_cells]
            row = self.get_row(y, clone=True)
            repeated = row.repeated or 1
            if repeated >= 2:
                row.repeated = None
            row.set_cells(cast("Iterable[Cell]", cell_list), start=x, clone=clone)
            self.set_row(y, row, clone=False)
            self._update_width(row)

    def set_value(
        self,
        coord: tuple | list | str,
        value: CellValue | None,
        cell_type: str | None = None,
        currency: str | None = None,
        style: str | None = None,
        formula: 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.
            formula: The formula to set for the cell.

        """
        # raise VAlue Error in get_cell if wrong coordinates
        # always returns a Cell
        current = self.get_cell(coord, clone=False)
        cell = current.clone
        cell.repeated = None
        cell.set_value(
            value,
            cell_type=cell_type,
            currency=currency,
            formula=formula,
        )
        if style:
            cell.style = style
        self.set_cell(coord, cell, clone=False)

    def set_cell_image(
        self,
        coord: tuple | list | str,
        image_frame: Frame,
        doc_type: str | None = None,
    ) -> None:
        """Insert an image in a cell (deprecated, use recipes instead).

        See recipes:
            - add_an_image_to_a_table_inside_spreadsheet.py
            - add_an_image_to_a_table_inside_text_document.py

        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:
                msg = "Document type not found"
                raise ValueError(msg)
            doc_type = {"office:spreadsheet": "spreadsheet", "office:text": "text"}.get(
                body.tag
            )
            if doc_type is None:
                msg = "Document type not supported for images"
                raise ValueError(msg)
        # 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
        # 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
        while x < min(end, self.width - 1):
            x += 1
            if x < start:
                continue
            col = Column()
            col.x = x
            yield col

    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 XML-defined columns ?
        if x >= self._table_cache.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)
            if column is None:
                return None
            self._table_cache.store_col(cast("Column", column), idx)
        return cast("Column", 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
        col_width = self._table_cache.width()
        diff = x - col_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)
        self._table_cache.clear_col_indexes()
        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)
        col_width = self._table_cache.width()
        diff = x - col_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!
        self._table_cache.clear_row_indexes()
        self._table_cache.clear_col_indexes()
        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
            for idx, child in enumerate(self.children):
                if child.tag in (
                    "table:table-row",
                    "table:table-row-group",
                    "table:table-header-rows",
                    "table:table-rows",
                ):
                    position = idx
                    break
        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._table_cache.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)
        self._table_cache.clear_col_indexes()
        # 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
        col_width = self._table_cache.width()
        if x < col_width:
            self._table_cache.delete_col_in_cache(x, self)
        # Update width
        for row in self._get_rows():
            if row.width > x:
                row.delete_cell(x)
        self._table_cache.clear_row_indexes()
        self._table_cache.clear_col_indexes()

    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))  # noqa: PERF401
            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[CellValue | tuple[CellValue | None, str | None] | None]:
        """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[CellValue | tuple[CellValue | None, str | None] | None]:
                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[CellValue | tuple[CellValue | None, str | None] | None] = []
        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: Iterable[Cell]) -> None:
        """Set the cells for the column at the given 'x' position.

        The provided iterable of cells must yield the same number of items as
        the table's height.

        Args:
            x: The 0-based index or alphabetical representation of the column.
            cells: An iterable of Cell elements to set.

        """
        cells_list = list(cells)
        height = self.height
        if len(cells_list) != height:
            msg = f"Column height mismatch: {height} cells expected"
            raise ValueError(msg)
        cells_iterator = iter(cells_list)
        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: Iterable[CellValue | None],
        cell_type: str | None = None,
        currency: str | None = None,
        style: str | None = None,
    ) -> None:
        """Set the Python values for the cells in the column at the given 'x'
        position.

        The provided iterable of values must yield the same number of items as
        the table's height.

        Args:
            x: The 0-based index or alphabetical representation of the column.
            values: An iterable 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 (value is None) 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]:
        """Return the list of local Name Ranges (internal)."""
        return cast(
            "list[NamedRange]",
            self.get_elements("descendant::table:named-expressions/table:named-range"),
        )

    def _local_named_range(self, name: str) -> NamedRange | None:
        """Return the local Name Range of the specified name (internal)."""
        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])
        return None

    def _local_append_named_range(self, named_range: NamedRange) -> None:
        """Append the named range to the current table (internal)."""
        named_expressions = cast(
            "TableNamedExpressions | None",
            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:
        """Create a Named Range element and insert it in the table (internal).
        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:
        """Delete the Named Range of specified name (internal)."""
        named_range = self._local_named_range(name)
        if not named_range:
            return
        named_range.delete()
        named_expressions = cast(
            "TableNamedExpressions | None",
            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()
        else:
            named_ranges = self._local_named_ranges()
        if not table_name:
            return named_ranges
        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:
                msg = "Table is not inside a document"
                raise ValueError(msg)
            if not body.allow_named_range:
                return None
            nr: NamedRange | None = body.get_named_range(name)

        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:
                msg = "Table is not inside a document"
                raise ValueError(msg)
            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)
        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:
            msg = "Name required"
            raise ValueError(msg)
        if global_scope:
            body = self.document_body
            if not body:
                msg = "Table is not inside a document"
                raise ValueError(msg)
            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(
                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:
            msg = "Name required"
            raise ValueError(msg)
        if global_scope:
            body = self.document_body
            if not body:
                msg = "Table is not inside a document"
                raise ValueError(msg)
            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)
        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(  # noqa:PERF401
                    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])  # ty: ignore[invalid-argument-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

    #
    # Import/export API
    #

    @property
    def shape(self) -> tuple[int, int]:
        """Return the dimensions (rows, columns) of the table after rstrip
        optimization.

        The table remains unchanged.

        Example:
            | reference | color | price |
            |-----------|-------|-------|
            | ref01     | white | 10,00 |
            | ref02     | blue  | 20,50 |
            | ref03     | red   | 25,75 |

        >>> table.shape
        (4, 3)

        Returns:
            The (height, width) tuple of the table.

        """
        cloned_table = self.clone
        cloned_table.rstrip(aggressive=True)
        return (cloned_table.height, cloned_table.width)

    @property
    def headers(self) -> list[CellValue | None]:  # ty: ignore[invalid-property-type-override]
        """Return the first row of table values (column headers) after rstrip.

        The table remains unchanged.

        Example:
            | reference | color | price |
            |-----------|-------|-------|
            | ref01     | white | 10,00 |
            | ref02     | blue  | 20,50 |
            | ref03     | red   | 25,75 |

        >>> table.headers
        ['reference', 'color', 'price']

        Returns:
            List of column header values, or empty list if the table has no
            rows.

        """
        cloned_table = self.clone
        cloned_table.rstrip(aggressive=True)
        values = cloned_table.values
        return values[0] if values else []

    def to_dict(
        self,
        orient: str = "list",
        header: bool = True,
        mode: str = "python",
        lstrip: bool = False,
        no_decimal: bool = False,
        no_date: bool = False,
        no_nan: bool = False,
    ) -> dict[str, Any] | list[dict[str, Any]]:
        """Export table data as a Python dictionary or list of dictionaries.

        Args:
            orient: Format of the output:
                - "list" (default): Columnar dict `{"col": [values, ...]}`.
                - "records": List of row dicts `[{"col": value, ...}, ...]`.
                - "matrix": Dict with table name `{"TableName": [[...], ...]}`.
            header: (for orientation "list" or "records"). If True, uses the
                first row of data as column header keys. If False, column keys
                are generated as "0", "1", "2", ...
            mode: Serialization mode ("python" or "json"). Defaults
                to "python".
            lstrip: If True, also removes leading empty rows and columns from
                the top-left before export.
            no_decimal: If True in "python" mode, convert Decimal values to
                float or int.
            no_date: If True in "python" mode, convert date, datetime, and
                timedelta values to ODF/ISO formatted strings.
            no_nan: If True in "python" mode, convert NaN and infinity values
                to None.

        Example:
            | reference | color | price |
            |-----------|-------|-------|
            | ref01     | white | 10,00 |
            | ref02     | blue  | 20,50 |
            | ref03     | red   | 25,75 |

        >>> table.to_dict()
        {
            'reference': ['ref01', 'ref02', 'ref03'],
            'color': ['white', 'blue', 'red'],
            'price': [10, Decimal('20.5'), Decimal('25.75')]
        }

        >>> table.to_dict(orient="records")
        [
            {'reference': 'ref01', 'color': 'white', 'price': 10},
            {'reference': 'ref02', 'color': 'blue', 'price': Decimal('20.5')},
            {'reference': 'ref03', 'color': 'red', 'price': Decimal('25.75')}
        ]

        >>> table.to_dict(orient="matrix")
        {
            'product': [
                ['reference', 'color', 'price'],
                ['ref01', 'white', 10],
                ['ref02', 'blue', Decimal('20.5')],
                ['ref03', 'red', Decimal('25.75')]
            ]
        }

        Returns:
            The table data formatted as a dictionary or list of dicts.

        Raises:
            ValueError: If `orient` is not one of "list", "records", or "matrix".

        """
        match orient:
            case "list":
                return self._to_dict_list(
                    header=header,
                    mode=mode,
                    lstrip=lstrip,
                    no_decimal=no_decimal,
                    no_date=no_date,
                    no_nan=no_nan,
                )
            case "records":
                return self._to_dict_records(
                    header=header,
                    mode=mode,
                    lstrip=lstrip,
                    no_decimal=no_decimal,
                    no_date=no_date,
                    no_nan=no_nan,
                )
            case "matrix":
                return self._to_dict_matrix(
                    mode=mode,
                    lstrip=lstrip,
                    no_decimal=no_decimal,
                    no_date=no_date,
                    no_nan=no_nan,
                )
            case _:
                msg = (
                    f"Invalid orient parameter: {orient!r}. "
                    "Expected 'list', 'records', or 'matrix'"
                )
                raise ValueError(msg)

    def _to_dict_list(
        self,
        header: bool,
        mode: str,
        lstrip: bool,
        no_decimal: bool,
        no_date: bool,
        no_nan: bool,
    ) -> dict[str, list[Any]]:
        rows = serialize_table(
            self,
            mode=mode,
            lstrip=lstrip,
            no_decimal=no_decimal,
            no_date=no_date,
            no_nan=no_nan,
        )
        if not rows:
            return {}

        if header:
            headers = [
                str(h) if h is not None and str(h) != "" else f"Unnamed: {i}"
                for i, h in enumerate(rows[0])
            ]
            data_rows = rows[1:]
        else:
            headers = [str(i) for i in range(len(rows[0]))]
            data_rows = rows

        unifyer = NameUnifyer()
        unique_headers = [unifyer.unique(h) for h in headers]

        res_dict: dict[str, list[Any]] = {h: [] for h in unique_headers}
        for row in data_rows:
            for i, h in enumerate(unique_headers):
                val = row[i] if i < len(row) else None
                res_dict[h].append(val)
        return res_dict

    def _to_dict_records(
        self,
        header: bool,
        mode: str,
        lstrip: bool,
        no_decimal: bool,
        no_date: bool,
        no_nan: bool,
    ) -> list[dict[str, Any]]:
        rows = serialize_table(
            self,
            mode=mode,
            lstrip=lstrip,
            no_decimal=no_decimal,
            no_date=no_date,
            no_nan=no_nan,
        )
        if not rows:
            return []

        if header:
            headers = [
                str(h) if h is not None and str(h) != "" else f"Unnamed: {i}"
                for i, h in enumerate(rows[0])
            ]
            data_rows = rows[1:]
        else:
            headers = [str(i) for i in range(len(rows[0]))]
            data_rows = rows

        unifyer = NameUnifyer()
        unique_headers = [unifyer.unique(h) for h in headers]

        res_records: list[dict[str, Any]] = []
        for row in data_rows:
            record: dict[str, Any] = {}
            for i, h in enumerate(unique_headers):
                record[h] = row[i] if i < len(row) else None
            res_records.append(record)
        return res_records

    def _to_dict_matrix(
        self, mode: str, lstrip: bool, no_decimal: bool, no_date: bool, no_nan: bool
    ) -> dict[str, list[list[Any]]]:
        rows = serialize_table(
            self,
            mode=mode,
            lstrip=lstrip,
            no_decimal=no_decimal,
            no_date=no_date,
            no_nan=no_nan,
        )
        name = self.name
        if not name:
            unifyer = NameUnifyer()
            name = unifyer.unique()
        return {name: rows}

    @classmethod
    def from_dict(
        cls,
        data: dict[str, Any] | list[dict[str, Any]],
        name: str | None = None,
        guess_type: bool = False,
    ) -> Table:
        """Create a new Table object from a dictionary or list of
        dictionaries.

        Accepts:
        - Columnar dict: `{"Col1": [val1, val2], "Col2": [val3, val4]}`
        - List of records: `[{"Col1": val1, "Col2": val3}, {"Col1": val2,
            "Col2": val4}]`
        - Matrix dict: `{"SheetName": [[val1, val2], [val3, val4]]}`

        Args:
            data: The dictionary or list of dicts to import.
            name: Name of the table to create.
            guess_type: If True, try to detect Python type from strings
                values (int, float, dates).

        Returns:
            A new Table populated with the dictionary data.

        Raises:
            TypeError: If data is not a dict or list of dicts.

        """
        if isinstance(data, dict):
            return cls._from_dict_dict(data, name, guess_type)
        if isinstance(data, list):
            return cls._from_dict_list(data, name, guess_type)
        msg = "Data must be a dict or list of dicts"
        raise TypeError(msg)

    @classmethod
    def _from_dict_dict(
        cls, data: dict[str, Any], name: str | None, guess_type: bool
    ) -> Table:
        if not data:
            return cls(name or "Table")
        first_val = next(iter(data.values()))
        if (
            len(data) == 1
            and isinstance(first_val, list)
            and (not first_val or isinstance(first_val[0], list))
        ):
            table_name = name or next(iter(data.keys()))
            table = cls(table_name)
            if guess_type:
                _populate_table(table, first_val)
            else:
                _populate_table_keep_strings(table, first_val)
            return table

        headers = list(data.keys())
        columns_data = [data[h] for h in headers]
        max_len = max(
            (len(col) if isinstance(col, (list, tuple)) else 1 for col in columns_data),
            default=0,
        )
        rows: list[list[Any]] = [headers]
        for row_idx in range(max_len):
            row = [
                columns_data[col_idx][row_idx]
                if isinstance(columns_data[col_idx], (list, tuple))
                and row_idx < len(columns_data[col_idx])
                else columns_data[col_idx]
                if not isinstance(columns_data[col_idx], (list, tuple)) and row_idx == 0
                else None
                for col_idx in range(len(headers))
            ]
            rows.append(row)
        table = cls(name or "Table")
        if guess_type:
            _populate_table(table, rows)
        else:
            _populate_table_keep_strings(table, rows)
        return table

    @classmethod
    def _from_dict_list(
        cls, data: list[dict[str, Any]], name: str | None, guess_type: bool
    ) -> Table:
        if not data:
            return cls(name or "Table")
        first = data[0]
        if not isinstance(first, dict):
            msg = "List elements must be dictionaries"
            raise TypeError(msg)
        headers = list(
            dict.fromkeys(
                k for record in data if isinstance(record, dict) for k in record
            )
        )
        rows = [headers]
        for record in data:
            if not isinstance(record, dict):
                msg = "List elements must be dictionaries"
                raise TypeError(msg)
            row = [record.get(h) for h in headers]
            rows.append(row)
        table = cls(name or "Table")
        if guess_type:
            _populate_table(table, rows)
        else:
            _populate_table_keep_strings(table, rows)
        return table

    def to_markdown(self) -> str:
        """Export the table content as a Markdown string.

        Example:
            | reference | color | price |
            |-----------|-------|-------|
            | ref01     | white | 10,00 |
            | ref02     | blue  | 20,50 |
            | ref03     | red   | 25,75 |

        Returns:
            str: The Markdown representation of the table.

        """
        was_initialized = "document" in MD_GLOBAL and MD_GLOBAL["document"] is not None
        if not was_initialized:
            _set_global(None)
        try:
            return self._md_format()
        finally:
            if not was_initialized:
                _set_global(None)

    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.

        Example:
            | reference | color | price |
            |-----------|-------|-------|
            | ref01     | white | 10,00 |
            | ref02     | blue  | 20,50 |
            | ref03     | red   | 25,75 |

        >>> print(table.to_csv())
        reference,color,price
        ref01,white,10
        ref02,blue,20.5
        ref03,red,25.75

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

        """
        rows = serialize_table(self, "csv")
        content = StringIO(newline="")
        csv_writer = csv.writer(content, dialect=dialect, **fmtparams)
        for row in rows:
            csv_writer.writerow(row)

        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)
        table.clear()

        def _read_lines() -> Iterator[list[str]]:
            for line in reader:
                while line and not line[-1].strip():
                    line.pop()
                yield line

        _populate_table(table, _read_lines())
        return table

    def to_json(
        self,
        path_or_file: str | Path | None = None,
        pretty: bool = False,
        ensure_ascii: bool = False,
    ) -> str | None:
        """Export the table values as a JSON string or file.

        Args:
            path_or_file: The path or file to save the JSON content to.
                If None, the JSON content is returned as a string.
            pretty: Use pretty formater. Defaults to False.
            ensure_ascii: If True, non-ASCII characters are escaped. Defaults
                to False.

        Example:
            | reference | color | price |
            |-----------|-------|-------|
            | ref01     | white | 10,00 |
            | ref02     | blue  | 20,50 |
            | ref03     | red   | 25,75 |

        >>> print(table.to_json(pretty=True))
        {
          "product": [
            ["reference", "color", "price"],
            ["ref01", "white", 10],
            ["ref02", "blue", 20.5],
            ["ref03", "red", 25.75]
          ]
        }

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

        """
        rows = serialize_table(self, "json")
        name = self.name
        if not name:
            unifyer = NameUnifyer()
            name = unifyer.unique()
        data: Any = {name: rows}
        if pretty:
            content = format_json(data, ensure_ascii=ensure_ascii)
        else:
            content = json.dumps(data, ensure_ascii=ensure_ascii, allow_nan=False)
        if path_or_file:
            Path(path_or_file).write_text(content, encoding="utf-8")
            return None
        return content

    def _serialize_table_rows(self) -> list[list[CellValue | None]]:
        return serialize_table(self, "json")

    @classmethod
    def from_json(
        cls,
        content: str | dict[str, list[list[Any]]] | list[list[Any]],
        name: str | None = "",
    ) -> Table:
        """Import JSON content into a new Table object.

        Args:
            content: A JSON string, dictionary `{table_name: [[...], ...]}` or
                2D list `[[...], ...]`.
            name: Name of table to create. If None, uses key from dict or
                "Sheet".

        Returns:
            Table: A new Table object populated with the JSON data.

        """
        if isinstance(content, str):
            data = json.loads(content)
        else:
            data = content

        unifyer = NameUnifyer()
        if isinstance(data, dict):
            if not data:
                table_name = unifyer.unique(name or "")
                rows_data: list[list[Any]] = []
            else:
                key = next(iter(data))
                table_name = unifyer.unique(key)
                rows_data = data[key]
        elif isinstance(data, list):
            table_name = unifyer.unique(name or "")
            rows_data = data
        else:
            msg = "JSON content must be a dict, list, or valid JSON string"
            raise TypeError(msg)

        table = cls(table_name)
        table.clear()
        _populate_table(table, rows_data)
        return table

_append class-attribute instance-attribute

_append = Element.append

_table_cache instance-attribute

_table_cache = TableCache()

_tag class-attribute instance-attribute

_tag = 'table:table'

cells property

cells: list[list[Cell]]

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

Returns:

Name Type Description
list list[list[Cell]]

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.

headers property

headers: list[CellValue | None]

Return the first row of table values (column headers) after rstrip.

The table remains unchanged.

Example
reference color price
ref01 white 10,00
ref02 blue 20,50
ref03 red 25,75

table.headers [‘reference’, ‘color’, ‘price’]

Returns:

Type Description
list[CellValue | None]

List of column header values, or empty list if the table has no

list[CellValue | None]

rows.

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.

shape property

shape: tuple[int, int]

Return the dimensions (rows, columns) of the table after rstrip optimization.

The table remains unchanged.

Example
reference color price
ref01 white 10,00
ref02 blue 20,50
ref03 red 25,75

table.shape (4, 3)

Returns:

Type Description
tuple[int, int]

The (height, width) tuple of the table.

size property

size: tuple[int, int]

Get the current width and height of the table.

Example
reference color price
ref01 white 10,00
ref02 blue 20,50
ref03 red 25,75

table.size (3, 4)

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

values property writable

values: list[list[CellValue | None]]

Get or set the matrix of cell values of the table.

When getting, the type of each cell value is inferred from the ‘office:value-type’ attribute.

When setting, the type of the provided Python value determines the ‘office:value-type’ of each cell. If the provided values do not cover the entire area of the table, the previous values are retained. Objects of type “str” are not treated as iterables.

Note: the cell style content is kept when using cell values. To ensure an absolute empty table, use Table.clear().

Example
reference color price
ref01 white 10,00
ref02 blue 20,50
ref03 red 25,75

table.values [[‘reference’, ‘color’, ‘price’], [‘ref01’, ‘white’, 10], [‘ref02’, ‘blue’, Decimal(‘20.5’)], [‘ref03’, ‘red’, Decimal(‘25.75’)]]

Returns:

Type Description
list[list[CellValue | None]]

list[list[CellValue | None]]: The 2D matrix of values of cells in their appropriate Python type.

width property

width: int

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

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

Initialize a Table element.

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

The Table.name attribute is not mandatory (per ODF 1.4 standard). However, an unnamed table is not recommended for spreadsheet tables: such tables cannot support named cell ranges or be referenced by formulas, and loading the document with certain tools (such as LibreOffice) will result in a default name being assigned to unnamed tables. Similarly, having multiple tables with the same name or no name is discouraged for the same reasons. Finally, setting table name to None on a table with named ranges is not a good idea, as existing named ranges will remain pending with their previous table name.

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
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
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:
    """Initialize a Table element.

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

    The `Table.name` attribute is not mandatory (per ODF 1.4 standard).
    However, an unnamed table is not recommended for spreadsheet tables:
    such tables cannot support named cell ranges or be referenced by
    formulas, and loading the document with certain tools (such as
    LibreOffice) will result in a default name being assigned to unnamed
    tables. Similarly, having multiple tables with the same name or no
    name is discouraged for the same reasons. Finally, setting table name
    to None on a table with named ranges is not a good idea, as existing
    named ranges will remain pending with their previous table name.

    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:
        if name is not None:
            # allow tables with no names. Tables with no names can not
            # have named ranges
            self.name = name
        if protected:
            self.protected = protected
            if protection_key is None:
                msg = "A protection_key must be provided for protected tables"
                raise ValueError(msg)
            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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
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)

    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
494
495
496
497
498
499
500
501
502
503
504
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)
    if self._table_cache.col_map_length() == 0 and self._table_cache.height() > 0:
        self.normalize_columns()

_from_dict_dict classmethod

_from_dict_dict(
    data: dict[str, Any], name: str | None, guess_type: bool
) -> Table
Source code in odfdo/table.py
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
@classmethod
def _from_dict_dict(
    cls, data: dict[str, Any], name: str | None, guess_type: bool
) -> Table:
    if not data:
        return cls(name or "Table")
    first_val = next(iter(data.values()))
    if (
        len(data) == 1
        and isinstance(first_val, list)
        and (not first_val or isinstance(first_val[0], list))
    ):
        table_name = name or next(iter(data.keys()))
        table = cls(table_name)
        if guess_type:
            _populate_table(table, first_val)
        else:
            _populate_table_keep_strings(table, first_val)
        return table

    headers = list(data.keys())
    columns_data = [data[h] for h in headers]
    max_len = max(
        (len(col) if isinstance(col, (list, tuple)) else 1 for col in columns_data),
        default=0,
    )
    rows: list[list[Any]] = [headers]
    for row_idx in range(max_len):
        row = [
            columns_data[col_idx][row_idx]
            if isinstance(columns_data[col_idx], (list, tuple))
            and row_idx < len(columns_data[col_idx])
            else columns_data[col_idx]
            if not isinstance(columns_data[col_idx], (list, tuple)) and row_idx == 0
            else None
            for col_idx in range(len(headers))
        ]
        rows.append(row)
    table = cls(name or "Table")
    if guess_type:
        _populate_table(table, rows)
    else:
        _populate_table_keep_strings(table, rows)
    return table

_from_dict_list classmethod

_from_dict_list(
    data: list[dict[str, Any]],
    name: str | None,
    guess_type: bool,
) -> Table
Source code in odfdo/table.py
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
@classmethod
def _from_dict_list(
    cls, data: list[dict[str, Any]], name: str | None, guess_type: bool
) -> Table:
    if not data:
        return cls(name or "Table")
    first = data[0]
    if not isinstance(first, dict):
        msg = "List elements must be dictionaries"
        raise TypeError(msg)
    headers = list(
        dict.fromkeys(
            k for record in data if isinstance(record, dict) for k in record
        )
    )
    rows = [headers]
    for record in data:
        if not isinstance(record, dict):
            msg = "List elements must be dictionaries"
            raise TypeError(msg)
        row = [record.get(h) for h in headers]
        rows.append(row)
    table = cls(name or "Table")
    if guess_type:
        _populate_table(table, rows)
    else:
        _populate_table_keep_strings(table, rows)
    return table

_get_column2

_get_column2(x: int) -> Column | None
Source code in odfdo/table.py
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
def _get_column2(self, x: int) -> Column | None:
    # Outside the XML-defined columns ?
    if x >= self._table_cache.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)
        if column is None:
            return None
        self._table_cache.store_col(cast("Column", column), idx)
    return cast("Column", column.clone)

_get_columns

_get_columns() -> list[Column]
Source code in odfdo/table.py
2240
2241
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
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
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
def _get_formatted_text_rst(self, context: dict) -> str:
    context["no_img_level"] += 1
    # Strip the table => We must clone
    table: Table = self.clone
    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(("-", "..")):
                    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
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
def _get_row2(self, y: int, clone: bool = True, create: bool = True) -> Row:
    if y >= self.height:
        if create:
            return Row()
        msg = "Row not found"
        raise ValueError(msg)
    row = self._get_row2_base(y)
    if row is None:
        msg = "Row not found"
        raise ValueError(msg)
    if clone:
        return row.clone
    return row

_get_row2_base

_get_row2_base(y: int) -> Row | None
Source code in odfdo/table.py
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
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)  # ty: ignore[invalid-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
1371
1372
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

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

Source code in odfdo/table.py
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
def _local_append_named_range(self, named_range: NamedRange) -> None:
    """Append the named range to the current table (internal)."""
    named_expressions = cast(
        "TableNamedExpressions | None",
        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

Delete the Named Range of specified name (internal).

Source code in odfdo/table.py
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
def _local_delete_named_range(self, name: str) -> None:
    """Delete the Named Range of specified name (internal)."""
    named_range = self._local_named_range(name)
    if not named_range:
        return
    named_range.delete()
    named_expressions = cast(
        "TableNamedExpressions | None",
        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

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

Source code in odfdo/table.py
2714
2715
2716
2717
2718
2719
2720
2721
def _local_named_range(self, name: str) -> NamedRange | None:
    """Return the local Name Range of the specified name (internal)."""
    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])
    return None

_local_named_ranges

_local_named_ranges() -> list[NamedRange]

Return the list of local Name Ranges (internal).

Source code in odfdo/table.py
2707
2708
2709
2710
2711
2712
def _local_named_ranges(self) -> list[NamedRange]:
    """Return the list of local Name Ranges (internal)."""
    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

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

Source code in odfdo/table.py
2740
2741
2742
2743
2744
2745
2746
2747
def _local_set_named_range(
    self, name: str, crange: str | tuple | list, usage: str | None = None
) -> None:
    """Create a Named Range element and insert it in the table (internal).
    current table.
    """
    named_range = NamedRange(name, crange, self.name, usage)
    self._local_append_named_range(named_range)

_optimize_height_trim_rows

_optimize_height_trim_rows() -> None
Source code in odfdo/table.py
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
def _optimize_height_trim_rows(self) -> None:
    for row in reversed(self._get_rows()):
        if not row.has_values():
            if row.repeated:
                row._set_repeated(None)
        else:
            break
    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)
            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()
    self._compute_table_cache()

_optimize_width_adapt_columns

_optimize_width_adapt_columns(width: int) -> None
Source code in odfdo/table.py
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
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
            column.parent.delete(column)
            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
1251
1252
1253
1254
1255
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
1257
1258
1259
def _optimize_width_rstrip_rows(self, width: int) -> None:
    for row in self._get_rows():
        row.force_width(width)

_serialize_table_rows

_serialize_table_rows() -> list[list[CellValue | None]]
Source code in odfdo/table.py
3631
3632
def _serialize_table_rows(self) -> list[list[CellValue | None]]:
    return serialize_table(self, "json")

_to_dict_list

_to_dict_list(
    header: bool,
    mode: str,
    lstrip: bool,
    no_decimal: bool,
    no_date: bool,
    no_nan: bool,
) -> dict[str, list[Any]]
Source code in odfdo/table.py
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
def _to_dict_list(
    self,
    header: bool,
    mode: str,
    lstrip: bool,
    no_decimal: bool,
    no_date: bool,
    no_nan: bool,
) -> dict[str, list[Any]]:
    rows = serialize_table(
        self,
        mode=mode,
        lstrip=lstrip,
        no_decimal=no_decimal,
        no_date=no_date,
        no_nan=no_nan,
    )
    if not rows:
        return {}

    if header:
        headers = [
            str(h) if h is not None and str(h) != "" else f"Unnamed: {i}"
            for i, h in enumerate(rows[0])
        ]
        data_rows = rows[1:]
    else:
        headers = [str(i) for i in range(len(rows[0]))]
        data_rows = rows

    unifyer = NameUnifyer()
    unique_headers = [unifyer.unique(h) for h in headers]

    res_dict: dict[str, list[Any]] = {h: [] for h in unique_headers}
    for row in data_rows:
        for i, h in enumerate(unique_headers):
            val = row[i] if i < len(row) else None
            res_dict[h].append(val)
    return res_dict

_to_dict_matrix

_to_dict_matrix(
    mode: str,
    lstrip: bool,
    no_decimal: bool,
    no_date: bool,
    no_nan: bool,
) -> dict[str, list[list[Any]]]
Source code in odfdo/table.py
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
def _to_dict_matrix(
    self, mode: str, lstrip: bool, no_decimal: bool, no_date: bool, no_nan: bool
) -> dict[str, list[list[Any]]]:
    rows = serialize_table(
        self,
        mode=mode,
        lstrip=lstrip,
        no_decimal=no_decimal,
        no_date=no_date,
        no_nan=no_nan,
    )
    name = self.name
    if not name:
        unifyer = NameUnifyer()
        name = unifyer.unique()
    return {name: rows}

_to_dict_records

_to_dict_records(
    header: bool,
    mode: str,
    lstrip: bool,
    no_decimal: bool,
    no_date: bool,
    no_nan: bool,
) -> list[dict[str, Any]]
Source code in odfdo/table.py
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
def _to_dict_records(
    self,
    header: bool,
    mode: str,
    lstrip: bool,
    no_decimal: bool,
    no_date: bool,
    no_nan: bool,
) -> list[dict[str, Any]]:
    rows = serialize_table(
        self,
        mode=mode,
        lstrip=lstrip,
        no_decimal=no_decimal,
        no_date=no_date,
        no_nan=no_nan,
    )
    if not rows:
        return []

    if header:
        headers = [
            str(h) if h is not None and str(h) != "" else f"Unnamed: {i}"
            for i, h in enumerate(rows[0])
        ]
        data_rows = rows[1:]
    else:
        headers = [str(i) for i in range(len(rows[0]))]
        data_rows = rows

    unifyer = NameUnifyer()
    unique_headers = [unifyer.unique(h) for h in headers]

    res_records: list[dict[str, Any]] = []
    for row in data_rows:
        record: dict[str, Any] = {}
        for i, h in enumerate(unique_headers):
            record[h] = row[i] if i < len(row) else None
        res_records.append(record)
    return res_records

_translate_cell_coordinates

_translate_cell_coordinates(
    coord: tuple | list | str,
) -> tuple[int | None, int | None]
Source code in odfdo/table.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
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
467
468
469
470
471
472
473
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
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
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
420
421
422
423
424
425
426
427
428
429
430
431
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
412
413
414
415
416
417
418
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
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
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
399
400
401
402
403
404
405
406
407
408
409
410
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
677
678
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
351
352
353
354
355
356
357
358
359
360
361
362
363
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
506
507
508
509
510
511
512
513
514
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._table_cache.width()
    if diff > 0:
        self.append_column(Column(repeated=diff))
    self._table_cache.cached_width = None

_yield_odf_columns

_yield_odf_columns() -> Iterator[Column]
Source code in odfdo/table.py
2288
2289
2290
2291
2292
2293
2294
2295
2296
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
1458
1459
1460
1461
1462
1463
1464
1465
1466
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(str_or_element: 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
str_or_element Element | str

The Row or Column to append.

required
Source code in odfdo/table.py
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
def append(self, str_or_element: 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:
        str_or_element (Element | str): The Row or Column to append.

    """
    if isinstance(str_or_element, Row):
        self.append_row(str_or_element)
    elif isinstance(str_or_element, Column):
        self.append_column(str_or_element)
    else:
        # probably still an error
        self._append(str_or_element)

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
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
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
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
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
        for idx, child in enumerate(self.children):
            if child.tag in (
                "table:table-row",
                "table:table-row-group",
                "table:table-header-rows",
                "table:table-rows",
            ):
                position = idx
                break
    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._table_cache.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)
    self._table_cache.clear_col_indexes()
    # 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
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
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:
            msg = "Table is not inside a document"
            raise ValueError(msg)
        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)
    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
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
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 (preserving table name if set).

Source code in odfdo/table.py
341
342
343
344
345
346
347
348
349
def clear(self) -> None:
    """Remove all children, text content, and attributes from the table
    element (preserving table name if set).
    """
    name = self.name
    self._xml_element.clear()
    if name:
        self.name = name
    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
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
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
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
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
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
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
    col_width = self._table_cache.width()
    if x < col_width:
        self._table_cache.delete_col_in_cache(x, self)
    # Update width
    for row in self._get_rows():
        if row.width > x:
            row.delete_cell(x)
    self._table_cache.clear_row_indexes()
    self._table_cache.clear_col_indexes()

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
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
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:
        msg = "Name required"
        raise ValueError(msg)
    if global_scope:
        body = self.document_body
        if not body:
            msg = "Table is not inside a document"
            raise ValueError(msg)
        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)
    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
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
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: Iterable[Row] | None = None) -> None

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

Parameters:

Name Type Description Default
rows Iterable[Row] | None

An iterable of Row elements to append.

None
Source code in odfdo/table.py
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
def extend_rows(self, rows: Iterable[Row] | None = None) -> None:
    """Append a list of rows to the end of the table.

    Args:
        rows: An iterable of Row elements to append.

    """
    if rows is None:
        rows = []
    self.extend(rows)
    self._compute_table_cache()
    # Update width if necessary
    self.normalize_columns()

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
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
@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)
    table.clear()

    def _read_lines() -> Iterator[list[str]]:
        for line in reader:
            while line and not line[-1].strip():
                line.pop()
            yield line

    _populate_table(table, _read_lines())
    return table

from_dict classmethod

from_dict(
    data: dict[str, Any] | list[dict[str, Any]],
    name: str | None = None,
    guess_type: bool = False,
) -> Table

Create a new Table object from a dictionary or list of dictionaries.

Accepts: - Columnar dict: {"Col1": [val1, val2], "Col2": [val3, val4]} - List of records: [{"Col1": val1, "Col2": val3}, {"Col1": val2, "Col2": val4}] - Matrix dict: {"SheetName": [[val1, val2], [val3, val4]]}

Parameters:

Name Type Description Default
data dict[str, Any] | list[dict[str, Any]]

The dictionary or list of dicts to import.

required
name str | None

Name of the table to create.

None
guess_type bool

If True, try to detect Python type from strings values (int, float, dates).

False

Returns:

Type Description
Table

A new Table populated with the dictionary data.

Raises:

Type Description
TypeError

If data is not a dict or list of dicts.

Source code in odfdo/table.py
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
@classmethod
def from_dict(
    cls,
    data: dict[str, Any] | list[dict[str, Any]],
    name: str | None = None,
    guess_type: bool = False,
) -> Table:
    """Create a new Table object from a dictionary or list of
    dictionaries.

    Accepts:
    - Columnar dict: `{"Col1": [val1, val2], "Col2": [val3, val4]}`
    - List of records: `[{"Col1": val1, "Col2": val3}, {"Col1": val2,
        "Col2": val4}]`
    - Matrix dict: `{"SheetName": [[val1, val2], [val3, val4]]}`

    Args:
        data: The dictionary or list of dicts to import.
        name: Name of the table to create.
        guess_type: If True, try to detect Python type from strings
            values (int, float, dates).

    Returns:
        A new Table populated with the dictionary data.

    Raises:
        TypeError: If data is not a dict or list of dicts.

    """
    if isinstance(data, dict):
        return cls._from_dict_dict(data, name, guess_type)
    if isinstance(data, list):
        return cls._from_dict_list(data, name, guess_type)
    msg = "Data must be a dict or list of dicts"
    raise TypeError(msg)

from_json classmethod

from_json(
    content: str
    | dict[str, list[list[Any]]]
    | list[list[Any]],
    name: str | None = "",
) -> Table

Import JSON content into a new Table object.

Parameters:

Name Type Description Default
content str | dict[str, list[list[Any]]] | list[list[Any]]

A JSON string, dictionary {table_name: [[...], ...]} or 2D list [[...], ...].

required
name str | None

Name of table to create. If None, uses key from dict or “Sheet”.

''

Returns:

Name Type Description
Table Table

A new Table object populated with the JSON data.

Source code in odfdo/table.py
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
@classmethod
def from_json(
    cls,
    content: str | dict[str, list[list[Any]]] | list[list[Any]],
    name: str | None = "",
) -> Table:
    """Import JSON content into a new Table object.

    Args:
        content: A JSON string, dictionary `{table_name: [[...], ...]}` or
            2D list `[[...], ...]`.
        name: Name of table to create. If None, uses key from dict or
            "Sheet".

    Returns:
        Table: A new Table object populated with the JSON data.

    """
    if isinstance(content, str):
        data = json.loads(content)
    else:
        data = content

    unifyer = NameUnifyer()
    if isinstance(data, dict):
        if not data:
            table_name = unifyer.unique(name or "")
            rows_data: list[list[Any]] = []
        else:
            key = next(iter(data))
            table_name = unifyer.unique(key)
            rows_data = data[key]
    elif isinstance(data, list):
        table_name = unifyer.unique(name or "")
        rows_data = data
    else:
        msg = "JSON content must be a dict, list, or valid JSON string"
        raise TypeError(msg)

    table = cls(table_name)
    table.clear()
    _populate_table(table, rows_data)
    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
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
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
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
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
    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
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
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
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
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))  # noqa: PERF401
        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[
    CellValue | tuple[CellValue | None, str | None] | None
]

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[CellValue | tuple[CellValue | None, str | None] | None]

list[CellValue | tuple[CellValue | None, str | None] | None]: A list of Python values or (value, odf_type) tuples.

Source code in odfdo/table.py
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
def get_column_values(
    self,
    x: int | str,
    cell_type: str | None = None,
    complete: bool = True,
    get_type: bool = False,
) -> list[CellValue | tuple[CellValue | None, str | None] | None]:
    """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[CellValue | tuple[CellValue | None, str | None] | None]:
            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[CellValue | tuple[CellValue | None, str | None] | None] = []
    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
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
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
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
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
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
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
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:
            msg = "Table is not inside a document"
            raise ValueError(msg)
        if not body.allow_named_range:
            return None
        nr: NamedRange | None = body.get_named_range(name)

    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
2764
2765
2766
2767
2768
2769
2770
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
2804
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()
    else:
        named_ranges = self._local_named_ranges()
    if not table_name:
        return named_ranges
    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).

By default, 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
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
def get_row(self, y: int | str, clone: bool = True, create: bool = True) -> Row:
    """Get the row at the given 'y' position (0-based).

    By default, 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)
    row.y = y
    return row

get_row_sub_elements

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

Get the list of cell contents for the row at index “y” or Row object (internal).

The list is padded to “table.width”.

For each column in the row: - If the cell contains non-empty child text elements (““), returns the list of child elements “[Element, …]”. - If the cell is empty or contains non-text content, returns the Cell object itself. - If the column index extends beyond the row boundary up to “table.width”, returns “[]”.

Parameters:

Name Type Description Default
y int | str | Row

The row index (0-based) or Row element.

required

Returns:

Type Description
list[Any]

list[Any]: A list of child element lists, Cell objects, or [] padded to match the table’s width.

Source code in odfdo/table.py
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
def get_row_sub_elements(self, y: int | str | Row) -> list[Any]:
    """Get the list of cell contents for the row at index "y" or Row
    object (internal).

    The list is padded to "table.width".

    For each column in the row:
    - If the cell contains non-empty child text elements ("<text:p>"),
      returns the list of child elements "[Element, ...]".
    - If the cell is empty or contains non-text content, returns the
      Cell object itself.
    - If the column index extends beyond the row boundary up to
      "table.width", returns "[]".

    Args:
        y: The row index (0-based) or Row element.

    Returns:
        list[Any]: A list of child element lists, Cell objects, or []
            padded to match the table's width.

    """
    row = y if isinstance(y, Row) else self.get_row(y, clone=False)
    cells = row.get_cells()
    values: list[Any] = []
    for cell in cells:
        children = cell.children
        if children and any(getattr(e, "inner_text", "").strip() for e in children):
            values.append(children)
        else:
            values.append(cell)
    if len(values) < self.width:
        values.extend([[]] * (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[
    CellValue | tuple[CellValue | None, str | None] | None
]

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[CellValue | tuple[CellValue | None, str | None] | None]

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

Source code in odfdo/table.py
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
def get_row_values(
    self,
    y: int | str,
    cell_type: str | None = None,
    complete: bool = True,
    get_type: bool = False,
) -> list[CellValue | tuple[CellValue | None, str | None] | None]:
    """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
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
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
) -> CellValue | tuple[CellValue | None, str | None] | None

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:

Type Description
CellValue | tuple[CellValue | None, str | None] | None

CellValue | tuple[CellValue | None, str | None] | None: The Python value of the cell, or a (value, type) tuple if get_type is True.

Source code in odfdo/table.py
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
def get_value(
    self,
    coord: tuple | list | str,
    get_type: bool = False,
) -> CellValue | tuple[CellValue | None, str | None] | None:
    """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:
        CellValue | tuple[CellValue | None, str | None] | None:
            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
    # 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
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
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

Cell

updated.

Source code in odfdo/table.py
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
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
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
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)
    col_width = self._table_cache.width()
    diff = x - col_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!
    self._table_cache.clear_row_indexes()
    self._table_cache.clear_col_indexes()
    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
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
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 (value is None) 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
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
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 (value is None) 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 (value is None) 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
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
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 (value is None) 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 (value is None) 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
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
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 (value is None) 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
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
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
    while x < min(end, self.width - 1):
        x += 1
        if x < start:
            continue
        col = Column()
        col.x = x
        yield col

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

lstrip

lstrip(aggressive: bool = False) -> None

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

A cell is considered empty if it has no value (value is None) and no style (or style is ignored when aggressive=True).

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
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
def lstrip(self, aggressive: bool = False) -> None:
    """Remove top empty rows and left-side empty cells from the table
    in-place.

    A cell is considered empty if it has no value (value is None) and no
    style (or style is ignored when `aggressive=True`).

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

    """
    # Step 1: remove empty rows at the top of the table
    while True:
        rows = self._get_rows()
        if not rows:
            break
        if rows[0].is_empty(aggressive=aggressive):
            row0 = rows[0]
            row0.parent.delete(row0)
            self._table_cache.clear_row_indexes()
        else:
            break

    rows = self._get_rows()
    if not rows:
        self._compute_table_cache()
        return

    # Step 2: find minimum leading empty cells across all rows
    min_leading_empty: int = 2**30
    for row in rows:
        leading = 0
        for cell in row._get_cells():
            if cell.is_empty(aggressive=aggressive):
                leading += cell.repeated or 1
            else:
                break
        if leading < min_leading_empty:
            min_leading_empty = leading
            if min_leading_empty == 0:
                break

    # Step 3: delete min_leading_empty columns from the left
    if min_leading_empty > 0:
        for _ in range(min_leading_empty):
            self.delete_column(0)

    self._table_cache.clear_row_indexes()
    self._table_cache.clear_col_indexes()
    self._compute_table_cache()

normalize_columns

normalize_columns() -> None

Ensure that table:table-column definitions cover the full width of the rows.

If the table lacks table:table-column elements or if the existing columns do not cover the maximum width of the rows, default column definitions are appended to match the maximum row width.

Source code in odfdo/table.py
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
def normalize_columns(self) -> None:
    """Ensure that table:table-column definitions cover the full width of
    the rows.

    If the table lacks table:table-column elements or if the existing
    columns do not cover the maximum width of the rows, default column
    definitions are appended to match the maximum row width.
    """
    rows = self._get_rows()
    if not rows:
        return
    max_row_width = max((row.width for row in rows), default=0)
    col_width = self._table_cache.width()
    diff = max_row_width - col_width
    if diff > 0:
        self.append_column(Column(repeated=diff))
    self._table_cache.cached_width = None

optimize_height

optimize_height() -> None

Remove bottom empty rows in-place.

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

Source code in odfdo/table.py
1205
1206
1207
1208
1209
1210
1211
def optimize_height(self) -> None:
    """Remove bottom empty rows in-place.

    This method keeps the repeated styles of empty cells but minimizes the
    table height to fit the actual content.
    """
    self._optimize_height_trim_rows()

optimize_width

optimize_width() -> None

Remove 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
1213
1214
1215
1216
1217
1218
1219
1220
1221
def optimize_width(self) -> None:
    """Remove 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.
    """
    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 (value is None) 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
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
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 (value is None) 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)
        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
            column.parent.delete(column)
            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
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
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

Insert an image in a cell (deprecated, use recipes instead).

See recipes
  • add_an_image_to_a_table_inside_spreadsheet.py
  • add_an_image_to_a_table_inside_text_document.py

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
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
def set_cell_image(
    self,
    coord: tuple | list | str,
    image_frame: Frame,
    doc_type: str | None = None,
) -> None:
    """Insert an image in a cell (deprecated, use recipes instead).

    See recipes:
        - add_an_image_to_a_table_inside_spreadsheet.py
        - add_an_image_to_a_table_inside_text_document.py

    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:
            msg = "Document type not found"
            raise ValueError(msg)
        doc_type = {"office:spreadsheet": "spreadsheet", "office:text": "text"}.get(
            body.tag
        )
        if doc_type is None:
            msg = "Document type not supported for images"
            raise ValueError(msg)
    # 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
    # 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[Iterable[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 an iterable of iterables, where each inner iterable represents a row.

Parameters:

Name Type Description Default
cells Iterable[Iterable[Cell]]

An iterable of iterables 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
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
def set_cells(
    self,
    cells: Iterable[Iterable[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 an iterable of iterables, where each inner iterable
    represents a row.

    Args:
        cells: An iterable of iterables 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
    if not isiterable(cells):
        cells = [cells]  # ty: ignore
    for row_cells in cells:
        y += 1
        if row_cells is None:
            continue
        cell_list: Any
        # isiterable excludes str and bytes, and returns False for single Cell
        if isiterable(row_cells):
            cell_list = list(row_cells)
            if not cell_list:
                continue
        else:
            cell_list = [row_cells]
        row = self.get_row(y, clone=True)
        repeated = row.repeated or 1
        if repeated >= 2:
            row.repeated = None
        row.set_cells(cast("Iterable[Cell]", cell_list), 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
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
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
    col_width = self._table_cache.width()
    diff = x - col_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)
    self._table_cache.clear_col_indexes()
    return column_back

set_column_cells

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

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

The provided iterable of cells must yield the same number of items 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 Iterable[Cell]

An iterable of Cell elements to set.

required
Source code in odfdo/table.py
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
def set_column_cells(self, x: int | str, cells: Iterable[Cell]) -> None:
    """Set the cells for the column at the given 'x' position.

    The provided iterable of cells must yield the same number of items as
    the table's height.

    Args:
        x: The 0-based index or alphabetical representation of the column.
        cells: An iterable of Cell elements to set.

    """
    cells_list = list(cells)
    height = self.height
    if len(cells_list) != height:
        msg = f"Column height mismatch: {height} cells expected"
        raise ValueError(msg)
    cells_iterator = iter(cells_list)
    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: Iterable[CellValue | None],
    cell_type: str | None = None,
    currency: str | None = None,
    style: str | None = None,
) -> None

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

The provided iterable of values must yield the same number of items 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 Iterable[CellValue | None]

An iterable 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
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
def set_column_values(
    self,
    x: int | str,
    values: Iterable[CellValue | None],
    cell_type: str | None = None,
    currency: str | None = None,
    style: str | None = None,
) -> None:
    """Set the Python values for the cells in the column at the given 'x'
    position.

    The provided iterable of values must yield the same number of items as
    the table's height.

    Args:
        x: The 0-based index or alphabetical representation of the column.
        values: An iterable 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
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
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:
        msg = "Name required"
        raise ValueError(msg)
    if global_scope:
        body = self.document_body
        if not body:
            msg = "Table is not inside a document"
            raise ValueError(msg)
        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(
            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
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
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: Iterable[Cell] | 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 Iterable[Cell] | None

An iterable 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
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
def set_row_cells(self, y: int | str, cells: Iterable[Cell] | 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: An iterable 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: Iterable[CellValue | None],
    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 Iterable[CellValue | None]

An iterable 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
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
def set_row_values(
    self,
    y: int | str,
    values: Iterable[CellValue | None],
    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: An iterable 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 = self.get_row(y)
    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
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
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(  # noqa:PERF401
                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])  # ty: ignore[invalid-argument-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: CellValue | None,
    cell_type: str | None = None,
    currency: str | None = None,
    style: str | None = None,
    formula: 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 CellValue | None

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
formula str | None

The formula to set for the cell.

None
Source code in odfdo/table.py
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
def set_value(
    self,
    coord: tuple | list | str,
    value: CellValue | None,
    cell_type: str | None = None,
    currency: str | None = None,
    style: str | None = None,
    formula: 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.
        formula: The formula to set for the cell.

    """
    # raise VAlue Error in get_cell if wrong coordinates
    # always returns a Cell
    current = self.get_cell(coord, clone=False)
    cell = current.clone
    cell.repeated = None
    cell.set_value(
        value,
        cell_type=cell_type,
        currency=currency,
        formula=formula,
    )
    if style:
        cell.style = style
    self.set_cell(coord, cell, clone=False)

set_values

set_values(
    values: Iterable[Iterable[CellValue | None]],
    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 an iterable of iterables, where each inner iterable represents a row. If the provided values do not cover the entire area of the table, the previous values are retained. Objects of type “str” are not treated as iterables.

Parameters:

Name Type Description Default
values Iterable[Iterable[CellValue | None]]

An iterable of iterables 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
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
def set_values(
    self,
    values: Iterable[Iterable[CellValue | None]],
    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 an iterable
    of iterables, where each inner iterable represents a row. If the
    provided values do not cover the entire area of the table, the
    previous values are retained. Objects of type "str" are not treated
    as iterables.

    Args:
        values: An iterable of iterables 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
    if not isiterable(values):
        # guard against str iterable
        values = [values]  # ty: ignore
    for row_values in values:
        y += 1
        if row_values is None:
            continue
        val_list: Any
        # isiterable excludes str and bytes, avoiding splitting strings into chars
        if isiterable(row_values):
            val_list = list(row_values)
            if not val_list:
                continue
        else:
            val_list = row_values
        row = self.get_row(y, clone=True)
        repeated = row.repeated or 1
        if repeated >= 2:
            row.repeated = None
        row.set_values(
            val_list,
            start=x,
            cell_type=cell_type,
            currency=currency,
            style=style,
        )
        self.set_row(y, row, clone=False)
        self._update_width(row)

strip

strip(aggressive: bool = False) -> None

Remove empty rows and columns from top, bottom, left, and right in-place.

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
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
def strip(self, aggressive: bool = False) -> None:
    """Remove empty rows and columns from top, bottom, left, and right
    in-place.

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

    """
    self.rstrip(aggressive=aggressive)
    self.lstrip(aggressive=aggressive)

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.

{}
Example
reference color price
ref01 white 10,00
ref02 blue 20,50
ref03 red 25,75

print(table.to_csv()) reference,color,price ref01,white,10 ref02,blue,20.5 ref03,red,25.75

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
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
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.

    Example:
        | reference | color | price |
        |-----------|-------|-------|
        | ref01     | white | 10,00 |
        | ref02     | blue  | 20,50 |
        | ref03     | red   | 25,75 |

    >>> print(table.to_csv())
    reference,color,price
    ref01,white,10
    ref02,blue,20.5
    ref03,red,25.75

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

    """
    rows = serialize_table(self, "csv")
    content = StringIO(newline="")
    csv_writer = csv.writer(content, dialect=dialect, **fmtparams)
    for row in rows:
        csv_writer.writerow(row)

    if path_or_file:
        # windows fix: write file as binary
        Path(path_or_file).write_bytes(content.getvalue().encode())
        return None
    return content.getvalue()

to_dict

to_dict(
    orient: str = "list",
    header: bool = True,
    mode: str = "python",
    lstrip: bool = False,
    no_decimal: bool = False,
    no_date: bool = False,
    no_nan: bool = False,
) -> dict[str, Any] | list[dict[str, Any]]

Export table data as a Python dictionary or list of dictionaries.

Parameters:

Name Type Description Default
orient str

Format of the output: - “list” (default): Columnar dict {"col": [values, ...]}. - “records”: List of row dicts [{"col": value, ...}, ...]. - “matrix”: Dict with table name {"TableName": [[...], ...]}.

'list'
header bool

(for orientation “list” or “records”). If True, uses the first row of data as column header keys. If False, column keys are generated as “0”, “1”, “2”, …

True
mode str

Serialization mode (“python” or “json”). Defaults to “python”.

'python'
lstrip bool

If True, also removes leading empty rows and columns from the top-left before export.

False
no_decimal bool

If True in “python” mode, convert Decimal values to float or int.

False
no_date bool

If True in “python” mode, convert date, datetime, and timedelta values to ODF/ISO formatted strings.

False
no_nan bool

If True in “python” mode, convert NaN and infinity values to None.

False
Example
reference color price
ref01 white 10,00
ref02 blue 20,50
ref03 red 25,75

table.to_dict() { ‘reference’: [‘ref01’, ‘ref02’, ‘ref03’], ‘color’: [‘white’, ‘blue’, ‘red’], ‘price’: [10, Decimal(‘20.5’), Decimal(‘25.75’)] }

table.to_dict(orient=”records”) [ {‘reference’: ‘ref01’, ‘color’: ‘white’, ‘price’: 10}, {‘reference’: ‘ref02’, ‘color’: ‘blue’, ‘price’: Decimal(‘20.5’)}, {‘reference’: ‘ref03’, ‘color’: ‘red’, ‘price’: Decimal(‘25.75’)} ]

table.to_dict(orient=”matrix”) { ‘product’: [ [‘reference’, ‘color’, ‘price’], [‘ref01’, ‘white’, 10], [‘ref02’, ‘blue’, Decimal(‘20.5’)], [‘ref03’, ‘red’, Decimal(‘25.75’)] ] }

Returns:

Type Description
dict[str, Any] | list[dict[str, Any]]

The table data formatted as a dictionary or list of dicts.

Raises:

Type Description
ValueError

If orient is not one of “list”, “records”, or “matrix”.

Source code in odfdo/table.py
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
def to_dict(
    self,
    orient: str = "list",
    header: bool = True,
    mode: str = "python",
    lstrip: bool = False,
    no_decimal: bool = False,
    no_date: bool = False,
    no_nan: bool = False,
) -> dict[str, Any] | list[dict[str, Any]]:
    """Export table data as a Python dictionary or list of dictionaries.

    Args:
        orient: Format of the output:
            - "list" (default): Columnar dict `{"col": [values, ...]}`.
            - "records": List of row dicts `[{"col": value, ...}, ...]`.
            - "matrix": Dict with table name `{"TableName": [[...], ...]}`.
        header: (for orientation "list" or "records"). If True, uses the
            first row of data as column header keys. If False, column keys
            are generated as "0", "1", "2", ...
        mode: Serialization mode ("python" or "json"). Defaults
            to "python".
        lstrip: If True, also removes leading empty rows and columns from
            the top-left before export.
        no_decimal: If True in "python" mode, convert Decimal values to
            float or int.
        no_date: If True in "python" mode, convert date, datetime, and
            timedelta values to ODF/ISO formatted strings.
        no_nan: If True in "python" mode, convert NaN and infinity values
            to None.

    Example:
        | reference | color | price |
        |-----------|-------|-------|
        | ref01     | white | 10,00 |
        | ref02     | blue  | 20,50 |
        | ref03     | red   | 25,75 |

    >>> table.to_dict()
    {
        'reference': ['ref01', 'ref02', 'ref03'],
        'color': ['white', 'blue', 'red'],
        'price': [10, Decimal('20.5'), Decimal('25.75')]
    }

    >>> table.to_dict(orient="records")
    [
        {'reference': 'ref01', 'color': 'white', 'price': 10},
        {'reference': 'ref02', 'color': 'blue', 'price': Decimal('20.5')},
        {'reference': 'ref03', 'color': 'red', 'price': Decimal('25.75')}
    ]

    >>> table.to_dict(orient="matrix")
    {
        'product': [
            ['reference', 'color', 'price'],
            ['ref01', 'white', 10],
            ['ref02', 'blue', Decimal('20.5')],
            ['ref03', 'red', Decimal('25.75')]
        ]
    }

    Returns:
        The table data formatted as a dictionary or list of dicts.

    Raises:
        ValueError: If `orient` is not one of "list", "records", or "matrix".

    """
    match orient:
        case "list":
            return self._to_dict_list(
                header=header,
                mode=mode,
                lstrip=lstrip,
                no_decimal=no_decimal,
                no_date=no_date,
                no_nan=no_nan,
            )
        case "records":
            return self._to_dict_records(
                header=header,
                mode=mode,
                lstrip=lstrip,
                no_decimal=no_decimal,
                no_date=no_date,
                no_nan=no_nan,
            )
        case "matrix":
            return self._to_dict_matrix(
                mode=mode,
                lstrip=lstrip,
                no_decimal=no_decimal,
                no_date=no_date,
                no_nan=no_nan,
            )
        case _:
            msg = (
                f"Invalid orient parameter: {orient!r}. "
                "Expected 'list', 'records', or 'matrix'"
            )
            raise ValueError(msg)

to_json

to_json(
    path_or_file: str | Path | None = None,
    pretty: bool = False,
    ensure_ascii: bool = False,
) -> str | None

Export the table values as a JSON string or file.

Parameters:

Name Type Description Default
path_or_file str | Path | None

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

None
pretty bool

Use pretty formater. Defaults to False.

False
ensure_ascii bool

If True, non-ASCII characters are escaped. Defaults to False.

False
Example
reference color price
ref01 white 10,00
ref02 blue 20,50
ref03 red 25,75

print(table.to_json(pretty=True)) { “product”: [ [“reference”, “color”, “price”], [“ref01”, “white”, 10], [“ref02”, “blue”, 20.5], [“ref03”, “red”, 25.75] ] }

Returns:

Type Description
str | None

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

Source code in odfdo/table.py
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
def to_json(
    self,
    path_or_file: str | Path | None = None,
    pretty: bool = False,
    ensure_ascii: bool = False,
) -> str | None:
    """Export the table values as a JSON string or file.

    Args:
        path_or_file: The path or file to save the JSON content to.
            If None, the JSON content is returned as a string.
        pretty: Use pretty formater. Defaults to False.
        ensure_ascii: If True, non-ASCII characters are escaped. Defaults
            to False.

    Example:
        | reference | color | price |
        |-----------|-------|-------|
        | ref01     | white | 10,00 |
        | ref02     | blue  | 20,50 |
        | ref03     | red   | 25,75 |

    >>> print(table.to_json(pretty=True))
    {
      "product": [
        ["reference", "color", "price"],
        ["ref01", "white", 10],
        ["ref02", "blue", 20.5],
        ["ref03", "red", 25.75]
      ]
    }

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

    """
    rows = serialize_table(self, "json")
    name = self.name
    if not name:
        unifyer = NameUnifyer()
        name = unifyer.unique()
    data: Any = {name: rows}
    if pretty:
        content = format_json(data, ensure_ascii=ensure_ascii)
    else:
        content = json.dumps(data, ensure_ascii=ensure_ascii, allow_nan=False)
    if path_or_file:
        Path(path_or_file).write_text(content, encoding="utf-8")
        return None
    return content

to_markdown

to_markdown() -> str

Export the table content as a Markdown string.

Example
reference color price
ref01 white 10,00
ref02 blue 20,50
ref03 red 25,75

Returns:

Name Type Description
str str

The Markdown representation of the table.

Source code in odfdo/table.py
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
def to_markdown(self) -> str:
    """Export the table content as a Markdown string.

    Example:
        | reference | color | price |
        |-----------|-------|-------|
        | ref01     | white | 10,00 |
        | ref02     | blue  | 20,50 |
        | ref03     | red   | 25,75 |

    Returns:
        str: The Markdown representation of the table.

    """
    was_initialized = "document" in MD_GLOBAL and MD_GLOBAL["document"] is not None
    if not was_initialized:
        _set_global(None)
    try:
        return self._md_format()
    finally:
        if not was_initialized:
            _set_global(None)

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

    """
    if self.width == 0 or self.height == 0:
        return
    data = []
    if coord is None:
        data = [row.cells for row in self.iter_rows()]
        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()

_decode_time_string

_decode_time_string(data: str) -> timedelta
Source code in odfdo/table.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def _decode_time_string(data: str) -> timedelta:
    parts = data.strip().split(":")
    if 2 <= len(parts) <= 3:
        hours = int(parts[0])
        minutes = int(parts[1])
        if not (0 <= hours <= 23 and 0 <= minutes <= 59):
            raise ValueError
        seconds = float(parts[2]) if len(parts) == 3 else 0.0
        if not (0 <= seconds < 60):
            raise ValueError
        return timedelta(hours=hours, minutes=minutes, seconds=seconds)
    msg = f"Invalid time string: {data!r}"
    raise ValueError(msg)

_get_python_value

_get_python_value(
    data: str | bytes | int | float | bool,
    encoding: str = "utf-8",
) -> CellValue

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.

'utf-8'

Returns:

Name Type Description
CellValue CellValue

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

Source code in odfdo/table.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def _get_python_value(
    data: str | bytes | int | float | bool, encoding: str = "utf-8"
) -> CellValue:
    """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:
        CellValue: 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 ?
    with contextlib.suppress(ValueError):
        return int(data)
    # A float ?
    with contextlib.suppress(ValueError):
        return float(data)
    # A DateTime ?
    if "T" in data or " " in data:
        with contextlib.suppress(ValueError):
            return DateTime.decode(data.replace(" ", "T"))
    # A Date ?
    with contextlib.suppress(ValueError):
        return Date.decode(data)
    # A Duration ?
    with contextlib.suppress(ValueError):
        return Duration.decode(data)
    # A time string (HH:MM:SS or HH:MM)?
    with contextlib.suppress(ValueError, AttributeError):
        return _decode_time_string(data)
    # A Boolean ?
    with contextlib.suppress(ValueError):
        # "True" or "False" with a .lower
        return Boolean.decode(data.lower())
    # So a string
    return data

_populate_table

_populate_table(
    table: Table, rows: Iterable[Iterable[Any]]
) -> None

Populate a table with rows of values, appending each row in-place.

String values are evaluated as Python types.

Parameters:

Name Type Description Default
table Table

Target Table instance.

required
rows Iterable[Iterable[Any]]

2D iterable of cell values.

required
Source code in odfdo/table.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def _populate_table(table: Table, rows: Iterable[Iterable[Any]]) -> None:
    """Populate a table with rows of values, appending each row in-place.

    String values are evaluated as Python types.

    Args:
        table: Target Table instance.
        rows: 2D iterable of cell values.

    """
    for row in rows:
        row_elem = Row()
        row_converted = [
            _get_python_value(val) if isinstance(val, str) else val for val in row
        ]
        row_elem.set_values(row_converted)
        table.append_row(row_elem, clone=False)

_populate_table_keep_strings

_populate_table_keep_strings(
    table: Table, rows: Iterable[Iterable[Any]]
) -> None

Populate a table with rows of values, appending each row in-place.

String-type values are preserved as strings.

Parameters:

Name Type Description Default
table Table

Target Table instance.

required
rows Iterable[Iterable[Any]]

2D iterable of cell values.

required
Source code in odfdo/table.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def _populate_table_keep_strings(table: Table, rows: Iterable[Iterable[Any]]) -> None:
    """Populate a table with rows of values, appending each row in-place.

    String-type values are preserved as strings.

    Args:
        table: Target Table instance.
        rows: 2D iterable of cell values.

    """
    for row in rows:
        row_elem = Row()
        row_elem.set_values(row)
        table.append_row(row_elem, clone=False)

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
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
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()
    if isinstance(content_b, bytes):
        content = content_b.decode()
    else:
        content = content_b
    return Table.from_csv(content=content, name=name, style=style, **fmtparams)