excel-ooxml 1.0.0

Reading and writing of the SpreadsheetML format (.xlsx).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
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
3677
3678
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
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
//! The minimal in-memory model of a SpreadsheetML workbook: a workbook is a sequence of sheets,
//! each a sequence of rows, each a sequence of cells — matching how a real `.xlsx` structures
//! `xl/workbook.xml`'s `<sheets>` list and each `xl/worksheets/sheetN.xml`'s `<sheetData>`
//! (`CT_Workbook`/`CT_Worksheet`/`CT_Row`/`CT_Cell`).
//!
//! Text, numeric, boolean, date, formula, and rich-text cell values are modeled
//! (`CellValue::Text`/`::Number`/`::Boolean`/`::Date`/`::Formula`/`::RichText`), and a cell may
//! carry a [`CellFormat`] (number format, basic font, solid fill, alignment). A sheet may also
//! carry [`ConditionalFormattingRule`]s, [`DataValidationRule`]s, and embedded charts
//! ([`SheetChart`]). A workbook may also carry [`DefinedName`]s (named ranges/formulas/constants).

/// A `.xlsx` workbook: a sequence of sheets, in the order they appear in Excel's own sheet tabs.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Workbook {
    /// The sheets that make up this workbook, in order.
    pub sheets: Vec<Sheet>,
    /// Named ranges/formulas/constants defined on this workbook (`<definedNames>`/`<definedName>`,
    /// `CT_DefinedNames`/`CT_DefinedName`), in order. Unlike a sheet, this lives at the workbook
    /// level even for a name scoped to a single sheet (see [`DefinedName::local_sheet_id`]).
    pub defined_names: Vec<DefinedName>,
    /// Document metadata (`docProps/core.xml`/`docProps/app.xml`). Both parts are always written by
    /// this crate (they're required for a strictly valid package), but before this point every
    /// field in them was left empty/boilerplate.
    pub properties: DocumentProperties,
    /// Workbook *structure* protection (`<workbookProtection>`, `CT_WorkbookProtection`). Distinct
    /// from [`Sheet::protection`]: this locks whether sheets can be
    /// added/renamed/hidden/reordered/deleted, not cell editing within a sheet.
    pub protection: Option<WorkbookProtection>,
    /// Write-protection / "read-only recommended" (`<fileSharing>`, `CT_FileSharing`). Distinct
    /// from [`protection`](Workbook::protection) (`<workbookProtection>`, point 26, which locks
    /// *structure*): this instead controls the "This file should be opened as read-only" prompt
    /// Excel shows when opening the file, and/or the legacy 16-bit write-reservation password some
    /// older workflows still use. Confirmed via `sml.xsd`: `CT_Workbook`'s sequence puts
    /// `fileSharing?` *before* `workbookPr?`/ `workbookProtection?`/`bookViews?`, i.e. as the very
    /// first possible child of `<workbook>`.
    pub write_protection: Option<WriteProtection>,
    /// The 0-based index into [`sheets`](Workbook::sheets) of the sheet shown as active/selected
    /// when the workbook is opened (`<bookViews><workbookView activeTab="..">`). `None` leaves
    /// Excel's own default (the first sheet).
    pub active_tab: Option<usize>,
    /// References to other workbooks used by this workbook's formulas (`<externalReferences>` + one
    /// `xl/externalLinks/externalLinkN.xml` part per entry, `CT_ExternalReference`). Storage only,
    /// same posture as this crate's own formula text: nothing here resolves or evaluates a
    /// reference into the other workbook's actual values.
    pub external_links: Vec<ExternalWorkbookLink>,
    /// A VBA project's raw compiled bytes (`xl/vbaProject.bin`), if this workbook carries macros.
    /// Preserved *opaquely*: this crate can round-trip an existing macro-enabled workbook's
    /// `vbaProject.bin` unchanged but cannot create, parse, or modify VBA source from scratch; the
    /// OLE2/ CFB container format `vbaProject.bin` is internally structured in isn't decoded at
    /// all. When `Some`, `Workbook::write_to` switches the workbook part's content type to the
    /// macro-enabled variant (`..sheet.macroEnabled.main+xml`) — the caller is still responsible
    /// for using a `.xlsm` file name, this crate has no notion of file extensions.
    pub vba_project: Option<Vec<u8>>,
    /// Workbook-wide calculation properties (`<calcPr>`, `CT_CalcPr`). `None` leaves Excel's own
    /// default (automatic recalculation, no iterative calculation).
    pub calculation: Option<CalculationProperties>,
    /// Custom table style definitions (`xl/styles.xml`'s `<tableStyles>`), referenced by name from
    /// any sheet's [`ExcelTable::table_style_name`]. Workbook-wide (styles.xml is a single shared
    /// part), same posture as `defined_names` living here rather than per-sheet even for a
    /// sheet-scoped name.
    pub table_styles: Vec<TableStyle>,
    /// Named cell styles (`xl/styles.xml`'s `<cellStyles>`/`<cellStyleXfs>`,
    /// `CT_CellStyles`/`CT_CellStyleXfs`): the "Cell Styles" gallery Excel's Home ribbon shows
    /// (`Good`/ `Bad`/`Neutral`, `Heading 1`-`4`, `Input`/`Output`/`Calculation`,
    /// `Currency`/`Percent`/`Comma`..). Before this point every `cellXfs` entry this crate wrote
    /// implicitly pointed at a single, hardcoded `"Normal"` `cellStyleXfs` entry (`xfId="0"`) — a
    /// cell format that set [`CellFormat::named_style`] had no way to actually link back to one of
    /// these named entries, so the association was silently lost on write. A [`CellFormat`] used
    /// anywhere in this workbook (cell, row/column default..) that sets `named_style` to a name
    /// found here gets that entry's index written as its `cellXfs` `xfId`, instead of the default
    /// `0`; a name not found here silently falls back to `0` (`"Normal"`), same "best-effort, not
    /// validated" posture as `ExcelTable::table_style_name` referencing a name not in this same
    /// list. Workbook-wide (styles.xml is a single shared part), same posture as
    /// `table_styles`/`defined_names` living here rather than per-sheet.
    pub named_cell_styles: Vec<NamedCellStyle>,
}

/// A single worksheet (`xl/worksheets/sheetN.xml`, `CT_Worksheet`): a name (shown on Excel's sheet
/// tab) plus a sequence of rows.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Sheet {
    /// This sheet's name (`<sheet name="..">` in `xl/workbook.xml`), shown on Excel's own sheet
    /// tab. Excel itself limits this to 31 characters and disallows a handful of characters (`: \ /
    /// ? * [ ]`) — neither limit is enforced here, same "caller's responsibility" posture as
    /// `word-ooxml`'s `PageSetup.orientation` not auto-swapping dimensions.
    pub name: String,
    /// The rows that make up this sheet's data, in order. A row's own 1-based row number (`<row
    /// r="..">`) is simply this row's position in this `Vec` plus one — not a separate field — so
    /// there is no way to represent a sparse sheet (e.g. data starting at row 5 with rows 1-4
    /// genuinely absent) when *writing*; reading back a sparse sheet from a real `.xlsx` still
    /// works (missing rows are filled in as empty), see `reader.rs`.
    pub rows: Vec<Row>,
    /// Conditional formatting rules applied to ranges of this sheet
    /// (`<conditionalFormatting>`/`<cfRule>`, `CT_ConditionalFormatting`/ `CT_CfRule`), in order.
    /// Each rule gets its own dedicated `<conditionalFormatting>` block when written (see
    /// `writer.rs::write_conditional_formatting`) — real Excel groups multiple rules sharing the
    /// same range under one block, but nothing in the schema requires it, so this crate doesn't
    /// bother.
    pub conditional_formatting_rules: Vec<ConditionalFormattingRule>,
    /// Data validation rules applied to ranges of this sheet
    /// (`<dataValidations>`/`<dataValidation>`, `CT_DataValidations`/ `CT_DataValidation`), in
    /// order.
    pub data_validation_rules: Vec<DataValidationRule>,
    /// Merged cell ranges (`<mergeCells>`/`<mergeCell>`, `CT_MergeCells`), each written verbatim as
    /// a range reference (e.g. `"A1:C1"`). This crate does not validate that ranges don't overlap
    /// or that only the top-left cell of a merged range carries a value (both are the caller's
    /// responsibility, same posture as
    /// `ConditionalFormattingRule::range`/`DataValidationRule::range`).
    pub merged_ranges: Vec<String>,
    /// Per-column width/visibility/outline settings (`<cols>`/`<col>`, `CT_Cols`/`CT_Col`). Each
    /// entry covers exactly one column (`min == max` in the written XML) — this crate doesn't
    /// bother collapsing adjacent identical entries into a single `<col min="1" max="3"../>` range
    /// the way real Excel does, same "less compact but schema-valid" posture as
    /// `ConditionalFormattingRule`'s one-block-per-rule choice.
    pub column_settings: Vec<ColumnSetting>,
    /// The autofilter range (`<autoFilter ref="..">`, `CT_AutoFilter`), if any. Only the
    /// dropdown-arrow range is modeled, not per-column filter criteria
    /// (`CT_FilterColumn`/`CT_Filters`) — out of scope.
    pub auto_filter_range: Option<String>,
    /// Frozen (or split) panes (`<sheetView><pane../></sheetView>`, `CT_Pane`), if any. Only
    /// "frozen" panes are modeled (the common case, e.g. freezing a header row/column), not "split"
    /// panes (a draggable divider with no scroll-locking) — `CT_Pane`'s `state="split"` variant is
    /// out of scope.
    pub freeze_panes: Option<FreezePane>,
    /// This sheet's print/page-setup settings (print area, repeated rows/columns, page orientation,
    /// fit-to-page, header/footer text). `PrintSettings::default()` (everything `None`) writes no
    /// print-related XML at all.
    pub print_settings: PrintSettings,
    /// This sheet's protection settings (`<sheetProtection>`, `CT_SheetProtection`), if protected.
    pub protection: Option<SheetProtection>,
    /// Per-cell hyperlinks (`<hyperlinks>`/`<hyperlink>`, `CT_Hyperlinks`/ `CT_Hyperlink`).
    pub hyperlinks: Vec<CellHyperlink>,
    /// Per-cell comments (legacy `xl/comments*.xml` + VML drawing, `CT_Comments`/`CT_Comment`).
    pub comments: Vec<CellComment>,
    /// A structured (`ListObject`) table on this sheet (`<tableParts>`/`<tablePart>` + a dedicated
    /// `xl/tables/tableN.xml` part, `CT_Table`), if any. Only one table per sheet is modeled (this
    /// crate's own scope choice, not an ECMA-376 limit — real Excel allows several) since a single
    /// example is enough to prove the feature out; a second table on the same sheet is simply never
    /// written.
    pub table: Option<ExcelTable>,
    /// This sheet's tab visibility (`<sheet state=".">` in `xl/workbook.xml` — a `CT_Sheet`
    /// attribute, not part of the worksheet part itself) — extended to a genuine three-state
    /// `SheetVisibility` (was a plain `bool` before this).
    pub visibility: SheetVisibility,
    /// This sheet's own display zoom percentage (`<sheetView zoomScale="..">`, e.g. `100` for
    /// 100%). `None` leaves Excel's own default (100%).
    pub zoom_scale: Option<u32>,
    /// This sheet's tab color (`<sheetPr><tabColor rgb=".."/></sheetPr>`), as an 8-hex-digit ARGB
    /// string. `None` leaves Excel's own default (no color, the plain gray/white tab).
    pub tab_color: Option<String>,
    /// Whether this sheet's view shows gridlines (`<sheetView showGridLines="..">`). `None` leaves
    /// Excel's own default (shown).
    pub show_grid_lines: Option<bool>,
    /// Whether this sheet's view shows row/column headers (`<sheetView showRowColHeaders="..">`).
    /// `None` leaves Excel's own default (shown).
    pub show_row_col_headers: Option<bool>,
    /// Whether this sheet's view shows zero values, or leaves those cells blank (`<sheetView
    /// showZeros="..">`). `None` leaves Excel's own default (shown).
    pub show_zeros: Option<bool>,
    /// Whether this sheet's view is laid out right-to-left (`<sheetView rightToLeft="..">`). `None`
    /// leaves Excel's own default (left-to-right).
    pub right_to_left: Option<bool>,
    /// The cell selected/active when this sheet is shown (`<selection activeCell=".." sqref="..">`,
    /// both attributes written the same — this crate only models a single selected cell, not a
    /// multi-cell selection). Distinct from [`Workbook::active_tab`]: this is the cell selected
    /// *within* this sheet, not which sheet tab is shown. `None` leaves Excel's own default (`A1`).
    pub active_cell: Option<String>,
    /// This sheet's default column width, in Excel's own character-width units (`<sheetFormatPr
    /// defaultColWidth="..">`). Distinct from [`ColumnSetting::width`](ColumnSetting): this is the
    /// width used for every column *without* its own explicit [`ColumnSetting`]. `None` leaves
    /// Excel's own default.
    pub default_column_width: Option<f64>,
    /// This sheet's default row height, in points (`<sheetFormatPr defaultRowHeight="..">`).
    /// Distinct from [`Row::height`]: this is the height used for every row *without* its own
    /// explicit height. `None` leaves Excel's own default (`15`, i.e. `defaultRowHeight` is always
    /// written with a concrete value — `CT_SheetFormatPr::defaultRowHeight` is mandatory whenever
    /// `<sheetFormatPr>` is written at all, unlike every other field on this type).
    pub default_row_height: Option<f64>,
    /// Manual page breaks after these 1-based row numbers (`<rowBreaks>`/`<brk>`, `CT_PageBreak`).
    pub row_breaks: Vec<u32>,
    /// Manual page breaks after these 1-based column numbers (`<colBreaks>`/`<brk>`).
    pub column_breaks: Vec<u32>,
    /// "What-if" scenarios (`<scenarios>`/`<scenario>`, `CT_Scenario`).
    pub scenarios: Vec<Scenario>,
    /// Per-column filter criteria for [`auto_filter_range`](Sheet::auto_filter_range)
    /// (`<filterColumn>`/`<filters>`, `CT_FilterColumn`/`CT_Filters`). A no-op if
    /// `auto_filter_range` is `None`. Only the simplest form (a fixed list of checked/visible
    /// values) is modeled — `CT_Filters`'s custom criteria, top10, and date-grouping filter forms
    /// are not.
    pub auto_filter_columns: Vec<AutoFilterColumn>,
    /// Suppressed error-checking indicators (the little green triangle in a cell's corner and its
    /// "Ignore Error" right-click option), (`<ignoredErrors>`/`<ignoredError>`, `CT_IgnoredErrors`/
    /// `CT_IgnoredError`). Each entry covers one range and one or more error categories; this crate
    /// writes one `<ignoredError>` element per [`IgnoredError`] entry, same "less compact but
    /// schema-valid" posture as `ColumnSetting`/ `ConditionalFormattingRule` not bothering to merge
    /// adjacent/ overlapping ranges the way real Excel's UI sometimes does.
    pub ignored_errors: Vec<IgnoredError>,
    /// Multiple named protected ranges (`<protectedRanges>`/ `<protectedRange>`,
    /// `CT_ProtectedRanges`/`CT_ProtectedRange`). Distinct from [`Sheet::protection`] (point 13,
    /// `<sheetProtection>`): that locks/unlocks editing for the *whole* sheet at once (based on
    /// each cell's own `locked` [`CellFormat`] flag), while this is Excel's older "Allow Users to
    /// Edit Ranges" feature — one or more named ranges, each optionally its own password, that stay
    /// editable while the rest of a protected sheet is locked. `CT_Worksheet`'s sequence puts
    /// `protectedRanges` right after `sheetProtection`, before `scenarios` (confirmed via
    /// `sml.xsd`).
    pub protected_ranges: Vec<ProtectedRange>,
    /// A remembered sort order for [`auto_filter_range`](Sheet::auto_filter_range)
    /// (`<autoFilter><sortState>..</sortState></autoFilter>`). A no-op if `auto_filter_range` is
    /// `None` (same posture as [`auto_filter_columns`](Sheet::auto_filter_columns)).
    /// `CT_AutoFilter`'s own sequence puts `sortState` *after* `filterColumn*`, nested inside
    /// `<autoFilter>` — distinct from [`ExcelTable::sort_state`], which is a sibling of a table's
    /// own `<autoFilter>`, not a child of it (see that field's doc comment for the schema source).
    pub sort_state: Option<SortState>,
    /// Whether an outline/grouping's summary rows sit below their detail rows, or above
    /// (`<sheetPr><outlinePr summaryBelow="..">`, `CT_SheetPr`/`CT_OutlinePr`). Relevant only when
    /// [`Row::outline_level`]/column grouping is used. `None` leaves Excel's own default (`true`,
    /// summary below); `Some(false)` matches the "summary above" layout common in accounting
    /// templates. Confirmed via `sml.xsd`: `outlinePr` is `CT_SheetPr`'s second child, right after
    /// `tabColor?`.
    pub outline_summary_below: Option<bool>,
    /// Whether an outline/grouping's summary columns sit to the right of their detail columns, or
    /// to the left (`<outlinePr summaryRight="..">`) — same point 55, the column-axis counterpart
    /// of `outline_summary_below`. `None` leaves Excel's own default (`true`, summary to the
    /// right).
    pub outline_summary_right: Option<bool>,
    /// This sheet's DrawingML drawing — embedded pictures and/or charts, each anchored to a cell
    /// range (`<drawing r:id="..">` referencing a dedicated `xl/drawings/drawingN.xml` part,
    /// `CT_Drawing`/`xdr:wsDr`). Only one drawing part per sheet is modeled (this crate's own scope
    /// choice, not an ECMA-376 limit — real Excel only ever has one anyway), same posture as
    /// [`Sheet::table`]. `None` writes no `<drawing>` element and no drawing part at all.
    pub drawing: Option<SheetDrawing>,
}

/// A single row of cells (`<row>`, `CT_Row`).
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Row {
    /// The cells that make up this row, in column order starting at column A. Like `Sheet.rows`, a
    /// cell's column letter is derived from its position in this `Vec`, not stored separately —
    /// writing a row always produces a dense `A`, `B`, `C`. sequence with no gaps. Reading back a
    /// sparse row from a real `.xlsx` (Excel itself never writes a `<c>` element for a genuinely
    /// empty cell) still works: any skipped column is filled in as `CellValue::Empty` so a cell's
    /// index in this `Vec` always matches its real column, see `reader.rs`.
    pub cells: Vec<Cell>,
    /// This row's explicit height, in points (`<row ht=".." customHeight="1">`) — `None` uses
    /// Excel's own default row height.
    pub height: Option<f64>,
    /// Whether this row is hidden (`<row hidden="1">`).
    pub hidden: bool,
    /// This row's outline (grouping) level (`<row outlineLevel="..">`, 0-7).
    pub outline_level: u8,
    /// Whether this row's outline group is shown collapsed (`<row collapsed="1">`, the "-"
    /// summary-only state of the little outline button). Distinct from `outline_level` itself
    /// (which rows belong to the group) — this is only the group's current expanded/collapsed
    /// *display* state.
    pub collapsed: bool,
    /// This row's default cell format (`<row s="n" customFormat="1">`, an index into
    /// `xl/styles.xml`'s `cellXfs`). Same "applies to any cell without its own explicit format,
    /// storage only, caller keeps things straight" posture as [`ColumnSetting::style`] — see its
    /// doc comment for the precedence note. `CT_Row`'s `customFormat` flag is always written
    /// together with `s` when this is `Some` (confirmed via `sml.xsd`: `s` alone with
    /// `customFormat` left at its `false` default means the row number's own displayed style, not
    /// every cell in the row — real Excel always pairs the two when a row-level format is actually
    /// set through its UI).
    pub default_format: Option<CellFormat>,
}

/// A single cell (`<c>`, `CT_Cell`): a value plus an optional style.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Cell {
    /// This cell's value.
    pub value: CellValue,
    /// This cell's style, if any. `None` means the cell uses Excel's own default style
    /// (`xl/styles.xml`'s `cellXfs` index 0, the "Normal" style) — this crate never writes a
    /// `<c>`'s `s` attribute for a cell with no format, matching how real Excel omits `s="0"` too
    /// (it's the implicit default). Distinct `CellFormat`s across a workbook are deduplicated into
    /// shared `cellXfs` entries by the writer, exactly like `CellValue::Text`'s shared-strings
    /// deduplication — see `writer.rs::collect_cell_formats`.
    pub format: Option<CellFormat>,
}

/// A cell's value.
#[derive(Debug, Default, Clone, PartialEq)]
pub enum CellValue {
    /// No value — an empty cell. This crate never writes a `<c>` element for one (matching real
    /// Excel output, which omits genuinely empty cells entirely) *unless* the cell carries a
    /// [`CellFormat`], in which case a self-closing `<c r=".." s=".."/>` is written (a
    /// styled-but-empty cell — real Excel does this too, e.g. for a pre-formatted but not yet
    /// filled-in cell). This variant also exists so a sparse row read back from a real `.xlsx` can
    /// still be represented densely, keeping a cell's `Vec` position equal to its real column. The
    /// default value for a freshly-constructed `Cell`.
    #[default]
    Empty,
    /// A text value (`<c t="s"><v>N</v></c>`, an index into the shared strings table
    /// `xl/sharedStrings.xml` — `CT_Cell`'s `t="str"` in-cell-formula-result and `t="inlineStr"`
    /// variants are not modeled, matching Excel's own default behavior of always deduplicating
    /// repeated text through the shared strings table rather than writing it inline).
    Text(String),
    /// A numeric value (`<c><v>..</v></c>`, `CT_Cell`'s default/`"n"` type — a plain `f64`, written
    /// with Rust's own default floating-point-to-string formatting; not a `CT_Cell`'s `t="b"`
    /// (boolean) or `t="e"` (error) variant).
    Number(f64),
    /// A formula cell (`<c><f>..</f><v>..</v></c>`, `CT_CellFormula` + cached `CT_Cell/@v`).
    /// Formula *evaluation* is out of scope — only the literal formula text and, if present, its
    /// last-computed cached value are stored, never recomputed.
    ///
    /// A cell built via [`Cell::formula`] always has `Some` formula text; writing a cell with
    /// `formula: None` falls back to writing just the cached value with no `<f>` element at all
    /// (see `writer.rs::write_cell`). A real `.xlsx`'s `t="shared"` formula cells (both the group's
    /// master and its followers) now read back as [`SharedFormula`](CellValue::SharedFormula)
    /// instead of this variant — point 52, which replaced this variant's earlier "drop the
    /// `si`/`ref`, keep only the cached value" limit with a dedicated, round-trippable
    /// representation.
    Formula {
        /// The formula text, without a leading `=` (e.g. `"A2*B2"`).
        formula: Option<String>,
        /// The formula's last-computed value, if known.
        cached_value: Option<f64>,
    },
    /// A boolean value (`<c t="b"><v>0|1</v></c>`). Fully round-trippable (unlike `Date`, see
    /// below).
    Boolean(bool),
    /// A date/time value. **Write side only**: [`Cell::date`] converts an [`ExcelDateTime`] to the
    /// serial-day number Excel actually stores (`<c><v>..</v></c>`, a plain numeric cell,
    /// `CT_Cell`'s default type — SpreadsheetML has no dedicated date cell type, a date is *always*
    /// just a number that happens to carry a date-shaped `numFmtId`), so writing one produces
    /// exactly the same XML shape as `CellValue::Number`. Reading a workbook back never
    /// reconstructs this variant, even for a cell this crate's own writer produced — a
    /// date-formatted cell reads back as `CellValue::Number(serial)`, the caller's own
    /// responsibility to reinterpret using the cell's `CellFormat::number_format`, same honest
    /// "storage, not clever inference" posture as this crate's formula-evaluation scope limit. Pair
    /// `Cell::date` with a `CellFormat::with_number_format` (e.g. `"dd/mm/yyyy"`) for Excel to
    /// actually display it as a date rather than a raw serial number — this crate does not do that
    /// automatically (see `Cell::date`'s doc comment), matching `word-ooxml`'s
    /// `PageSetup.orientation` "caller's responsibility" precedent.
    Date(ExcelDateTime),
    /// A text value with per-run character formatting (`<si><r>..</r></si>` in
    /// `xl/sharedStrings.xml` — the "rich text" shared string form, as opposed to
    /// `CellValue::Text`'s plain `<si><t>..</t></si>` form). Fully round-trippable.
    RichText(Vec<RichTextRun>),
    /// An array (CSE, "Ctrl+Shift+Enter") formula (`<c><f t="array" ref=".">.</f><v>.</v></c>`,
    /// `CT_CellFormula`'s `t="array"` variant) — distinct from `Formula`'s plain/shared forms. Real
    /// Excel writes the literal `<f t="array" ref=".">` only on the array range's top-left (anchor)
    /// cell — every other cell the range covers gets no `<f>` at all, just its own cached `<v>`
    /// (this crate's own writer only ever builds a `Cell` holding this variant for the anchor cell
    /// itself; the caller is responsible for the other cells in `range` carrying plain
    /// `CellValue::Number`/`Empty` cells with the right cached values, same "caller keeps things in
    /// sync" posture as `ExcelTable::columns` needing to match the header row's actual text).
    /// Reading a real `.xlsx`'s array-formula continuation cells (which carry no `<f>` at all)
    /// simply reads them back as whatever plain value type their own `<v>`/`t` attribute says —
    /// this crate does not reconstruct that they were once part of an array's range.
    ArrayFormula {
        /// The formula text, without a leading `=`.
        formula: String,
        /// The array's full range this formula fills (e.g. `"B2:B10"`) — a single-cell array
        /// formula still needs its own cell as the range (e.g. `"B2:B2"`).
        range: String,
        /// The formula's last-computed value for this (the anchor) cell, if known.
        cached_value: Option<f64>,
    },
    /// One cell of a shared-formula group (`<c><f t="shared" si=".." ref="..">..</f><v>..</v></c>`
    /// on the group's master cell, or `<c><f t="shared" si=".."/><v>..</v></c>` on a follower cell
    /// — `CT_CellFormula`'s `t="shared"` variant). Confirmed against `sml.xsd`: `si` (the group's
    /// shared index) is the only attribute present on *every* cell in the group; `ref` (the group's
    /// full range) is only meaningful — and, matching real Excel's own convention, only ever
    /// written — on the master cell, the one carrying the actual formula text. This crate does
    /// **not** compute or shift relative references for follower cells (e.g. deriving `"A3*B3"`
    /// from a master's `"A2*B2"`) — same "storage, not evaluation" posture as
    /// [`Formula`](CellValue::Formula) itself; the caller supplies each follower's own
    /// already-correct formula text (or `None`, matching what real Excel itself writes for a
    /// follower — see [`Cell::shared_formula_follower`]).
    SharedFormula {
        /// The formula text, without a leading `=` — `Some` on the group's master cell, `None` on a
        /// follower (real Excel writes a follower's `<f>` with no text content at all, just
        /// `t`/`si`).
        formula: Option<String>,
        /// This formula group's shared index (`si`) — identical across every cell (master and every
        /// follower) belonging to the same group; a workbook may have several independent groups,
        /// each with its own index starting from `0`.
        group_index: u32,
        /// The group's full range (`ref`) — `Some` only on the master cell (the one written first,
        /// real Excel omits it on every follower).
        range: Option<String>,
        /// This cell's own last-computed value, if known.
        cached_value: Option<f64>,
    },
}

/// A calendar date/time, used to build a [`CellValue::Date`] (`Cell::date`) — deliberately not tied
/// to any external date/time crate (this project's dependency policy only forbids third-party
/// *OOXML-implementing* crates, but a plain field struct is simpler still and avoids the question
/// entirely). Only the proleptic Gregorian calendar and Excel's default "1900 date system" are
/// supported — the legacy "1904 date system" (an old Mac Excel option, `<workbookPr
/// date1904="1"/>`) is not modeled, same "one well-defined behavior, not every historical Excel
/// quirk" posture as elsewhere in this crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExcelDateTime {
    pub year: i32,
    pub month: u32,
    pub day: u32,
    pub hour: u32,
    pub minute: u32,
    pub second: u32,
}

impl ExcelDateTime {
    /// Creates a date with no time component (midnight).
    pub fn date(year: i32, month: u32, day: u32) -> Self {
        Self {
            year,
            month,
            day,
            hour: 0,
            minute: 0,
            second: 0,
        }
    }

    /// Sets a time-of-day component and returns the date for chaining.
    pub fn with_time(mut self, hour: u32, minute: u32, second: u32) -> Self {
        self.hour = hour;
        self.minute = minute;
        self.second = second;
        self
    }
}

/// One run of a [`CellValue::RichText`] value: a span of text sharing the same character formatting
/// (`<r><rPr>..</rPr><t>..</t></r>`, `CT_RElt`) — a deliberately scoped-down subset of
/// `CT_RPrElt`'s full run-property surface (bold/italic/color/size only, same subset `CellFormat`'s
/// own font fields already cover; underline/strike/ vertical-align/font-family are not modeled).
#[derive(Debug, Clone, PartialEq)]
pub struct RichTextRun {
    pub text: String,
    pub bold: bool,
    pub italic: bool,
    /// The run's font color, as an 8-hex-digit ARGB string.
    pub font_color: Option<String>,
    /// The run's font size, in points.
    pub font_size: Option<f64>,
    /// The run's font name/family (e.g. `"Calibri"`).
    pub font_name: Option<String>,
    /// Underline (plain single underline only, same posture as [`CellFormat::underline`]).
    pub underline: bool,
    /// Strikethrough.
    pub strike: bool,
}

impl RichTextRun {
    /// Creates a plain (no formatting) run.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            bold: false,
            italic: false,
            font_color: None,
            font_size: None,
            font_name: None,
            underline: false,
            strike: false,
        }
    }

    /// Sets bold and returns the run for chaining.
    pub fn with_bold(mut self, bold: bool) -> Self {
        self.bold = bold;
        self
    }

    /// Sets italic and returns the run for chaining.
    pub fn with_italic(mut self, italic: bool) -> Self {
        self.italic = italic;
        self
    }

    /// Sets the font color (8-hex-digit ARGB) and returns the run for chaining.
    pub fn with_font_color(mut self, color: impl Into<String>) -> Self {
        self.font_color = Some(color.into());
        self
    }

    /// Sets the font size, in points, and returns the run for chaining.
    pub fn with_font_size(mut self, size: f64) -> Self {
        self.font_size = Some(size);
        self
    }

    /// Sets the font name/family and returns the run for chaining.
    pub fn with_font_name(mut self, font_name: impl Into<String>) -> Self {
        self.font_name = Some(font_name.into());
        self
    }

    /// Sets underline and returns the run for chaining.
    pub fn with_underline(mut self, underline: bool) -> Self {
        self.underline = underline;
        self
    }

    /// Sets strikethrough and returns the run for chaining.
    pub fn with_strike(mut self, strike: bool) -> Self {
        self.strike = strike;
        self
    }
}

/// A cell's style: a number format, basic font attributes (bold/italic/size/color), a solid
/// background fill color, borders, and horizontal/vertical alignment.
///
/// Not deduplicated on the model itself — the writer deduplicates identical `CellFormat`s into
/// shared `xl/styles.xml` entries (`numFmts`/`fonts`/`fills`/`cellXfs`) when serializing, exactly
/// like `Workbook`'s own shared-strings deduplication for repeated text (see
/// `writer.rs::collect_cell_formats`/`build_styles`).
#[derive(Debug, Default, Clone, PartialEq)]
pub struct CellFormat {
    /// A custom number format code (e.g. `"0.00"`, `"#,##0"`). Always registered as a *custom*
    /// format (`numFmtId` >= 164) when written, even if the code happens to match one of Excel's
    /// built-in format codes — this crate does not maintain the built-in-format lookup table
    /// (`BuiltinFormats`), so it never reuses a built-in id. Reading back a real `.xlsx`'s built-in
    /// number format (any `numFmtId` not declared in that file's own `<numFmts>`) is not modeled
    /// either: it reads back as `None`.
    pub number_format: Option<String>,
    /// Bold font weight.
    pub bold: bool,
    /// Italic font style.
    pub italic: bool,
    /// Font size in points. `None` uses the workbook default (11pt) — note that writing *any* other
    /// font attribute (bold, italic, or a color) also resolves this to the default 11pt in the
    /// generated `xl/styles.xml` font entry (a single `<font>` element can't leave "unset"
    /// attributes that fall back independently), so reading a round-tripped format back may see
    /// `Some(11.0)` rather than `None` — a known, accepted round-trip nuance.
    pub font_size: Option<f64>,
    /// Font color, as an 8-hex-digit ARGB string (e.g. `"FFFF0000"` for opaque red). `None` uses
    /// the workbook default (opaque black) — same round-trip nuance as `font_size` applies here too
    /// (and to `font_name` below).
    pub font_color: Option<String>,
    /// Solid background fill color, as an 8-hex-digit ARGB string. `None` leaves the cell unfilled.
    pub fill_color: Option<String>,
    /// Horizontal alignment. `None` uses Excel's own default (`general` — text left-aligned,
    /// numbers right-aligned).
    pub horizontal_alignment: Option<HorizontalAlignment>,
    /// Vertical alignment. `None` uses Excel's own default (`bottom`).
    pub vertical_alignment: Option<VerticalAlignment>,
    /// This cell's borders (top/bottom/left/right/diagonal). `Border::default()` (all
    /// `None`/`false`) draws no border at all, matching every other `CellFormat` field's "unset
    /// means Excel's own default" posture.
    pub border: Border,
    /// Font name/family (e.g. `"Calibri"`, `"Arial"`). `None` uses the workbook default (Excel's
    /// own "Calibri"). Only a single Latin font name is modeled, not `CT_Font`'s separate
    /// east-Asian/complex-script overrides (`family`/`scheme`/`charset` are not modeled either).
    /// Same unset-resolves-to-the-default round-trip nuance as `font_size`/ `font_color` above
    /// applies here too: writing any other font attribute also resolves this to `Some("Calibri")`
    /// in the generated `<font>` entry, so an originally-`None` `font_name` may read back as
    /// `Some("Calibri")` rather than `None`.
    pub font_name: Option<String>,
    /// Underline. Only a plain single underline is modeled (`CT_Font`'s `ST_UnderlineValues` has
    /// several more: `double`/`singleAccounting`/ `doubleAccounting`) — same on/off posture
    /// `RichTextRun`'s `bold`/`italic` already use (unlike `word-ooxml`'s much richer
    /// `UnderlineStyle` enum).
    pub underline: bool,
    /// Strikethrough.
    pub strike: bool,
    /// Wraps text onto multiple lines within the cell (`wrapText`).
    pub wrap_text: bool,
    /// Indentation level (`indent`, roughly 3 character-widths per level).
    pub indent: Option<u32>,
    /// Text rotation, in Excel's own raw `ST_CellAlignment`/`textRotation` units — `0` to `90` for
    /// counter-clockwise degrees, `91` to `180` for clockwise degrees (stored as `90 - angle`, e.g.
    /// a plain `-45°` tilt is `135`), or the special value `255` for top-to-bottom vertical text.
    /// Written and read back verbatim — converting a plain signed angle into this encoding is the
    /// caller's responsibility, same "storage, not a conversion helper" posture as
    /// `PrintSettings::header`'s raw `&L`/`&C`/`&R` codes.
    pub text_rotation: Option<u16>,
    /// Shrinks the font size to fit the cell's width instead of wrapping or overflowing
    /// (`shrinkToFit`).
    pub shrink_to_fit: bool,
    /// A non-solid pattern fill (`<patternFill patternType="..">` with a foreground/background
    /// color pair). Mutually exclusive with
    /// [`fill_color`](CellFormat::fill_color)/[`gradient_fill`](CellFormat::gradient_fill) in
    /// practice (Excel itself only ever uses one `<fill>` child); if more than one is set, the
    /// writer prefers `gradient_fill`, then `pattern_fill`, then `fill_color`, see
    /// `writer.rs::resolve_fill`.
    pub pattern_fill: Option<PatternFill>,
    /// A gradient fill (`<gradientFill>`). Only the linear (angle-based) gradient form is modeled,
    /// not `CT_GradientFill`'s "path" (radial, from-center) form. See `pattern_fill`'s doc comment
    /// for the precedence rule when more than one fill field is set.
    pub gradient_fill: Option<GradientFill>,
    /// Whether this cell is locked when the sheet is protected (`<protection locked=".">`,
    /// `CT_CellProtection`) — independent of [`Sheet::protection`] actually being turned on: Excel
    /// itself treats every cell as `locked` by default, so protection only has a visible effect
    /// once [`Sheet::protection`] is `Some`. `None` leaves Excel's own default (locked).
    pub locked: Option<bool>,
    /// Whether this cell's formula is hidden from the formula bar when the sheet is protected
    /// (`<protection hidden="..">`). `None` leaves Excel's own default (not hidden). Meaningless on
    /// a non-formula cell, same as real Excel.
    pub formula_hidden: Option<bool>,
    /// Links this format to one of [`Workbook::named_cell_styles`] by name (resolved into that
    /// entry's index, written as this format's `cellXfs` `xfId` attribute). This is what makes a
    /// cell show up as e.g. "Good"/"Heading 1" in Excel's own Cell Styles gallery
    /// (highlighted/selected) rather than merely happening to look the same. `None` (the default)
    /// writes `xfId="0"`, i.e. based on the implicit `"Normal"` style, same as every `CellFormat`
    /// before this point. A name not found in `Workbook::named_cell_styles` at write time silently
    /// falls back to `0` too — see that field's own doc comment.
    pub named_style: Option<String>,
}

/// A cell's horizontal alignment (`ST_HorizontalAlignment`) — only the three most common values are
/// modeled; `general`/`fill`/`justify`/ `centerContinuous`/`distributed` are not (they read back as
/// `None`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HorizontalAlignment {
    Left,
    Center,
    Right,
}

/// A cell's vertical alignment (`ST_VerticalAlignment`) — only the three most common values are
/// modeled; `justify`/`distributed` are not (they read back as `None`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerticalAlignment {
    Top,
    Center,
    Bottom,
}

/// A border line style (`ST_BorderStyle`) — only the handful of styles a real spreadsheet actually
/// uses day to day are modeled; `hair`/`mediumDashed`/`dashDot`/`mediumDashDot`/`dashDotDot`/
/// `mediumDashDotDot`/`slantDashDot` are not (out of scope, same scope-reduction posture as
/// elsewhere in this crate).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BorderStyle {
    Thin,
    Medium,
    Thick,
    Dashed,
    Dotted,
    Double,
    Hair,
}

/// One edge of a [`Border`] (`<left>`/`<right>`/`<top>`/`<bottom>`/ `<diagonal>`, `CT_BorderPr`): a
/// line style plus an optional color.
#[derive(Debug, Clone, PartialEq)]
pub struct BorderEdge {
    pub style: BorderStyle,
    /// The edge's color, as an 8-hex-digit ARGB string. `None` leaves the edge at Excel's own
    /// default (opaque black).
    pub color: Option<String>,
}

impl BorderEdge {
    /// Creates a border edge with the given style, no explicit color (opaque black, Excel's own
    /// default).
    pub fn new(style: BorderStyle) -> Self {
        Self { style, color: None }
    }

    /// Sets the edge's color (8-hex-digit ARGB) and returns it for chaining.
    pub fn with_color(mut self, color: impl Into<String>) -> Self {
        self.color = Some(color.into());
        self
    }
}

/// A cell's borders (`<border>`, `CT_Border`) — up to four edges plus an optional diagonal.
/// `Border::default()` (every field `None`/`false`) draws no border at all.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Border {
    pub top: Option<BorderEdge>,
    pub bottom: Option<BorderEdge>,
    pub left: Option<BorderEdge>,
    pub right: Option<BorderEdge>,
    /// The diagonal line's style/color — only drawn if [`diagonal_up`](Border::diagonal_up) and/or
    /// [`diagonal_down`](Border::diagonal_down) is also set (`CT_Border`'s own
    /// `diagonalUp`/`diagonalDown` attributes live on the parent `<border>` element, not
    /// `<diagonal>` itself).
    pub diagonal: Option<BorderEdge>,
    /// Draws the diagonal from bottom-left to top-right.
    pub diagonal_up: bool,
    /// Draws the diagonal from top-left to bottom-right.
    pub diagonal_down: bool,
}

impl Border {
    /// Creates a `Border` with no edges at all.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the top edge and returns the border for chaining.
    pub fn with_top(mut self, edge: BorderEdge) -> Self {
        self.top = Some(edge);
        self
    }

    /// Sets the bottom edge and returns the border for chaining.
    pub fn with_bottom(mut self, edge: BorderEdge) -> Self {
        self.bottom = Some(edge);
        self
    }

    /// Sets the left edge and returns the border for chaining.
    pub fn with_left(mut self, edge: BorderEdge) -> Self {
        self.left = Some(edge);
        self
    }

    /// Sets the right edge and returns the border for chaining.
    pub fn with_right(mut self, edge: BorderEdge) -> Self {
        self.right = Some(edge);
        self
    }

    /// Sets the diagonal edge and whether it runs bottom-left-to-top-right and/or
    /// top-left-to-bottom-right, and returns the border for chaining.
    pub fn with_diagonal(mut self, edge: BorderEdge, up: bool, down: bool) -> Self {
        self.diagonal = Some(edge);
        self.diagonal_up = up;
        self.diagonal_down = down;
        self
    }

    /// A convenience for the common case of the same style/color on all four sides (a full box
    /// border) — equivalent to calling
    /// [`with_top`](Border::with_top)/[`with_bottom`](Border::with_bottom)/
    /// [`with_left`](Border::with_left)/[`with_right`](Border::with_right) with four identical
    /// edges.
    pub fn all(style: BorderStyle, color: impl Into<String>) -> Self {
        let color = color.into();
        Self {
            top: Some(BorderEdge::new(style).with_color(color.clone())),
            bottom: Some(BorderEdge::new(style).with_color(color.clone())),
            left: Some(BorderEdge::new(style).with_color(color.clone())),
            right: Some(BorderEdge::new(style).with_color(color)),
            diagonal: None,
            diagonal_up: false,
            diagonal_down: false,
        }
    }
}

impl Workbook {
    /// Creates an empty workbook (no sheets).
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends a sheet and returns the workbook for chaining.
    pub fn with_sheet(mut self, sheet: Sheet) -> Self {
        self.sheets.push(sheet);
        self
    }

    /// Appends an empty sheet with the given name and returns a mutable reference to it, to build
    /// it up in place (e.g. `workbook.add_sheet("Feuil1").write_cell(1, 1, Cell::text("Hi"))`). A
    /// `&mut self` counterpart to [`Self::with_sheet`], for building a workbook sheet-by-sheet in a
    /// loop without the consuming builder's `workbook = workbook.with_sheet(..)` reassignment on
    /// every iteration.
    pub fn add_sheet(&mut self, name: impl Into<String>) -> &mut Sheet {
        self.sheets.push(Sheet::new(name));
        self.sheets.last_mut().expect("a sheet was just pushed")
    }

    /// Appends a defined name and returns the workbook for chaining.
    pub fn with_defined_name(mut self, defined_name: DefinedName) -> Self {
        self.defined_names.push(defined_name);
        self
    }

    /// Sets this workbook's calculation properties and returns it for chaining.
    pub fn with_calculation(mut self, calculation: CalculationProperties) -> Self {
        self.calculation = Some(calculation);
        self
    }

    /// Appends a custom table style definition and returns the workbook for chaining. See
    /// [`ExcelTable::table_style_name`]'s doc comment for how a table references one of these by
    /// name.
    pub fn with_table_style(mut self, table_style: TableStyle) -> Self {
        self.table_styles.push(table_style);
        self
    }

    /// Sets this workbook's write-protection and returns it for chaining.
    pub fn with_write_protection(mut self, write_protection: WriteProtection) -> Self {
        self.write_protection = Some(write_protection);
        self
    }

    /// Appends a named cell style definition and returns the workbook for chaining. See
    /// [`CellFormat::named_style`]'s doc comment for how a format references one of these by name.
    pub fn with_named_cell_style(mut self, named_cell_style: NamedCellStyle) -> Self {
        self.named_cell_styles.push(named_cell_style);
        self
    }
}

/// A workbook's recalculation mode (`<calcPr calcMode="..">`, `ST_CalcMode`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CalculationMode {
    /// Recalculates automatically whenever a dependency changes (Excel's own default).
    Automatic,
    /// Recalculates automatically except for data tables (`ST_CalcMode`'s `"autoNoTable"`) — data
    /// tables (`TABLE()` what-if formulas) only recalculate on a manual trigger, everything else
    /// stays automatic.
    AutomaticExceptTables,
    /// Only recalculates when the user explicitly triggers it (F9 or "Calculate Now").
    Manual,
}

/// Workbook-wide calculation properties (`<calcPr>`, `CT_CalcPr`). This crate never evaluates
/// formulas itself (see `CellValue::Formula`'s doc comment) — these settings are pure storage,
/// telling *Excel* how to recalculate once the file is opened, same "storage, not evaluation"
/// posture as a formula's own text.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CalculationProperties {
    /// The recalculation mode. `None` leaves Excel's own default (automatic).
    pub mode: Option<CalculationMode>,
    /// Enables iterative calculation, needed for formulas with intentional circular references
    /// (`<calcPr iterate="1">`) — without this, Excel refuses to open a file containing a genuine
    /// circular reference without warning the user first.
    pub iterate: bool,
}

impl CalculationProperties {
    /// Calculation properties with Excel's own defaults (automatic mode, no iterative calculation)
    /// — only useful as a starting point for the `with_*` builders, since this is equivalent to
    /// leaving `Workbook.calculation` as `None` entirely.
    pub fn new() -> Self {
        Self {
            mode: None,
            iterate: false,
        }
    }

    /// Sets the recalculation mode and returns the properties for chaining.
    pub fn with_mode(mut self, mode: CalculationMode) -> Self {
        self.mode = Some(mode);
        self
    }

    /// Enables iterative calculation and returns the properties for chaining.
    pub fn with_iterate(mut self, iterate: bool) -> Self {
        self.iterate = iterate;
        self
    }
}

impl Default for CalculationProperties {
    fn default() -> Self {
        Self::new()
    }
}

impl Sheet {
    /// Creates an empty sheet (no rows) with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            rows: Vec::new(),
            conditional_formatting_rules: Vec::new(),
            data_validation_rules: Vec::new(),
            merged_ranges: Vec::new(),
            column_settings: Vec::new(),
            auto_filter_range: None,
            freeze_panes: None,
            print_settings: PrintSettings::default(),
            protection: None,
            hyperlinks: Vec::new(),
            comments: Vec::new(),
            table: None,
            visibility: SheetVisibility::Visible,
            zoom_scale: None,
            row_breaks: Vec::new(),
            column_breaks: Vec::new(),
            scenarios: Vec::new(),
            auto_filter_columns: Vec::new(),
            tab_color: None,
            show_grid_lines: None,
            show_row_col_headers: None,
            show_zeros: None,
            right_to_left: None,
            active_cell: None,
            default_column_width: None,
            default_row_height: None,
            ignored_errors: Vec::new(),
            protected_ranges: Vec::new(),
            sort_state: None,
            outline_summary_below: None,
            outline_summary_right: None,
            drawing: None,
        }
    }

    /// Appends a row and returns the sheet for chaining.
    pub fn with_row(mut self, row: Row) -> Self {
        self.rows.push(row);
        self
    }

    /// Writes `cell` at the given 1-based `(row, col)` position — `(1, 1)` is `A1` — growing `rows`
    /// and the target row's own `cells` with empty padding cells as needed to reach it, and returns
    /// a mutable reference to the cell just written. Direct coordinate addressing, for the common
    /// case of writing cells out of strict top-to-bottom, left-to-right order (or just one cell at
    /// a time in a loop) without assembling a full [`Row`] by hand first. 1-based, to match this
    /// crate's own existing convention — a row's or cell's position in its `Vec` plus one (see
    /// [`Sheet::rows`]'s and [`Row::cells`]'s doc comments) — so a `Sheet` never mixes two
    /// different numbering schemes depending on which method touched it.
    ///
    /// Padding cells are genuinely empty ([`Cell::new`]/[`Cell::default`]), not written out as
    /// `<c>` elements at all unless later given a format — same posture as a sparse [`Row`] built
    /// by hand.
    ///
    /// Accepts anything convertible to a [`Cell`] — a `Cell` itself (built via
    /// [`Cell::text`]/[`Cell::formula`]/[`Cell::date`]/etc. for the cases below that need one made
    /// explicitly), or, for the three unambiguous cases, the raw value directly: `&str`/`String` (→
    /// [`CellValue::Text`]), `f64` (→ [`CellValue::Number`]), `bool` (→ [`CellValue::Boolean`]) —
    /// the common case a caller writing cells one at a time reaches for most often. Formulas,
    /// dates, rich text, and array formulas are deliberately *not* covered by an automatic
    /// conversion — there's no unambiguous way to tell "this is a formula" from a plain string, or
    /// "this number is a date" from a plain number, so those still go through their own `Cell::*`
    /// constructor.
    ///
    /// # Panics
    ///
    /// Panics if `row` or `col` is `0` (1-based, so `0` is never a valid position).
    pub fn write_cell(&mut self, row: u32, col: u32, cell: impl Into<Cell>) -> &mut Cell {
        assert!(
            row >= 1 && col >= 1,
            "write_cell uses 1-based row/col indices, got ({row}, {col})"
        );
        let cell = cell.into();
        let row_index = (row - 1) as usize;
        let col_index = (col - 1) as usize;

        if self.rows.len() <= row_index {
            self.rows.resize_with(row_index + 1, Row::default);
        }
        let target_row = &mut self.rows[row_index];
        if target_row.cells.len() <= col_index {
            target_row.cells.resize_with(col_index + 1, Cell::default);
        }
        target_row.cells[col_index] = cell;
        &mut target_row.cells[col_index]
    }

    /// Appends a conditional formatting rule and returns the sheet for chaining.
    pub fn with_conditional_formatting_rule(mut self, rule: ConditionalFormattingRule) -> Self {
        self.conditional_formatting_rules.push(rule);
        self
    }

    /// Appends a data validation rule and returns the sheet for chaining.
    pub fn with_data_validation_rule(mut self, rule: DataValidationRule) -> Self {
        self.data_validation_rules.push(rule);
        self
    }

    /// Appends a merged cell range (e.g. `"A1:C1"`) and returns the sheet for chaining.
    pub fn with_merged_range(mut self, range: impl Into<String>) -> Self {
        self.merged_ranges.push(range.into());
        self
    }

    /// Appends a column setting and returns the sheet for chaining.
    pub fn with_column_setting(mut self, setting: ColumnSetting) -> Self {
        self.column_settings.push(setting);
        self
    }

    /// Sets the autofilter range and returns the sheet for chaining.
    pub fn with_auto_filter_range(mut self, range: impl Into<String>) -> Self {
        self.auto_filter_range = Some(range.into());
        self
    }

    /// Sets frozen panes and returns the sheet for chaining.
    pub fn with_freeze_panes(mut self, freeze_panes: FreezePane) -> Self {
        self.freeze_panes = Some(freeze_panes);
        self
    }

    /// Sets this sheet's print settings and returns the sheet for chaining.
    pub fn with_print_settings(mut self, print_settings: PrintSettings) -> Self {
        self.print_settings = print_settings;
        self
    }

    /// Sets this sheet's protection and returns the sheet for chaining.
    pub fn with_protection(mut self, protection: SheetProtection) -> Self {
        self.protection = Some(protection);
        self
    }

    /// Appends a cell hyperlink and returns the sheet for chaining.
    pub fn with_hyperlink(mut self, hyperlink: CellHyperlink) -> Self {
        self.hyperlinks.push(hyperlink);
        self
    }

    /// Appends a cell comment and returns the sheet for chaining.
    pub fn with_comment(mut self, comment: CellComment) -> Self {
        self.comments.push(comment);
        self
    }

    /// Sets this sheet's structured table and returns the sheet for chaining.
    pub fn with_table(mut self, table: ExcelTable) -> Self {
        self.table = Some(table);
        self
    }

    /// Sets this sheet's drawing (embedded pictures/charts) and returns the sheet for chaining.
    pub fn with_drawing(mut self, drawing: SheetDrawing) -> Self {
        self.drawing = Some(drawing);
        self
    }

    /// Sets this sheet's tab visibility and returns the sheet for chaining — replacing the old
    /// `with_hidden(bool)` (removed, pre-1.0 breaking change): use
    /// `with_visibility(SheetVisibility::Hidden)` for what used to be `with_hidden(true)`.
    pub fn with_visibility(mut self, visibility: SheetVisibility) -> Self {
        self.visibility = visibility;
        self
    }

    /// Sets this sheet's display zoom percentage and returns the sheet for chaining.
    pub fn with_zoom_scale(mut self, zoom_scale: u32) -> Self {
        self.zoom_scale = Some(zoom_scale);
        self
    }

    /// Sets this sheet's tab color (8-hex-digit ARGB) and returns the sheet for chaining.
    pub fn with_tab_color(mut self, color: impl Into<String>) -> Self {
        self.tab_color = Some(color.into());
        self
    }

    /// Sets whether this sheet's view shows gridlines and returns the sheet for chaining.
    pub fn with_show_grid_lines(mut self, show: bool) -> Self {
        self.show_grid_lines = Some(show);
        self
    }

    /// Sets whether this sheet's view shows row/column headers and returns the sheet for chaining.
    pub fn with_show_row_col_headers(mut self, show: bool) -> Self {
        self.show_row_col_headers = Some(show);
        self
    }

    /// Sets whether this sheet's view shows zero values and returns the sheet for chaining.
    pub fn with_show_zeros(mut self, show: bool) -> Self {
        self.show_zeros = Some(show);
        self
    }

    /// Sets whether this sheet's view is laid out right-to-left and returns the sheet for chaining.
    pub fn with_right_to_left(mut self, right_to_left: bool) -> Self {
        self.right_to_left = Some(right_to_left);
        self
    }

    /// Sets the cell selected/active when this sheet is shown (e.g. `"B3"`) and returns the sheet
    /// for chaining.
    pub fn with_active_cell(mut self, cell: impl Into<String>) -> Self {
        self.active_cell = Some(cell.into());
        self
    }

    /// Sets this sheet's default column width and returns the sheet for chaining.
    pub fn with_default_column_width(mut self, width: f64) -> Self {
        self.default_column_width = Some(width);
        self
    }

    /// Sets this sheet's default row height and returns the sheet for chaining.
    pub fn with_default_row_height(mut self, height: f64) -> Self {
        self.default_row_height = Some(height);
        self
    }

    /// Adds a manual page break after the given 1-based row number and returns the sheet for
    /// chaining.
    pub fn with_row_break(mut self, row: u32) -> Self {
        self.row_breaks.push(row);
        self
    }

    /// Adds a manual page break after the given 1-based column number and returns the sheet for
    /// chaining.
    pub fn with_column_break(mut self, column: u32) -> Self {
        self.column_breaks.push(column);
        self
    }

    /// Appends a "what-if" scenario and returns the sheet for chaining.
    pub fn with_scenario(mut self, scenario: Scenario) -> Self {
        self.scenarios.push(scenario);
        self
    }

    /// Appends an autofilter column's criteria and returns the sheet for chaining.
    pub fn with_auto_filter_column(mut self, column: AutoFilterColumn) -> Self {
        self.auto_filter_columns.push(column);
        self
    }

    /// Appends a suppressed error-checking entry and returns the sheet for chaining.
    pub fn with_ignored_error(mut self, ignored_error: IgnoredError) -> Self {
        self.ignored_errors.push(ignored_error);
        self
    }

    /// Appends a named protected range and returns the sheet for chaining.
    pub fn with_protected_range(mut self, protected_range: ProtectedRange) -> Self {
        self.protected_ranges.push(protected_range);
        self
    }

    /// Sets this sheet's (worksheet-level `<autoFilter>`) remembered sort order and returns the
    /// sheet for chaining. See [`Sheet::sort_state`]'s doc comment: a no-op unless
    /// [`with_auto_filter_range`](Sheet::with_auto_filter_range) is also used.
    pub fn with_sort_state(mut self, sort_state: SortState) -> Self {
        self.sort_state = Some(sort_state);
        self
    }

    /// Sets whether outline/grouping summary rows sit below (`true`) or above (`false`) their
    /// detail rows, and returns the sheet for chaining.
    pub fn with_outline_summary_below(mut self, summary_below: bool) -> Self {
        self.outline_summary_below = Some(summary_below);
        self
    }

    /// Sets whether outline/grouping summary columns sit to the right (`true`) or left (`false`) of
    /// their detail columns, and returns the sheet for chaining — point 55, the column-axis
    /// counterpart of `with_outline_summary_below`.
    pub fn with_outline_summary_right(mut self, summary_right: bool) -> Self {
        self.outline_summary_right = Some(summary_right);
        self
    }
}

impl Row {
    /// Creates an empty row (no cells).
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends a cell and returns the row for chaining.
    pub fn with_cell(mut self, cell: Cell) -> Self {
        self.cells.push(cell);
        self
    }

    /// Appends a text cell and returns the row for chaining — a convenience for the common case of
    /// not needing `Cell` directly.
    pub fn with_text(self, text: impl Into<String>) -> Self {
        self.with_cell(Cell::text(text))
    }

    /// Appends a numeric cell and returns the row for chaining.
    pub fn with_number(self, number: f64) -> Self {
        self.with_cell(Cell::number(number))
    }

    /// Appends a formula cell (no cached value) and returns the row for chaining.
    pub fn with_formula(self, formula: impl Into<String>) -> Self {
        self.with_cell(Cell::formula(formula))
    }

    /// Sets this row's explicit height, in points, and returns it for chaining.
    pub fn with_height(mut self, height: f64) -> Self {
        self.height = Some(height);
        self
    }

    /// Sets whether this row is hidden and returns it for chaining.
    pub fn with_hidden(mut self, hidden: bool) -> Self {
        self.hidden = hidden;
        self
    }

    /// Sets this row's outline (grouping) level and returns it for chaining.
    pub fn with_outline_level(mut self, level: u8) -> Self {
        self.outline_level = level;
        self
    }

    /// Sets whether this row's outline group is shown collapsed and returns it for chaining.
    pub fn with_collapsed(mut self, collapsed: bool) -> Self {
        self.collapsed = collapsed;
        self
    }

    /// Sets this row's default cell format and returns it for chaining.
    pub fn with_style(mut self, style: CellFormat) -> Self {
        self.default_format = Some(style);
        self
    }
}

impl Cell {
    /// Creates an empty cell.
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a text cell.
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            value: CellValue::Text(text.into()),
            format: None,
        }
    }

    /// Creates a numeric cell.
    pub fn number(number: f64) -> Self {
        Self {
            value: CellValue::Number(number),
            format: None,
        }
    }

    /// Creates a formula cell holding the given formula text (without a leading `=`) and no cached
    /// value yet — see [`Cell::with_cached_value`] to attach one. A formula with no cached value is
    /// still schema-valid (Excel simply recomputes it the next time the file is opened, its
    /// standard behavior for any formula it considers "dirty").
    pub fn formula(formula: impl Into<String>) -> Self {
        Self {
            value: CellValue::Formula {
                formula: Some(formula.into()),
                cached_value: None,
            },
            format: None,
        }
    }

    /// Creates a boolean cell.
    pub fn boolean(value: bool) -> Self {
        Self {
            value: CellValue::Boolean(value),
            format: None,
        }
    }

    /// Creates a date cell from an [`ExcelDateTime`] — see [`CellValue::Date`]'s doc comment: pair
    /// this with a `.with_format(CellFormat::new().with_number_format("dd/mm/yyyy"))` (or any other
    /// date-shaped format code) for Excel to actually display it as a date; without one, Excel
    /// shows the raw serial number.
    pub fn date(date: ExcelDateTime) -> Self {
        Self {
            value: CellValue::Date(date),
            format: None,
        }
    }

    /// Creates a rich-text cell (a text value with per-run character formatting).
    pub fn rich_text(runs: Vec<RichTextRun>) -> Self {
        Self {
            value: CellValue::RichText(runs),
            format: None,
        }
    }

    /// Creates an array (CSE) formula cell holding the given formula text (without a leading `=`)
    /// and range, and no cached value yet — see [`Cell::with_cached_value`] to attach one. This
    /// cell should be placed at the array range's top-left (anchor) position — see
    /// [`CellValue::ArrayFormula`]'s doc comment.
    pub fn array_formula(formula: impl Into<String>, range: impl Into<String>) -> Self {
        Self {
            value: CellValue::ArrayFormula {
                formula: formula.into(),
                range: range.into(),
                cached_value: None,
            },
            format: None,
        }
    }

    /// Creates a shared-formula group's **master** cell — the one carrying the group's actual
    /// formula text and its full `range` — and no cached value yet — see
    /// [`Cell::with_cached_value`] to attach one. Pair with [`Cell::shared_formula_follower`] for
    /// the group's other cells, using the same `group_index`. See [`CellValue::SharedFormula`]'s
    /// doc comment: this crate does not compute each follower's own shifted formula text.
    pub fn shared_formula(
        formula: impl Into<String>,
        group_index: u32,
        range: impl Into<String>,
    ) -> Self {
        Self {
            value: CellValue::SharedFormula {
                formula: Some(formula.into()),
                group_index,
                range: Some(range.into()),
                cached_value: None,
            },
            format: None,
        }
    }

    /// Creates a shared-formula group's **follower** cell — no formula text and no `range`
    /// (matching what real Excel itself writes for a follower, just `t="shared" si=".."`), only the
    /// group's shared `group_index`. See [`Cell::shared_formula`] for the group's master cell.
    pub fn shared_formula_follower(group_index: u32) -> Self {
        Self {
            value: CellValue::SharedFormula {
                formula: None,
                group_index,
                range: None,
                cached_value: None,
            },
            format: None,
        }
    }

    /// Attaches a cached result value to a formula cell and returns the cell for chaining. A no-op
    /// if this cell doesn't hold
    /// `CellValue::Formula`/`CellValue::ArrayFormula`/`CellValue::SharedFormula` (e.g. called on a
    /// `Cell::number`).
    pub fn with_cached_value(mut self, value: f64) -> Self {
        match &mut self.value {
            CellValue::Formula { cached_value, .. }
            | CellValue::ArrayFormula { cached_value, .. }
            | CellValue::SharedFormula { cached_value, .. } => {
                *cached_value = Some(value);
            }
            _ => {}
        }
        self
    }

    /// Attaches a cell style and returns the cell for chaining.
    pub fn with_format(mut self, format: CellFormat) -> Self {
        self.format = Some(format);
        self
    }
}

/// Lets [`Sheet::write_cell`] accept a raw string directly (`sheet.write_cell(1, 1, "Bonjour")`)
/// instead of requiring `Cell::text("Bonjour")` — same rationale as the `f64`/`bool` impls below;
/// see [`Sheet::write_cell`]'s doc comment.
impl From<&str> for Cell {
    fn from(text: &str) -> Self {
        Cell::text(text)
    }
}

/// See the `&str` impl just above.
impl From<String> for Cell {
    fn from(text: String) -> Self {
        Cell::text(text)
    }
}

/// Lets [`Sheet::write_cell`] accept a raw `f64` directly (`sheet.write_cell(1, 1, 42.0)`) instead
/// of requiring `Cell::number(42.0)`.
impl From<f64> for Cell {
    fn from(number: f64) -> Self {
        Cell::number(number)
    }
}

/// Lets [`Sheet::write_cell`] accept a raw `bool` directly (`sheet.write_cell(1, 1, true)`) instead
/// of requiring `Cell::boolean(true)`.
impl From<bool> for Cell {
    fn from(value: bool) -> Self {
        Cell::boolean(value)
    }
}

impl CellFormat {
    /// Creates a default cell format (no overrides at all — equivalent to not setting a format,
    /// only useful as a starting point for the `with_*` builder methods).
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets a custom number format code.
    pub fn with_number_format(mut self, format: impl Into<String>) -> Self {
        self.number_format = Some(format.into());
        self
    }

    /// Sets bold.
    pub fn with_bold(mut self, bold: bool) -> Self {
        self.bold = bold;
        self
    }

    /// Sets italic.
    pub fn with_italic(mut self, italic: bool) -> Self {
        self.italic = italic;
        self
    }

    /// Sets the font size, in points.
    pub fn with_font_size(mut self, size: f64) -> Self {
        self.font_size = Some(size);
        self
    }

    /// Sets the font color (8-hex-digit ARGB, e.g. `"FFFF0000"`).
    pub fn with_font_color(mut self, color: impl Into<String>) -> Self {
        self.font_color = Some(color.into());
        self
    }

    /// Sets the solid background fill color (8-hex-digit ARGB).
    pub fn with_fill_color(mut self, color: impl Into<String>) -> Self {
        self.fill_color = Some(color.into());
        self
    }

    /// Sets horizontal alignment.
    pub fn with_horizontal_alignment(mut self, alignment: HorizontalAlignment) -> Self {
        self.horizontal_alignment = Some(alignment);
        self
    }

    /// Sets vertical alignment.
    pub fn with_vertical_alignment(mut self, alignment: VerticalAlignment) -> Self {
        self.vertical_alignment = Some(alignment);
        self
    }

    /// Sets this cell's borders.
    pub fn with_border(mut self, border: Border) -> Self {
        self.border = border;
        self
    }

    /// Sets the font name/family.
    pub fn with_font_name(mut self, font_name: impl Into<String>) -> Self {
        self.font_name = Some(font_name.into());
        self
    }

    /// Sets underline.
    pub fn with_underline(mut self, underline: bool) -> Self {
        self.underline = underline;
        self
    }

    /// Sets strikethrough.
    pub fn with_strike(mut self, strike: bool) -> Self {
        self.strike = strike;
        self
    }

    /// Sets whether text wraps onto multiple lines within the cell.
    pub fn with_wrap_text(mut self, wrap_text: bool) -> Self {
        self.wrap_text = wrap_text;
        self
    }

    /// Sets the indentation level.
    pub fn with_indent(mut self, indent: u32) -> Self {
        self.indent = Some(indent);
        self
    }

    /// Sets the raw Excel text rotation value (see [`text_rotation`](CellFormat::text_rotation)'s
    /// doc comment for the encoding).
    pub fn with_text_rotation(mut self, text_rotation: u16) -> Self {
        self.text_rotation = Some(text_rotation);
        self
    }

    /// Sets whether the font size shrinks to fit the cell's width.
    pub fn with_shrink_to_fit(mut self, shrink_to_fit: bool) -> Self {
        self.shrink_to_fit = shrink_to_fit;
        self
    }

    /// Sets a non-solid pattern fill.
    pub fn with_pattern_fill(mut self, pattern_fill: PatternFill) -> Self {
        self.pattern_fill = Some(pattern_fill);
        self
    }

    /// Sets a gradient fill.
    pub fn with_gradient_fill(mut self, gradient_fill: GradientFill) -> Self {
        self.gradient_fill = Some(gradient_fill);
        self
    }

    /// Sets whether this cell is locked when the sheet is protected.
    pub fn with_locked(mut self, locked: bool) -> Self {
        self.locked = Some(locked);
        self
    }

    /// Sets whether this cell's formula is hidden when the sheet is protected.
    pub fn with_formula_hidden(mut self, formula_hidden: bool) -> Self {
        self.formula_hidden = Some(formula_hidden);
        self
    }

    /// Links this format to a named cell style (by name, resolved against
    /// [`Workbook::named_cell_styles`] at write time) and returns it for chaining.
    pub fn with_named_style(mut self, name: impl Into<String>) -> Self {
        self.named_style = Some(name.into());
        self
    }
}

/// A [`CellFormat::pattern_fill`]'s pattern (`ST_PatternType`) — the solid fill is deliberately
/// excluded here (that's [`CellFormat::fill_color`]'s job, the common case); only the non-solid
/// patterns are modeled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PatternType {
    Gray125,
    Gray0625,
    DarkGray,
    MediumGray,
    LightGray,
    DarkHorizontal,
    DarkVertical,
    DarkDown,
    DarkUp,
    DarkGrid,
    DarkTrellis,
    LightHorizontal,
    LightVertical,
    LightDown,
    LightUp,
    LightGrid,
    LightTrellis,
}

/// A cell's non-solid pattern fill (`<patternFill patternType="..">`, `CT_PatternFill`).
#[derive(Debug, Clone, PartialEq)]
pub struct PatternFill {
    pub pattern_type: PatternType,
    /// The pattern's foreground color (8-hex-digit ARGB) — the color the pattern's own lines/dots
    /// are drawn in.
    pub fg_color: Option<String>,
    /// The pattern's background color (8-hex-digit ARGB) — the color showing through between the
    /// pattern's lines/dots.
    pub bg_color: Option<String>,
}

impl PatternFill {
    /// Creates a pattern fill with no colors set yet (Excel's own defaults — black foreground,
    /// white background — apply).
    pub fn new(pattern_type: PatternType) -> Self {
        Self {
            pattern_type,
            fg_color: None,
            bg_color: None,
        }
    }

    /// Sets the foreground color and returns the fill for chaining.
    pub fn with_fg_color(mut self, color: impl Into<String>) -> Self {
        self.fg_color = Some(color.into());
        self
    }

    /// Sets the background color and returns the fill for chaining.
    pub fn with_bg_color(mut self, color: impl Into<String>) -> Self {
        self.bg_color = Some(color.into());
        self
    }
}

/// One color stop of a [`GradientFill`] (`<stop position="..">`, `CT_GradientStop`).
#[derive(Debug, Clone, PartialEq)]
pub struct GradientStop {
    /// The stop's position along the gradient, `0.0` to `1.0`.
    pub position: f64,
    /// 8-hex-digit ARGB color.
    pub color: String,
}

impl GradientStop {
    pub fn new(position: f64, color: impl Into<String>) -> Self {
        Self {
            position,
            color: color.into(),
        }
    }
}

/// A cell's linear gradient fill (`<gradientFill degree="..">`, `CT_GradientFill`'s `type="linear"`
/// form — the default, no `type` attribute written). The "path" (radial) gradient form is not
/// modeled.
#[derive(Debug, Clone, PartialEq)]
pub struct GradientFill {
    /// The gradient's angle, in degrees (`0` = left to right).
    pub angle: f64,
    /// The gradient's color stops, in order. Excel itself always expects at least two (a start and
    /// end color) — not enforced here.
    pub stops: Vec<GradientStop>,
}

impl GradientFill {
    pub fn new(angle: f64, stops: Vec<GradientStop>) -> Self {
        Self { angle, stops }
    }
}

/// A relational comparison operator, shared between [`ConditionalFormattingCondition::CellIs`] and
/// [`DataValidationKind`]'s `WholeNumber`/`Decimal` variants — ECMA-376 defines two separate simple
/// types for these (`ST_ConditionalFormattingOperator`/ `ST_DataValidationOperator`), but both
/// share exactly the same 8 relational values, so one Rust enum covers both. Neither schema's full
/// enumeration is modeled: `ST_ConditionalFormattingOperator`'s
/// `containsText`/`notContains`/`beginsWith`/`endsWith` are, despite sharing the same XML
/// attribute, really distinct rule *types* in Excel's own "Highlight Cells Rules" UI, not `cellIs`
/// variants — out of scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComparisonOperator {
    LessThan,
    LessThanOrEqual,
    Equal,
    NotEqual,
    GreaterThanOrEqual,
    GreaterThan,
    Between,
    NotBetween,
}

/// A conditional formatting rule (`<cfRule>`, `CT_CfRule`) applied over a cell range
/// (`<conditionalFormatting sqref="..">`, `CT_ConditionalFormatting`).
///
/// Only the two most common rule types are modeled — see [`ConditionalFormattingCondition`].
/// `CT_CfRule`'s many other types (`colorScale`, `dataBar`, `iconSet`, `top10`, `uniqueValues`,
/// `duplicateValues`, `containsText`, `timePeriod`, `aboveAverage`..) are not modeled — this
/// crate's scope here is deliberately narrow.
#[derive(Debug, Clone, PartialEq)]
pub struct ConditionalFormattingRule {
    /// The cell range this rule applies to (`sqref`, e.g. `"A1:A10"`).
    pub range: String,
    /// The rule's condition.
    pub condition: ConditionalFormattingCondition,
    /// The formatting applied to cells in `range` when `condition` is met — reuses [`CellFormat`],
    /// the same subset already modeled for plain cell styles, as the shape of the underlying
    /// differential format record (`<dxf>`, `CT_Dxf` — confirmed via ECMA-376 to be a sequence of
    /// the same kind of optional `font`/`numFmt`/`fill`/ `alignment`/`border`/`protection` children
    /// `CellFormat` already covers, minus borders/protection). Distinct `CellFormat`s across a
    /// workbook's conditional formatting rules are deduplicated into shared `xl/styles.xml`
    /// `<dxfs>` entries by the writer, see `writer.rs::collect_dxfs`.
    pub format: CellFormat,
}

/// A conditional formatting rule's condition — only `cellIs` (a direct value comparison) and
/// `expression` (an arbitrary custom formula) are modeled, `CT_CfRule`'s two simplest and most
/// common types.
#[derive(Debug, Clone, PartialEq)]
pub enum ConditionalFormattingCondition {
    /// `type="cellIs"`: compares the cell's own value against one or two formulas using a
    /// relational operator (e.g. "greater than 0.5", or "between 10 and 20" when `formula2` is
    /// set).
    CellIs {
        operator: ComparisonOperator,
        /// The first (or only) comparison value/formula.
        formula1: String,
        /// The second comparison value/formula — only meaningful (and required by Excel) for
        /// `Between`/`NotBetween`.
        formula2: Option<String>,
    },
    /// `type="expression"`: an arbitrary formula, evaluated per cell in `range`, with the format
    /// applied when it evaluates to `TRUE`.
    Expression {
        /// The formula text (e.g. `"MOD(ROW(),2)=0"` for zebra striping).
        formula: String,
    },
    /// A 2- or 3-stop color scale (`<colorScale>`, `CT_ColorScale`). Unlike every other condition
    /// variant, a color scale ignores [`ConditionalFormattingRule::format`] entirely (its coloring
    /// comes from the stops themselves, not a `dxf`) — the writer never allocates a `dxfId` for
    /// this variant, see `writer.rs::write_conditional_formatting`.
    ColorScale(Vec<ColorScaleStop>),
    /// A data bar (`<dataBar>`, `CT_DataBar`) — min/max stops plus a single fill color. Like
    /// `ColorScale`, ignores `format`.
    DataBar {
        min: CfvoPosition,
        max: CfvoPosition,
        color: String,
    },
    /// A 3-icon set (`<iconSet>`, `CT_IconSet`) using Excel's own default equal-thirds percent
    /// thresholds (0/33/67) — only the icon set's visual style is configurable, not custom
    /// thresholds (out of scope). Like `ColorScale`, ignores `format`.
    IconSet(IconSetType),
    /// `type="top10"`: highlights the top (or bottom) `rank` items/percent of `range`.
    Top10 {
        rank: u32,
        /// Whether `rank` is a percentage rather than a raw count.
        percent: bool,
        /// Highlights the *bottom* `rank` instead of the top.
        bottom: bool,
    },
    /// `type="aboveAverage"`: highlights cells above (or below) the range's average.
    AboveAverage {
        /// Highlights above-average cells (`true`) or below-average ones (`false`).
        above: bool,
        /// Also highlights cells exactly equal to the average.
        equal_average: bool,
    },
    /// `type="duplicateValues"`: highlights cells whose value appears more than once in `range`.
    DuplicateValues,
    /// `type="uniqueValues"`: highlights cells whose value appears exactly once in `range`.
    UniqueValues,
    /// `type="containsText"`/`"notContains"`/`"beginsWith"`/`"endsWith"` (four distinct `CT_CfRule`
    /// types sharing the same shape, see [`TextComparisonOperator`]): highlights cells whose text
    /// matches `text` per `operator`. Unlike `ConditionalFormattingCondition::CellIs`, Excel
    /// auto-generates the underlying formula from `text` and the range's first cell — this crate
    /// reproduces that (see `writer.rs::write_conditional_formatting`), it isn't the caller's
    /// formula to write.
    ContainsText {
        operator: TextComparisonOperator,
        text: String,
    },
}

/// A [`ConditionalFormattingCondition::ColorScale`] stop: a threshold position plus the color
/// applied there (colors between two stops are interpolated by Excel itself, not written to the
/// file).
#[derive(Debug, Clone, PartialEq)]
pub struct ColorScaleStop {
    pub position: CfvoPosition,
    /// 8-hex-digit ARGB color.
    pub color: String,
}

impl ColorScaleStop {
    pub fn new(position: CfvoPosition, color: impl Into<String>) -> Self {
        Self {
            position,
            color: color.into(),
        }
    }
}

/// A threshold position for a [`ColorScaleStop`]/`DataBar` min or max (`<cfvo type=".." val="..">`,
/// `CT_Cfvo`) — only the three most common `ST_CfvoType` values are modeled;
/// `formula`/`percentile`/`autoMin`/ `autoMax` are not.
#[derive(Debug, Clone, PartialEq)]
pub enum CfvoPosition {
    /// `type="min"`: the range's own minimum value — `Min`/`Max` carry no `val` attribute at all
    /// when written.
    Min,
    /// `type="max"`: the range's own maximum value.
    Max,
    /// `type="percent"`, e.g. `Percent(50.0)` for the 50th percentile point.
    Percent(f64),
    /// `type="num"`: a fixed literal value.
    Number(f64),
}

/// A [`ConditionalFormattingCondition::IconSet`]'s visual style (`ST_IconSetType`) — only the
/// handful of 3-icon sets most commonly used are modeled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IconSetType {
    ThreeTrafficLights,
    ThreeArrows,
    ThreeFlags,
    ThreeSymbols,
}

/// The comparison performed by a [`ConditionalFormattingCondition::ContainsText`] rule — shares the
/// `cellIs`-adjacent `operator` attribute name with [`ComparisonOperator`], but is a distinct,
/// disjoint set of values (`ST_ConditionalFormattingOperator`'s text-comparison subset), so it's
/// its own enum rather than reusing `ComparisonOperator`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextComparisonOperator {
    Contains,
    NotContains,
    BeginsWith,
    EndsWith,
}

impl ConditionalFormattingRule {
    /// Creates a `cellIs` rule.
    pub fn cell_is(
        range: impl Into<String>,
        operator: ComparisonOperator,
        formula1: impl Into<String>,
        format: CellFormat,
    ) -> Self {
        Self {
            range: range.into(),
            condition: ConditionalFormattingCondition::CellIs {
                operator,
                formula1: formula1.into(),
                formula2: None,
            },
            format,
        }
    }

    /// Sets the second comparison formula (for `Between`/`NotBetween`) and returns the rule for
    /// chaining. A no-op if this rule isn't a `CellIs` condition.
    pub fn with_second_formula(mut self, formula2: impl Into<String>) -> Self {
        if let ConditionalFormattingCondition::CellIs {
            formula2: existing, ..
        } = &mut self.condition
        {
            *existing = Some(formula2.into());
        }
        self
    }

    /// Creates an `expression` rule.
    pub fn expression(
        range: impl Into<String>,
        formula: impl Into<String>,
        format: CellFormat,
    ) -> Self {
        Self {
            range: range.into(),
            condition: ConditionalFormattingCondition::Expression {
                formula: formula.into(),
            },
            format,
        }
    }

    /// Creates a color scale rule. `format` is ignored for this variant (see
    /// [`ConditionalFormattingCondition::ColorScale`]'s doc comment) — always
    /// `CellFormat::default()`.
    pub fn color_scale(range: impl Into<String>, stops: Vec<ColorScaleStop>) -> Self {
        Self {
            range: range.into(),
            condition: ConditionalFormattingCondition::ColorScale(stops),
            format: CellFormat::default(),
        }
    }

    /// Creates a data bar rule. `format` is ignored, same as `color_scale`.
    pub fn data_bar(
        range: impl Into<String>,
        min: CfvoPosition,
        max: CfvoPosition,
        color: impl Into<String>,
    ) -> Self {
        Self {
            range: range.into(),
            condition: ConditionalFormattingCondition::DataBar {
                min,
                max,
                color: color.into(),
            },
            format: CellFormat::default(),
        }
    }

    /// Creates a 3-icon-set rule with Excel's own default equal-thirds percent thresholds. `format`
    /// is ignored, same as `color_scale`.
    pub fn icon_set(range: impl Into<String>, icon_set: IconSetType) -> Self {
        Self {
            range: range.into(),
            condition: ConditionalFormattingCondition::IconSet(icon_set),
            format: CellFormat::default(),
        }
    }

    /// Creates a `top10` rule (top `rank` items/percent).
    pub fn top10(range: impl Into<String>, rank: u32, percent: bool, format: CellFormat) -> Self {
        Self {
            range: range.into(),
            condition: ConditionalFormattingCondition::Top10 {
                rank,
                percent,
                bottom: false,
            },
            format,
        }
    }

    /// Sets `top10`'s `bottom` flag (highlight the bottom `rank` instead) and returns the rule for
    /// chaining. A no-op for any other condition.
    pub fn with_bottom(mut self, bottom: bool) -> Self {
        if let ConditionalFormattingCondition::Top10 {
            bottom: existing, ..
        } = &mut self.condition
        {
            *existing = bottom;
        }
        self
    }

    /// Creates an `aboveAverage` rule.
    pub fn above_average(range: impl Into<String>, above: bool, format: CellFormat) -> Self {
        Self {
            range: range.into(),
            condition: ConditionalFormattingCondition::AboveAverage {
                above,
                equal_average: false,
            },
            format,
        }
    }

    /// Creates a `duplicateValues` rule.
    pub fn duplicate_values(range: impl Into<String>, format: CellFormat) -> Self {
        Self {
            range: range.into(),
            condition: ConditionalFormattingCondition::DuplicateValues,
            format,
        }
    }

    /// Creates a `uniqueValues` rule.
    pub fn unique_values(range: impl Into<String>, format: CellFormat) -> Self {
        Self {
            range: range.into(),
            condition: ConditionalFormattingCondition::UniqueValues,
            format,
        }
    }

    /// Creates a text-comparison rule (`containsText`/`notContains`/ `beginsWith`/`endsWith`).
    pub fn contains_text(
        range: impl Into<String>,
        operator: TextComparisonOperator,
        text: impl Into<String>,
        format: CellFormat,
    ) -> Self {
        Self {
            range: range.into(),
            condition: ConditionalFormattingCondition::ContainsText {
                operator,
                text: text.into(),
            },
            format,
        }
    }
}

/// An input or error message attached to a [`DataValidationRule`] (`promptTitle`/`prompt` or
/// `errorTitle`/`error` on `CT_DataValidation`).
#[derive(Debug, Clone, PartialEq)]
pub struct Message {
    /// The message's title (shown in bold in Excel's popup/tooltip).
    pub title: Option<String>,
    /// The message's body text.
    pub text: String,
}

impl Message {
    /// Creates a message with just body text, no title.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            title: None,
            text: text.into(),
        }
    }

    /// Sets a title and returns the message for chaining.
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }
}

/// A data validation rule (`<dataValidation>`, `CT_DataValidation`) applied over a cell range
/// (`sqref`).
///
/// Only three of `ST_DataValidationType`'s eight values are modeled — see [`DataValidationKind`];
/// `date`/`time`/`textLength`/`custom` are not. `showDropDown`/`imeMode` are not modeled either
/// (the former is a rarely-touched, confusingly-inverted flag most libraries leave alone; the
/// latter is IME-input-method behavior, irrelevant outside East Asian input).
#[derive(Debug, Clone, PartialEq)]
pub struct DataValidationRule {
    /// The cell range this rule applies to (`sqref`).
    pub range: String,
    /// The validation performed.
    pub kind: DataValidationKind,
    /// Whether a blank cell is considered valid (`allowBlank`).
    pub allow_blank: bool,
    /// An input message shown when the cell is selected (`showInputMessage` is written
    /// automatically when this is `Some`).
    pub input_message: Option<Message>,
    /// An error message shown when an invalid value is entered (`showErrorMessage` is written
    /// automatically when this is `Some`). Always written with `errorStyle="stop"` (blocking) — the
    /// `warning`/ `information` (non-blocking) styles are not modeled.
    pub error_message: Option<Message>,
}

/// The validation performed by a [`DataValidationRule`].
#[derive(Debug, Clone, PartialEq)]
pub enum DataValidationKind {
    /// `type="list"`: the cell's value must match one entry from a fixed list — Excel shows a
    /// dropdown. `source` is written verbatim as `formula1`, so it can be either a literal
    /// comma-separated list wrapped in quotes (e.g. `"\"Yes,No,Maybe\""`) or a reference to a range
    /// holding the valid values (e.g. `"$D$1:$D$3"`).
    List { source: String },
    /// `type="whole"`: the cell's value must be a whole number satisfying `operator` against
    /// `formula1` (and `formula2`, for `Between`/ `NotBetween`).
    WholeNumber {
        operator: ComparisonOperator,
        formula1: String,
        formula2: Option<String>,
    },
    /// `type="decimal"`: like `WholeNumber`, but the value may have a fractional part.
    Decimal {
        operator: ComparisonOperator,
        formula1: String,
        formula2: Option<String>,
    },
    /// `type="date"`: the cell's value must be a date satisfying `operator` against
    /// `formula1`/`formula2`. `formula1`/`formula2` are written verbatim, so the caller is
    /// responsible for passing an Excel date serial number (as text, e.g. `"45000"`) or a
    /// date-returning formula — same "storage, not a conversion helper" posture as everywhere else
    /// formula text is stored in this crate; see [`crate::ExcelDateTime`] plus
    /// `writer.rs::excel_serial_date` if a caller needs to compute one.
    Date {
        operator: ComparisonOperator,
        formula1: String,
        formula2: Option<String>,
    },
    /// `type="time"`: like `Date`, but for a time-of-day value (a fractional day, e.g. `"0.5"` for
    /// noon).
    Time {
        operator: ComparisonOperator,
        formula1: String,
        formula2: Option<String>,
    },
    /// `type="textLength"`: the cell's text length must satisfy `operator` against
    /// `formula1`/`formula2`.
    TextLength {
        operator: ComparisonOperator,
        formula1: String,
        formula2: Option<String>,
    },
    /// `type="custom"`: an arbitrary formula, evaluated per cell, the value is valid when it
    /// evaluates to `TRUE` — no `operator`, unlike every other variant.
    Custom { formula: String },
}

impl DataValidationRule {
    /// Creates a `list` validation rule with no messages, blanks allowed.
    pub fn list(range: impl Into<String>, source: impl Into<String>) -> Self {
        Self {
            range: range.into(),
            kind: DataValidationKind::List {
                source: source.into(),
            },
            allow_blank: true,
            input_message: None,
            error_message: None,
        }
    }

    /// Creates a `whole` validation rule with no messages, blanks allowed.
    pub fn whole_number(
        range: impl Into<String>,
        operator: ComparisonOperator,
        formula1: impl Into<String>,
    ) -> Self {
        Self {
            range: range.into(),
            kind: DataValidationKind::WholeNumber {
                operator,
                formula1: formula1.into(),
                formula2: None,
            },
            allow_blank: true,
            input_message: None,
            error_message: None,
        }
    }

    /// Creates a `decimal` validation rule with no messages, blanks allowed.
    pub fn decimal(
        range: impl Into<String>,
        operator: ComparisonOperator,
        formula1: impl Into<String>,
    ) -> Self {
        Self {
            range: range.into(),
            kind: DataValidationKind::Decimal {
                operator,
                formula1: formula1.into(),
                formula2: None,
            },
            allow_blank: true,
            input_message: None,
            error_message: None,
        }
    }

    /// Creates a `date` validation rule with no messages, blanks allowed.
    pub fn date(
        range: impl Into<String>,
        operator: ComparisonOperator,
        formula1: impl Into<String>,
    ) -> Self {
        Self {
            range: range.into(),
            kind: DataValidationKind::Date {
                operator,
                formula1: formula1.into(),
                formula2: None,
            },
            allow_blank: true,
            input_message: None,
            error_message: None,
        }
    }

    /// Creates a `time` validation rule with no messages, blanks allowed.
    pub fn time(
        range: impl Into<String>,
        operator: ComparisonOperator,
        formula1: impl Into<String>,
    ) -> Self {
        Self {
            range: range.into(),
            kind: DataValidationKind::Time {
                operator,
                formula1: formula1.into(),
                formula2: None,
            },
            allow_blank: true,
            input_message: None,
            error_message: None,
        }
    }

    /// Creates a `textLength` validation rule with no messages, blanks allowed.
    pub fn text_length(
        range: impl Into<String>,
        operator: ComparisonOperator,
        formula1: impl Into<String>,
    ) -> Self {
        Self {
            range: range.into(),
            kind: DataValidationKind::TextLength {
                operator,
                formula1: formula1.into(),
                formula2: None,
            },
            allow_blank: true,
            input_message: None,
            error_message: None,
        }
    }

    /// Creates a `custom` validation rule with no messages, blanks allowed.
    pub fn custom(range: impl Into<String>, formula: impl Into<String>) -> Self {
        Self {
            range: range.into(),
            kind: DataValidationKind::Custom {
                formula: formula.into(),
            },
            allow_blank: true,
            input_message: None,
            error_message: None,
        }
    }

    /// Sets the second comparison formula (for `Between`/`NotBetween`) on a
    /// `WholeNumber`/`Decimal`/`Date`/`Time`/`TextLength` rule and returns it for chaining. A no-op
    /// for a `List`/`Custom` rule.
    pub fn with_second_formula(mut self, formula2: impl Into<String>) -> Self {
        match &mut self.kind {
            DataValidationKind::WholeNumber {
                formula2: existing, ..
            }
            | DataValidationKind::Decimal {
                formula2: existing, ..
            }
            | DataValidationKind::Date {
                formula2: existing, ..
            }
            | DataValidationKind::Time {
                formula2: existing, ..
            }
            | DataValidationKind::TextLength {
                formula2: existing, ..
            } => {
                *existing = Some(formula2.into());
            }
            DataValidationKind::List { .. } | DataValidationKind::Custom { .. } => {}
        }
        self
    }

    /// Sets whether a blank cell is considered valid and returns the rule for chaining.
    pub fn with_allow_blank(mut self, allow_blank: bool) -> Self {
        self.allow_blank = allow_blank;
        self
    }

    /// Sets the input message and returns the rule for chaining.
    pub fn with_input_message(mut self, message: Message) -> Self {
        self.input_message = Some(message);
        self
    }

    /// Sets the error message and returns the rule for chaining.
    pub fn with_error_message(mut self, message: Message) -> Self {
        self.error_message = Some(message);
        self
    }
}

/// A named range/formula/constant (`<definedName>`, `CT_DefinedName`) — unlike
/// [`ConditionalFormattingRule`]/[`DataValidationRule`], this is a workbook-level construct, not
/// attached to any particular [`Sheet`], even when [`local_sheet_id`](DefinedName::local_sheet_id)
/// scopes it to one.
///
/// Only `name`/`refers_to`/`local_sheet_id`/`hidden`/`comment` are modeled. `CT_DefinedName`'s
/// remaining attributes (`function`/
/// `vbProcedure`/`xlm`/`functionGroupId`/`shortcutKey`/`publishToServer`/
/// `workbookParameter`/`customMenu`/`description`/`help`/`statusBar`) are all macro/add-in/UI-text
/// concerns with no real demand seen yet, same scope-reduction posture as elsewhere in this crate.
/// SpreadsheetML's reserved `_xlnm.*` built-in names (print area, print titles, filter database..)
/// aren't given any special handling — a caller can write one like any other name, but nothing here
/// validates or treats it specially.
#[derive(Debug, Clone, PartialEq)]
pub struct DefinedName {
    /// The name shown in Excel's Name Manager (`name`, required).
    pub name: String,
    /// The formula, range reference, or constant this name refers to (e.g. `"Feuil1!$A$1:$B$10"`),
    /// written as the element's own text content — unlike a conditional formatting/data validation
    /// rule's formula, `CT_DefinedName` has simple content (`ST_Formula`), not a dedicated child
    /// element.
    pub refers_to: String,
    /// If `Some`, scopes this name to a single sheet rather than the whole workbook
    /// (`localSheetId`, a 0-based index into [`Workbook.sheets`](Workbook::sheets) in declaration
    /// order) — a sheet-scoped name can be duplicated across different sheets' scopes, unlike a
    /// workbook-scoped one. `None` means workbook-wide scope, the common case.
    pub local_sheet_id: Option<usize>,
    /// Whether this name is hidden in Excel's Name Manager UI (`hidden`).
    pub hidden: bool,
    /// An optional comment shown for this name (`comment`).
    pub comment: Option<String>,
}

impl DefinedName {
    /// Creates a workbook-scoped defined name, not hidden, no comment.
    pub fn new(name: impl Into<String>, refers_to: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            refers_to: refers_to.into(),
            local_sheet_id: None,
            hidden: false,
            comment: None,
        }
    }

    /// Scopes this name to a single sheet (by its 0-based position in
    /// [`Workbook.sheets`](Workbook::sheets)) and returns it for chaining.
    pub fn with_local_sheet_id(mut self, local_sheet_id: usize) -> Self {
        self.local_sheet_id = Some(local_sheet_id);
        self
    }

    /// Sets whether this name is hidden in Excel's Name Manager and returns it for chaining.
    pub fn with_hidden(mut self, hidden: bool) -> Self {
        self.hidden = hidden;
        self
    }

    /// Sets this name's comment and returns it for chaining.
    pub fn with_comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }
}

/// A sheet's tab visibility (`<sheet state=".">`, `ST_SheetState`) — replacing the plain `bool`
/// used since. `VeryHidden` (unlike `Hidden`) cannot be un-hidden from Excel's own "Unhide." dialog
/// — only from the VBA object model or by editing the file directly — real-world usage is normally
/// to hide implementation-detail sheets (lookup tables, staging data) from end users while still
/// letting formulas reference them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SheetVisibility {
    #[default]
    Visible,
    Hidden,
    VeryHidden,
}

/// A single column's width/visibility/outline setting (`<col>`, `CT_Col`) — extended for
/// `collapsed`.
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnSetting {
    /// The 0-based column index this setting applies to (e.g. `0` for column A) — written as `min
    /// == max == column + 1` (see `Sheet.column_settings`'s doc comment for why this crate doesn't
    /// bother collapsing adjacent columns into a single ranged `<col>`).
    pub column: usize,
    /// The column's width, in Excel's own character-width units. `None` leaves the column at
    /// Excel's default width.
    pub width: Option<f64>,
    /// Whether this column is hidden.
    pub hidden: bool,
    /// This column's outline (grouping) level (0-7).
    pub outline_level: u8,
    /// Whether this column's outline group is shown collapsed (the "-" summary-only state of the
    /// little outline button). Distinct from `outline_level` itself (which columns belong to the
    /// group) — this is only the group's current expanded/collapsed *display* state.
    pub collapsed: bool,
    /// This column's default cell format (`<col style="n">`, an index into `xl/styles.xml`'s
    /// `cellXfs`). Applied by real Excel to any cell in this column that doesn't carry its own
    /// explicit `<c s="..">` — e.g. a brand-new cell typed into an empty row of this column picks
    /// up this format automatically. Distinct from [`Cell::format`]: a cell's own format always
    /// wins over its column's default when both are set (same precedence as real Excel's own
    /// column-formatting feature); this crate does not enforce or resolve that precedence itself,
    /// it only stores and writes each side's format independently, same "storage, not resolution"
    /// posture as elsewhere in this crate. Deduplicated into shared `cellXfs` entries by the writer
    /// exactly like `Cell::format` — see `writer.rs::collect_cell_formats`.
    pub style: Option<CellFormat>,
}

impl ColumnSetting {
    /// Creates a column setting with no width/hidden/outline/style override yet (only useful as a
    /// starting point for the `with_*` builders).
    pub fn new(column: usize) -> Self {
        Self {
            column,
            width: None,
            hidden: false,
            outline_level: 0,
            collapsed: false,
            style: None,
        }
    }

    /// Sets the column's width and returns it for chaining.
    pub fn with_width(mut self, width: f64) -> Self {
        self.width = Some(width);
        self
    }

    /// Sets the column's default cell format and returns it for chaining.
    pub fn with_style(mut self, style: CellFormat) -> Self {
        self.style = Some(style);
        self
    }

    /// Sets whether the column is hidden and returns it for chaining.
    pub fn with_hidden(mut self, hidden: bool) -> Self {
        self.hidden = hidden;
        self
    }

    /// Sets whether this column's outline group is shown collapsed and returns it for chaining.
    pub fn with_collapsed(mut self, collapsed: bool) -> Self {
        self.collapsed = collapsed;
        self
    }

    /// Sets the column's outline (grouping) level and returns it for chaining.
    pub fn with_outline_level(mut self, level: u8) -> Self {
        self.outline_level = level;
        self
    }
}

/// Frozen panes (`<pane state="frozen">`, `CT_Pane`). See `Sheet.freeze_panes`'s doc comment for
/// why only "frozen" (not "split") panes are modeled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FreezePane {
    /// The number of columns frozen at the left (`0` = no column freeze).
    pub frozen_columns: usize,
    /// The number of rows frozen at the top (`0` = no row freeze).
    pub frozen_rows: usize,
}

impl FreezePane {
    /// Creates a freeze-panes setting.
    pub fn new(frozen_columns: usize, frozen_rows: usize) -> Self {
        Self {
            frozen_columns,
            frozen_rows,
        }
    }
}

/// A sheet's page orientation (`ST_Orientation`) — only `portrait`/ `landscape` are modeled,
/// `default` (a third schema value, treated by Excel as "portrait") is not, same posture as
/// `word-ooxml`'s own `PageOrientation`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PageOrientation {
    Portrait,
    Landscape,
}

/// A sheet's print/page-setup settings. `PrintSettings::default()` (everything `None`) writes no
/// print-related XML at all.
///
/// `print_area`/`repeat_rows`/`repeat_columns` are, despite looking like plain worksheet settings,
/// actually implemented by real Excel as reserved sheet-scoped defined names (`_xlnm.Print_Area`/
/// `_xlnm.Print_Titles`, confirmed via ECMA-376 §18.2.6's "Print_Area"/"Print_Titles" built-in name
/// table) rather than a `<pageSetup>` attribute — this crate's writer synthesizes those
/// `DefinedName` entries automatically from each sheet's `Sheet.print_settings` when writing
/// `xl/workbook.xml`'s `<definedNames>` (see `writer.rs::synthesized_print_defined_names`), the
/// caller never constructs them directly.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct PrintSettings {
    /// The print area (e.g. `"$A$1:$F$30"`) — implemented via `_xlnm.Print_Area`.
    pub print_area: Option<String>,
    /// Rows to repeat on every printed page (e.g. `"$1:$2"`) — implemented via
    /// `_xlnm.Print_Titles`.
    pub repeat_rows: Option<String>,
    /// Columns to repeat on every printed page (e.g. `"$A:$B"`) — implemented via
    /// `_xlnm.Print_Titles` (combined with `repeat_rows` into a single name's `refers_to` when both
    /// are set, exactly like real Excel's own "Rows to repeat at top" + "Columns to repeat at left"
    /// combined into one `Print_Titles` name).
    pub repeat_columns: Option<String>,
    /// Scales the printout to fit within this many pages wide. Setting either this or
    /// `fit_to_height` switches on Excel's "Fit to" print scaling mode (`<sheetPr><pageSetUpPr
    /// fitToPage="1"/></sheetPr>`); leaving the other `None` means "as many pages as needed" in
    /// that dimension, matching Excel's own "Fit to: N page(s) wide by (blank) tall" UI behavior
    /// (written as `fitToWidth="0"`/`fitToHeight="0"`, `CT_PageSetup`'s own convention for
    /// "unconstrained").
    pub fit_to_width: Option<u32>,
    /// Scales the printout to fit within this many pages tall.
    pub fit_to_height: Option<u32>,
    /// Scales the printout by this percentage (`<pageSetup scale="..">`, e.g. `90` for 90%).
    /// Distinct from `fit_to_width`/`fit_to_height`: real Excel's "Page Setup" dialog offers either
    /// "Adjust to: N%" (`scale`) or "Fit to: W x H page(s)" (`fit_to_width`/`fit_to_height`) as two
    /// mutually exclusive radio-button modes (`<sheetPr><pageSetUpPr fitToPage>` selects which of
    /// the two `<pageSetup>` honors) — setting both here is the caller's own responsibility to
    /// avoid, not validated.
    pub scale: Option<u32>,
    /// Page orientation. `None` uses Excel's own default (portrait).
    pub orientation: Option<PageOrientation>,
    /// The page header text (`<oddHeader>`), written verbatim — Excel's own `&L`/`&C`/`&R` section
    /// codes and `&P`/`&N`/`&D`/. field codes are the caller's responsibility to include if wanted,
    /// same "storage, not a template engine" posture as a formula's text.
    pub header: Option<String>,
    /// The page footer text (`<oddFooter>`), written verbatim.
    pub footer: Option<String>,
    /// A different header on the first printed page (`<firstHeader>`), written verbatim. Setting
    /// this (or [`footer_first`](PrintSettings::footer_first)) switches on `<headerFooter
    /// differentFirst="1">`.
    pub header_first: Option<String>,
    /// A different footer on the first printed page (`<firstFooter>`).
    pub footer_first: Option<String>,
    /// A different header on even printed pages (`<evenHeader>`). Setting this (or
    /// [`footer_even`](PrintSettings::footer_even)) switches on `<headerFooter
    /// differentOddEven="1">`; the existing
    /// [`header`](PrintSettings::header)/[`footer`](PrintSettings::footer) fields become the
    /// *odd*-page header/footer once this is set, same as real Excel's own
    /// `<oddHeader>`/`<oddFooter>` meaning "odd, or every page if `differentOddEven` isn't set".
    pub header_even: Option<String>,
    /// A different footer on even printed pages (`<evenFooter>`).
    pub footer_even: Option<String>,
}

impl PrintSettings {
    /// Creates print settings with every field unset (equivalent to `PrintSettings::default()`,
    /// only useful as a starting point for the `with_*` builders).
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the print area and returns the settings for chaining.
    pub fn with_print_area(mut self, area: impl Into<String>) -> Self {
        self.print_area = Some(area.into());
        self
    }

    /// Sets the rows to repeat on every printed page and returns the settings for chaining.
    pub fn with_repeat_rows(mut self, rows: impl Into<String>) -> Self {
        self.repeat_rows = Some(rows.into());
        self
    }

    /// Sets the columns to repeat on every printed page and returns the settings for chaining.
    pub fn with_repeat_columns(mut self, columns: impl Into<String>) -> Self {
        self.repeat_columns = Some(columns.into());
        self
    }

    /// Sets the fit-to-width page count and returns the settings for chaining.
    pub fn with_fit_to_width(mut self, pages: u32) -> Self {
        self.fit_to_width = Some(pages);
        self
    }

    /// Sets the fit-to-height page count and returns the settings for chaining.
    pub fn with_fit_to_height(mut self, pages: u32) -> Self {
        self.fit_to_height = Some(pages);
        self
    }

    /// Sets the print scale percentage and returns the settings for chaining.
    pub fn with_scale(mut self, percent: u32) -> Self {
        self.scale = Some(percent);
        self
    }

    /// Sets the page orientation and returns the settings for chaining.
    pub fn with_orientation(mut self, orientation: PageOrientation) -> Self {
        self.orientation = Some(orientation);
        self
    }

    /// Sets the page header text and returns the settings for chaining.
    pub fn with_header(mut self, header: impl Into<String>) -> Self {
        self.header = Some(header.into());
        self
    }

    /// Sets the page footer text and returns the settings for chaining.
    pub fn with_footer(mut self, footer: impl Into<String>) -> Self {
        self.footer = Some(footer.into());
        self
    }

    /// Sets the first page's header text and returns the settings for chaining.
    pub fn with_header_first(mut self, header: impl Into<String>) -> Self {
        self.header_first = Some(header.into());
        self
    }

    /// Sets the first page's footer text and returns the settings for chaining.
    pub fn with_footer_first(mut self, footer: impl Into<String>) -> Self {
        self.footer_first = Some(footer.into());
        self
    }

    /// Sets the even pages' header text and returns the settings for chaining.
    pub fn with_header_even(mut self, header: impl Into<String>) -> Self {
        self.header_even = Some(header.into());
        self
    }

    /// Sets the even pages' footer text and returns the settings for chaining.
    pub fn with_footer_even(mut self, footer: impl Into<String>) -> Self {
        self.footer_even = Some(footer.into());
        self
    }
}

/// A sheet's protection settings (`<sheetProtection>`, `CT_SheetProtection`). Only the legacy
/// 16-bit password hash (`password="XXXX"`, still fully understood by every version of Excel even
/// though the UI has written the newer SHA-512 `hashValue`/`saltValue`/`spinCount` form since Excel
/// 2013 — see `writer.rs::legacy_password_hash`'s doc comment) is modeled. Every other
/// `CT_SheetProtection` flag (`formatCells`/`insertRows`/`sort`/ `autoFilter`/`objects`/..) is left
/// at Excel's own schema default — this crate only ever writes `sheet="1"` and, if set, `password`,
/// matching what checking Excel's own "Protect Sheet" dialog with no extra options touched
/// produces.
#[derive(Debug, Clone, PartialEq)]
pub struct SheetProtection {
    /// The password, in plain text — hashed into the legacy 16-bit form on write; never stored or
    /// written in plain text anywhere in the output file. `None` protects the sheet with no
    /// password at all (Excel's "Protect Sheet" with a blank password field — still blocks
    /// accidental edits through the UI, but anyone can immediately remove the protection since
    /// there's nothing to check a password against).
    pub password: Option<String>,
}

impl SheetProtection {
    /// Protects the sheet with no password.
    pub fn locked() -> Self {
        Self { password: None }
    }

    /// Protects the sheet with a password.
    pub fn with_password(password: impl Into<String>) -> Self {
        Self {
            password: Some(password.into()),
        }
    }
}

/// Workbook *structure* protection (`<workbookProtection>`, `CT_WorkbookProtection`). Locks whether
/// sheets can be added/renamed/hidden/reordered/deleted (`lockStructure`) and/or whether the
/// workbook's window can be moved/resized/closed (`lockWindows`) — distinct from
/// [`SheetProtection`], which locks cell editing within one sheet. Uses the same legacy 16-bit
/// password hash as `SheetProtection` (see `writer.rs::legacy_password_hash`'s doc comment for the
/// algorithm and its caveats) — implemented but not yet verified against a real Excel installation.
#[derive(Debug, Clone, PartialEq)]
pub struct WorkbookProtection {
    /// The password, in plain text — hashed on write, never recoverable on read (same one-way
    /// posture as `SheetProtection::password`).
    pub password: Option<String>,
    /// Locks the workbook's structure (adding/renaming/hiding/reordering/ deleting sheets).
    pub lock_structure: bool,
    /// Locks the workbook's window (moving/resizing/closing).
    pub lock_windows: bool,
}

impl WorkbookProtection {
    /// Locks the workbook's structure, no password, windows not locked.
    pub fn locked() -> Self {
        Self {
            password: None,
            lock_structure: true,
            lock_windows: false,
        }
    }

    /// Sets a password and returns the protection for chaining.
    pub fn with_password(mut self, password: impl Into<String>) -> Self {
        self.password = Some(password.into());
        self
    }

    /// Sets whether the workbook's window is locked and returns the protection for chaining.
    pub fn with_lock_windows(mut self, lock_windows: bool) -> Self {
        self.lock_windows = lock_windows;
        self
    }
}

/// Write-protection / "read-only recommended" (`<fileSharing>`, `CT_FileSharing`) — point 54, see
/// [`Workbook::write_protection`]'s doc comment for how this differs from [`WorkbookProtection`].
/// Confirmed against `sml.xsd`: `readOnlyRecommended` defaults to `false`; `userName` is a plain
/// display string (shown in Excel's own "reserved by.." prompt); `reservationPassword` uses the
/// same legacy 16-bit hash as `WorkbookProtection`/`SheetProtection` (see
/// `writer.rs::legacy_password_hash`'s doc comment) — the newer SHA-512
/// `algorithmName`/`hashValue`/`saltValue`/`spinCount` form is not modeled, same "one well-defined
/// mechanism" posture as `ProtectedRange`.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct WriteProtection {
    /// Recommends opening the file as read-only (`readOnlyRecommended`) — the checkbox behind
    /// Excel's Save As > Tools > General Options > "Read-only recommended".
    pub read_only_recommended: bool,
    /// The name shown in Excel's write-reservation prompt (`userName`), e.g. the name of the user
    /// who last saved with a reservation password set.
    pub user_name: Option<String>,
    /// The write-reservation password, in plain text — hashed into the legacy 16-bit form on write,
    /// never recoverable on read (same one-way posture as `WorkbookProtection::password`). Excel
    /// prompts for this password (or "Read Only") when opening the file.
    pub password: Option<String>,
}

impl WriteProtection {
    /// Recommends opening the file as read-only, no password/user name set.
    pub fn recommended() -> Self {
        Self {
            read_only_recommended: true,
            user_name: None,
            password: None,
        }
    }

    /// Sets the write-reservation password and returns it for chaining.
    pub fn with_password(mut self, password: impl Into<String>) -> Self {
        self.password = Some(password.into());
        self
    }

    /// Sets the user name shown in the write-reservation prompt and returns it for chaining.
    pub fn with_user_name(mut self, user_name: impl Into<String>) -> Self {
        self.user_name = Some(user_name.into());
        self
    }
}

/// One named, independently-passworded protected range (`<protectedRange>`, `CT_ProtectedRange`) —
/// point 51, see [`Sheet::protected_ranges`]'s doc comment for how this differs from
/// [`SheetProtection`]. Confirmed against `sml.xsd`: `name`/`sqref` are the only required
/// attributes; `password` uses the same legacy 16-bit hash as
/// `SheetProtection`/`WorkbookProtection` (see `writer.rs::legacy_password_hash`'s doc comment) —
/// the newer SHA-512 `algorithmName`/`hashValue`/`saltValue`/`spinCount` form and the optional
/// `securityDescriptor` child/attribute (a Windows ACL-based alternative to a password) are not
/// modeled, same "one well-defined mechanism, not every historical Excel option" posture as
/// `SheetProtection`.
#[derive(Debug, Clone, PartialEq)]
pub struct ProtectedRange {
    /// This range's name, shown in Excel's "Allow Users to Edit Ranges" dialog (must be unique
    /// within the sheet, not validated here).
    pub name: String,
    /// The range this entry covers (`sqref`, e.g. `"B2:D10"`) — like [`IgnoredError::range`],
    /// several disjoint cells can be packed into one `sqref` (space-separated) if the caller wants
    /// a single named range to cover them.
    pub range: String,
    /// The password unlocking this range while the sheet is otherwise protected, in plain text —
    /// hashed into the legacy 16-bit form on write, never stored or written in plain text (same
    /// one-way posture as `SheetProtection::password`). `None` leaves the range editable by anyone
    /// once the sheet itself is protected (no password prompt), same as
    /// `SheetProtection::password`'s `None` case.
    pub password: Option<String>,
}

impl ProtectedRange {
    /// Creates a named protected range with no password.
    pub fn new(name: impl Into<String>, range: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            range: range.into(),
            password: None,
        }
    }

    /// Sets a password and returns the range for chaining.
    pub fn with_password(mut self, password: impl Into<String>) -> Self {
        self.password = Some(password.into());
        self
    }
}

/// A per-cell hyperlink (`<hyperlink>`, `CT_Hyperlink`).
#[derive(Debug, Clone, PartialEq)]
pub struct CellHyperlink {
    /// The cell this hyperlink is attached to (e.g. `"A1"`).
    pub cell: String,
    /// The link's target.
    pub target: HyperlinkTarget,
    /// An optional tooltip shown on hover (`tooltip`).
    pub tooltip: Option<String>,
}

/// A [`CellHyperlink`]'s target.
#[derive(Debug, Clone, PartialEq)]
pub enum HyperlinkTarget {
    /// An external URL (`r:id`, resolved through this worksheet's own `.rels` part,
    /// `TargetMode="External"` — same shape as `word-ooxml`'s `Hyperlink::External`).
    External(String),
    /// A location within the same workbook (`location`, e.g. `"Feuil2!A1"` or a defined name) — no
    /// relationship needed, same shape as `word-ooxml`'s `Hyperlink::Internal`.
    Internal(String),
}

impl CellHyperlink {
    /// Creates an external hyperlink on the given cell.
    pub fn external(cell: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            cell: cell.into(),
            target: HyperlinkTarget::External(url.into()),
            tooltip: None,
        }
    }

    /// Creates an internal hyperlink (to a cell/defined name elsewhere in this workbook) on the
    /// given cell.
    pub fn internal(cell: impl Into<String>, location: impl Into<String>) -> Self {
        Self {
            cell: cell.into(),
            target: HyperlinkTarget::Internal(location.into()),
            tooltip: None,
        }
    }

    /// Sets a tooltip and returns the hyperlink for chaining.
    pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
        self.tooltip = Some(tooltip.into());
        self
    }
}

/// A comment attached to a cell (legacy `xl/comments*.xml` + VML drawing, `CT_Comment`). Only
/// plain-text comments with a fixed author are modeled — `CT_Comment`'s rich-text (`CT_RElt` runs)
/// body and threaded-comment reply chains (`CT_ThreadedComment`, the modern Excel 365 "@mention"
/// comment form) are out of scope.
#[derive(Debug, Clone, PartialEq)]
pub struct CellComment {
    /// The cell this comment is attached to (e.g. `"B2"`).
    pub cell: String,
    /// The comment's author (shown in the comment box's first bold line by Excel's own convention,
    /// and stored as a separate `<author>` entry — not otherwise validated).
    pub author: String,
    /// The comment's body text — when [`rich_text`](CellComment::rich_text) is `Some`, this is
    /// simply the plain-text concatenation of every run's own text (kept in sync automatically by
    /// [`CellComment::with_rich_text`]), not a separate independent value.
    pub text: String,
    /// The comment's body as per-run formatted text (`<text><r>..</r></text>`, reusing
    /// [`RichTextRun`] — the same per-run bold/italic/color/size/ name/underline/strike model a
    /// rich-text cell's shared-string runs already use). `None` writes the plain single-run
    /// `<text><r><t>..</t></r></text>` form instead, using `text` verbatim.
    pub rich_text: Option<Vec<RichTextRun>>,
}

impl CellComment {
    /// Creates a plain-text comment.
    pub fn new(
        cell: impl Into<String>,
        author: impl Into<String>,
        text: impl Into<String>,
    ) -> Self {
        Self {
            cell: cell.into(),
            author: author.into(),
            text: text.into(),
            rich_text: None,
        }
    }

    /// Sets this comment's body as per-run formatted text and returns it for chaining. Also
    /// resolves `text` (the plain-text fallback) to the concatenation of every run's own text, so
    /// both fields stay consistent.
    pub fn with_rich_text(mut self, runs: Vec<RichTextRun>) -> Self {
        self.text = runs.iter().map(|run| run.text.as_str()).collect();
        self.rich_text = Some(runs);
        self
    }
}

/// A custom table style definition (`<tableStyle>`, `CT_TableStyle`), declared workbook-wide in
/// `xl/styles.xml`'s `<tableStyles>` (`CT_TableStyles`) and referenced by name from an
/// [`ExcelTable`]'s own [`table_style_name`](ExcelTable::table_style_name). Confirmed against
/// `sml.xsd`: `CT_Stylesheet`'s own sequence puts `tableStyles` right after `dxfs`, before `colors`
/// (not written by this crate). This crate only ever writes `pivot="0"` (this style is for tables,
/// not pivot tables) and no `count` attribute (`CT_TableStyle`'s `count` is informational, Excel
/// recomputes it).
#[derive(Debug, Clone, PartialEq)]
pub struct TableStyle {
    /// This style's name, referenced by [`ExcelTable::table_style_name`] (must be unique within the
    /// workbook, not validated here — a name colliding with one of Excel's own dozens of built-in
    /// style names, e.g. `"TableStyleMedium2"`, silently shadows the built-in one for this
    /// workbook).
    pub name: String,
    /// The banding/region formats making up this style, in no particular required order (real Excel
    /// itself doesn't enforce one either).
    pub elements: Vec<TableStyleElement>,
}

impl TableStyle {
    /// Creates a named table style with no elements yet.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            elements: Vec::new(),
        }
    }

    /// Appends a formatted element and returns the style for chaining.
    pub fn with_element(mut self, element: TableStyleElement) -> Self {
        self.elements.push(element);
        self
    }
}

/// A named cell style (`<cellStyle>`/its paired `<cellStyleXfs>` `<xf>` entry,
/// `CT_CellStyle`/`CT_Xf`), declared workbook-wide in `xl/styles.xml` and referenced from any
/// [`CellFormat`] via [`CellFormat::named_style`]. This is Excel's "Cell Styles" gallery: built-in
/// entries like `Good`/`Bad`/ `Neutral`/`Heading 1`-`4`/`Input`/`Output`/`Calculation`/`Currency`/
/// `Percent`/`Comma`, or a caller's own custom-named style. Confirmed against `sml.xsd`:
/// `CT_CellStyle`'s only required attribute is `xfId` (this crate assigns it automatically, from
/// this entry's position in [`Workbook::named_cell_styles`], mirroring how a `dxfId`/table-style
/// `dxfId` is resolved rather than caller-supplied); `name`/`builtinId` are both optional but a
/// real style always sets `name` at least (an unnamed entry would show as blank in Excel's gallery,
/// so `name` is required here, not `Option`).
#[derive(Debug, Clone, PartialEq)]
pub struct NamedCellStyle {
    /// This style's name, shown in Excel's Cell Styles gallery and referenced by
    /// [`CellFormat::named_style`] (must be unique within the workbook, not validated here).
    pub name: String,
    /// The formatting this style applies (font/fill/border/number format/ alignment — the same
    /// [`CellFormat`] shape a regular cell format uses, written into its own dedicated
    /// `cellStyleXfs` entry rather than the shared `cellXfs` collection, mirroring how a `dxf`'s
    /// `CellFormat` is a separate index space too, see `writer.rs::collect_dxfs`'s doc comment).
    pub format: CellFormat,
    /// Identifies this as one of Excel's own built-in styles rather than a caller-defined one
    /// (`builtinId`, e.g. `0` = `"Normal"`, `3` = `"Good"`, `4` = `"Bad"`, `5` = `"Neutral"`,
    /// `7`-`10` = `"Heading 1"`-`"Heading 4"`. — `ST_CellStyleBuiltinId`'s full ~54-value table is
    /// not reproduced/validated here, this crate simply writes whatever `u32` the caller supplies
    /// verbatim). `None` for a purely custom style with no built-in equivalent.
    pub builtin_id: Option<u32>,
}

impl NamedCellStyle {
    /// Creates a named cell style with the given name and format, no built-in id (a purely custom
    /// style).
    pub fn new(name: impl Into<String>, format: CellFormat) -> Self {
        Self {
            name: name.into(),
            format,
            builtin_id: None,
        }
    }

    /// Sets the built-in id and returns the style for chaining.
    pub fn with_builtin_id(mut self, builtin_id: u32) -> Self {
        self.builtin_id = Some(builtin_id);
        self
    }
}

/// One formatted region of a [`TableStyle`] (`<tableStyleElement>`, `CT_TableStyleElement`).
#[derive(Debug, Clone, PartialEq)]
pub struct TableStyleElement {
    /// Which region of the table this element formats.
    pub element_type: TableStyleElementType,
    /// The formatting applied to this region — written as a `<dxf>` entry in `xl/styles.xml`'s
    /// `<dxfs>` (the same shared, deduplicated collection a [`ConditionalFormattingRule`]'s own
    /// `format` uses, see `writer.rs::collect_dxfs`) and referenced here by `dxfId`, exactly like a
    /// conditional formatting rule.
    pub format: CellFormat,
}

impl TableStyleElement {
    /// Creates a table style element.
    pub fn new(element_type: TableStyleElementType, format: CellFormat) -> Self {
        Self {
            element_type,
            format,
        }
    }
}

/// Which region of a table a [`TableStyleElement`] formats (`ST_TableStyleType`) — only the most
/// commonly used values are modeled (whole-table default, header/total rows, and row/column
/// banding); `ST_TableStyleType`'s remaining values (`firstHeaderCell`/
/// `lastHeaderCell`/`firstTotalCell`/`lastTotalCell`/`firstSubtotalColumn`/
/// `secondSubtotalColumn`/`thirdSubtotalColumn`/`firstSubtotalRow`/
/// `secondSubtotalRow`/`thirdSubtotalRow`/`blankRow`/
/// `firstColumnSubheading`/`secondColumnSubheading`/`thirdColumnSubheading`/
/// `firstRowSubheading`/`secondRowSubheading`/`thirdRowSubheading`/
/// `pageFieldLabels`/`pageFieldValues`, confirmed via `sml.xsd`) cover niche PivotTable-report and
/// outline-subtotal layouts out of this crate's current scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TableStyleElementType {
    /// The whole table's default formatting (`"wholeTable"`).
    WholeTable,
    /// The header row (`"headerRow"`).
    HeaderRow,
    /// The totals row (`"totalRow"`).
    TotalRow,
    /// Odd data rows, 1-based from the header (`"firstRowStripe"`).
    FirstRowStripe,
    /// Even data rows (`"secondRowStripe"`).
    SecondRowStripe,
    /// Odd data columns (`"firstColumnStripe"`).
    FirstColumnStripe,
    /// Even data columns (`"secondColumnStripe"`).
    SecondColumnStripe,
    /// The table's first (leftmost) column (`"firstColumn"`).
    FirstColumn,
    /// The table's last (rightmost) column (`"lastColumn"`).
    LastColumn,
}

/// A structured (`ListObject`) table (`<table>`, `CT_Table`) — extended for per-column
/// calculated-column formulas and totals-row functions, and for
/// [`table_style_name`](ExcelTable::table_style_name).
#[derive(Debug, Clone, PartialEq)]
pub struct ExcelTable {
    /// The table's name, shown in Excel's Name Manager/Table Design tab (must be unique within the
    /// workbook, not validated here).
    pub name: String,
    /// The table's full range, header row included (e.g. `"A1:D6"`).
    pub range: String,
    /// The table's columns, in order, matching the header row's actual cell text (not written into
    /// `<sheetData>` by this crate — the caller is responsible for the header row's own cell values
    /// matching each column's name, same "caller keeps the two in sync" posture as
    /// `ConditionalFormattingRule::range` referencing real cells).
    pub columns: Vec<TableColumn>,
    /// Whether the table shows a totals row as its last row.
    pub show_totals_row: bool,
    /// This table's remembered sort order (`<sortState>`, `CT_SortState`). Confirmed against
    /// `sml.xsd`: under `<table>` (`CT_Table`'s own sequence), `sortState` is a direct sibling of
    /// `autoFilter`, not nested inside it — distinct from [`Sheet::sort_state`], which *is* nested
    /// inside a plain worksheet-level `<autoFilter>` (`CT_AutoFilter`'s own sequence puts
    /// `sortState` after `filterColumn*`). Storage only: writing this records what Excel would show
    /// if the user reopened the table's sort dialog, it does not itself reorder `sheet.rows` — the
    /// caller remains responsible for the data actually being in that order, same "caller keeps
    /// things in sync" posture as `AutoFilterColumn`.
    pub sort_state: Option<SortState>,
    /// The named table style applied to this table (`<tableStyleInfo name="..">`). `None` keeps
    /// this crate's own long-standing default, `TableStyleMedium2` (Excel's built-in "Table Style
    /// Medium 2", the first entry in its table style gallery) — same behavior as before this point
    /// existed. `Some` can name either one of Excel's own dozens of built-in styles (e.g.
    /// `"TableStyleLight9"`) or a custom [`TableStyle`] declared in [`Workbook::table_styles`] —
    /// this crate does not itself validate that a `Some` name actually resolves to something Excel
    /// recognizes, same "caller's responsibility" posture as elsewhere (e.g. `Sheet.name`'s
    /// character-limit note).
    pub table_style_name: Option<String>,
}

impl ExcelTable {
    /// Creates a table with no totals row, from a list of plain column names (no calculated-column
    /// formula, no totals-row function on any column yet) — the common case. Use
    /// [`ExcelTable::with_columns`] instead for full control over each [`TableColumn`].
    pub fn new<S: Into<String>>(
        name: impl Into<String>,
        range: impl Into<String>,
        columns: Vec<S>,
    ) -> Self {
        Self {
            name: name.into(),
            range: range.into(),
            columns: columns.into_iter().map(TableColumn::new).collect(),
            show_totals_row: false,
            sort_state: None,
            table_style_name: None,
        }
    }

    /// Creates a table from a list of fully-specified [`TableColumn`]s.
    pub fn with_columns(
        name: impl Into<String>,
        range: impl Into<String>,
        columns: Vec<TableColumn>,
    ) -> Self {
        Self {
            name: name.into(),
            range: range.into(),
            columns,
            show_totals_row: false,
            sort_state: None,
            table_style_name: None,
        }
    }

    /// Sets whether the table shows a totals row and returns it for chaining.
    pub fn with_totals_row(mut self, show: bool) -> Self {
        self.show_totals_row = show;
        self
    }

    /// Sets this table's remembered sort order and returns it for chaining.
    pub fn with_sort_state(mut self, sort_state: SortState) -> Self {
        self.sort_state = Some(sort_state);
        self
    }

    /// Sets this table's named style and returns it for chaining. See
    /// [`table_style_name`](ExcelTable::table_style_name)'s doc comment.
    pub fn with_table_style_name(mut self, name: impl Into<String>) -> Self {
        self.table_style_name = Some(name.into());
        self
    }
}

/// One column of an [`ExcelTable`] (`<tableColumn>`, `CT_TableColumn`) — (plain `name` only),
/// extended for `calculated_formula`/ `totals_row_function`/`totals_row_label`.
#[derive(Debug, Clone, PartialEq)]
pub struct TableColumn {
    /// The column's name, matching the header row's actual cell text (see [`ExcelTable::columns`]'s
    /// doc comment).
    pub name: String,
    /// This column's calculated-column formula (`<calculatedColumnFormula>`), if any. Declaring a
    /// column calculated in the table definition only; this crate does **not** automatically
    /// propagate a `<f>` formula onto every data row's cell in this column — the caller remains
    /// responsible for each data row's own cell actually carrying a matching `CellValue::Formula`
    /// if the per-row formulas should appear too (storage only, same "caller keeps things in sync"
    /// posture as `ExcelTable::columns` itself).
    ///
    /// **Structured references must use the fully-qualified/expanded form, `TableName[[#This
    /// Row],[ColumnName]]` — not the shorthand `[@ColumnName]`.** Both are valid Excel syntax when
    /// *typed into the UI* (Excel silently normalizes one to the other), but a real Excel
    /// installation rejects and strips the whole `<table>` on open when the shorthand form is what
    /// ends up stored verbatim in `calculatedColumnFormula` (and/or a data row's own `<f>`) — a
    /// genuine Excel-authored file stores exactly this expanded form (`Table1[[#This
    /// Row],[ColumnName]]`) rather than `[@ColumnName]`. This crate does not rewrite or validate
    /// formula text — passing a shorthand structured reference here silently produces a file real
    /// Excel repairs on open.
    pub calculated_formula: Option<String>,
    /// This column's totals-row aggregate function (`<tableColumn totalsRowFunction="..">`), if
    /// any. Meaningless unless [`ExcelTable::show_totals_row`] is also `true`. Writes only the
    /// `totalsRowFunction=".."` attribute itself on `<tableColumn>` — unlike an earlier version of
    /// this crate, it does **not** auto-generate a matching
    /// `<totalsRowFormula>SUBTOTAL(n,[ColumnName])</totalsRowFormula>` *table-metadata child
    /// element* for a built-in function anymore: real Excel never writes that particular child
    /// element either (the function name alone determines what it computes internally).
    ///
    /// **This is a separate thing from the totals row's own cell in `sheetData`, which the caller
    /// remains responsible for** (same "caller keeps things in sync" posture as
    /// [`calculated_formula`](TableColumn::calculated_formula)): real Excel's own totals row is a
    /// genuine formula cell, not a plain cached number — confirmed against a real Excel-authored
    /// file, whose totals row cell for a `sum` column literally contains
    /// `<f>SUBTOTAL(109,TableName[ColumnName])</f>` with a cached `<v>`, and for `average`,
    /// `<f>SUBTOTAL(101,TableName[ColumnName])</f>`. The `10x`-prefixed `SUBTOTAL` function codes
    /// (ignoring manually-hidden rows) real Excel tables use are, in `TotalsRowFunction` order:
    /// `Average` → 101, `Count` → 102, `CountNums` → 103, `Max` → 104, `Min` → 105, `StdDev` → 107,
    /// `Var` → 110, `Sum` → 109 (`Custom` has no fixed code — the caller supplies
    /// [`totals_row_formula`](TableColumn::totals_row_formula) directly instead). A totals row cell
    /// left as a plain cached number instead of this formula is one of the concrete differences
    /// from real Excel output that causes a real Excel installation to reject and repair the file.
    /// Only [`TotalsRowFunction::Custom`] pairs with an explicit
    /// [`totals_row_formula`](TableColumn::totals_row_formula). Also see
    /// [`totals_row_label`](TableColumn::totals_row_label)'s doc comment: setting both on the same
    /// column, this field is silently dropped at write time.
    pub totals_row_function: Option<TotalsRowFunction>,
    /// This column's totals-row label (`<tableColumn totalsRowLabel="..">`), shown instead of a
    /// computed value — typically only meaningful on the *first* column of a totals row (e.g.
    /// `"Total"`). The same real Excel-authored reference file mentioned in `totals_row_function`'s
    /// doc comment also shows that the totals row's own cell for the label column carries the label
    /// text itself as a plain string value too (redundant with this attribute, but present) — the
    /// caller remains responsible for that cell's actual value matching. **Mutually exclusive with
    /// `totals_row_function` on the same column and enforced by the writer** (real Excel's own UI
    /// only ever offers one or the other per column): when both are set here, the label wins and
    /// `totals_row_function`/`totals_row_formula` are simply not written for that column.
    pub totals_row_label: Option<String>,
    /// This column's literal totals-row formula text (`<totalsRowFormula>`), only written when
    /// `totals_row_function` is [`TotalsRowFunction::Custom`] *and* `totals_row_label` is `None` —
    /// every other function variant writes no `<totalsRowFormula>` at all (see
    /// `totals_row_function`'s doc comment), and a label on the same column takes priority over
    /// both (see `totals_row_label`'s doc comment). If this formula uses a structured reference,
    /// see `calculated_formula`'s doc comment: use the expanded `TableName[[#This
    /// Row],[ColumnName]]` form, not `[@ColumnName]`.
    pub totals_row_formula: Option<String>,
}

impl TableColumn {
    /// Creates a plain column with no calculated formula or totals-row function yet.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            calculated_formula: None,
            totals_row_function: None,
            totals_row_label: None,
            totals_row_formula: None,
        }
    }

    /// Sets this column's calculated-column formula and returns it for chaining.
    pub fn with_calculated_formula(mut self, formula: impl Into<String>) -> Self {
        self.calculated_formula = Some(formula.into());
        self
    }

    /// Sets this column's totals-row aggregate function and returns it for chaining.
    pub fn with_totals_row_function(mut self, function: TotalsRowFunction) -> Self {
        self.totals_row_function = Some(function);
        self
    }

    /// Sets this column's totals-row label and returns it for chaining.
    pub fn with_totals_row_label(mut self, label: impl Into<String>) -> Self {
        self.totals_row_label = Some(label.into());
        self
    }

    /// Sets this column's literal totals-row formula text (only used when `totals_row_function` is
    /// [`TotalsRowFunction::Custom`]) and returns it for chaining.
    pub fn with_totals_row_formula(mut self, formula: impl Into<String>) -> Self {
        self.totals_row_formula = Some(formula.into());
        self
    }
}

/// A remembered sort order (`<sortState>`, `CT_SortState`). Written in two different places
/// depending on context: as a child of a worksheet-level `<autoFilter>` ([`Sheet::sort_state`]) or
/// as a sibling of a table's own `<autoFilter>` ([`ExcelTable::sort_state`]) — see each field's own
/// doc comment for the exact schema positioning, confirmed via `sml.xsd`'s `CT_AutoFilter`/
/// `CT_Table` sequences. Only the simplest, most common shape is modeled: a plain value-based
/// ascending/descending sort per range (`ST_SortBy`'s `"value"`, the schema default) —
/// `sortBy="cellColor"/ "fontColor"/"icon"`, `customList`, and `dxfId`/`iconSet`/`iconId` (color/
/// icon-based custom sort criteria) are not modeled, same "the common case, not every historical
/// Excel option" posture as `SheetProtection`/`AutoFilterColumn`. Storage only — this crate does
/// not itself reorder any rows, see `ExcelTable.sort_state`'s doc comment.
#[derive(Debug, Clone, PartialEq)]
pub struct SortState {
    /// The overall range this sort applies to (`ref`, required) — e.g. the table's own data range,
    /// or the autofiltered range.
    pub range: String,
    /// Up to 64 sort keys, in priority order (`<sortCondition>`, `CT_SortState`'s own
    /// `maxOccurs="64"` limit — not enforced here, same "caller's responsibility" posture as
    /// elsewhere in this crate).
    pub conditions: Vec<SortCondition>,
}

impl SortState {
    /// Creates a sort state over `range` with no sort keys yet.
    pub fn new(range: impl Into<String>) -> Self {
        Self {
            range: range.into(),
            conditions: Vec::new(),
        }
    }

    /// Appends a sort key and returns the sort state for chaining.
    pub fn with_condition(mut self, condition: SortCondition) -> Self {
        self.conditions.push(condition);
        self
    }
}

/// One sort key within a [`SortState`] (`<sortCondition>`, `CT_SortCondition`).
#[derive(Debug, Clone, PartialEq)]
pub struct SortCondition {
    /// The single column (or row, for a horizontal sort) this key sorts by, as a range reference
    /// (`ref`, required) — e.g. `"B2:B10"` for a sort keyed on column B's values.
    pub range: String,
    /// Whether this key sorts descending (`descending`, default ascending).
    pub descending: bool,
}

impl SortCondition {
    /// Creates an ascending sort key over `range`.
    pub fn new(range: impl Into<String>) -> Self {
        Self {
            range: range.into(),
            descending: false,
        }
    }

    /// Sets whether this key sorts descending and returns it for chaining.
    pub fn with_descending(mut self, descending: bool) -> Self {
        self.descending = descending;
        self
    }
}

/// A table column's totals-row aggregate function (`ST_TotalsRowFunction`).
/// `ST_TotalsRowFunction`'s `"none"` value isn't modeled as its own variant, same convention as
/// elsewhere in this crate — `Option::None` on `TableColumn::totals_row_function` already expresses
/// it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TotalsRowFunction {
    Sum,
    Average,
    Count,
    CountNums,
    Max,
    Min,
    StdDev,
    Var,
    /// A totals-row function this crate doesn't auto-generate a formula for — pair with
    /// [`TableColumn::totals_row_formula`] set to the literal formula text the caller wants written
    /// verbatim.
    Custom,
}

/// Document metadata (`docProps/core.xml`'s Dublin Core fields plus `docProps/app.xml`'s
/// `Company`/`Manager`/`HyperlinkBase`, and `docProps/custom.xml`'s user-defined properties) —
/// extended by. Before both `core.xml`/`app.xml` were always written but always empty/boilerplate
/// (see `writer.rs`'s `to_core_properties_xml`/ `to_app_properties_xml`). Only the handful of
/// fields a real document typically carries are modeled — `docProps/core.xml`'s
/// `lastModifiedBy`/`revision`/`created`/`modified`/`category`/`contentStatus` are still not.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct DocumentProperties {
    /// `docProps/core.xml`'s `<dc:title>`.
    pub title: Option<String>,
    /// `docProps/core.xml`'s `<dc:creator>`.
    pub author: Option<String>,
    /// `docProps/core.xml`'s `<dc:subject>`.
    pub subject: Option<String>,
    /// `docProps/core.xml`'s `<cp:keywords>`.
    pub keywords: Option<String>,
    /// `docProps/app.xml`'s `<Company>`.
    pub company: Option<String>,
    /// `docProps/app.xml`'s `<Manager>`.
    pub manager: Option<String>,
    /// `docProps/app.xml`'s `<HyperlinkBase>` (the base URL relative hyperlinks in this workbook
    /// resolve against) — point 57.
    pub hyperlink_base: Option<String>,
    /// User-defined custom document properties (`docProps/custom.xml`,
    /// `CT_Properties`/`CT_Property`) — point 56, visible in Excel's File > Info > Properties >
    /// Advanced Properties > Custom tab. A `Vec` of `(name, value)` pairs, not a map: insertion
    /// order is preserved and determines the sequential `pid` each entry gets when written (`2`,
    /// `3`, `4`. — `0`/`1` are reserved by the format and never assigned), matching `word-ooxml`'s
    /// own `Document.custom_properties` convention exactly (including which 4
    /// [`CustomPropertyValue`] variants are modeled, for consistency across this workspace's
    /// crates). Only written if non-empty, same "optional part" posture as
    /// `table_styles`/`external_links` elsewhere in this crate.
    pub custom_properties: Vec<(String, CustomPropertyValue)>,
}

/// A single custom document property's value (`docProps/custom.xml`, `CT_Property`'s value
/// `xsd:choice` — this crate models the same 4 of its many variant types as `word-ooxml`'s own
/// `CustomPropertyValue`: `vt:lpwstr` (`Text`), `vt:bool` (`Bool`), `vt:i4` (`Int`), `vt:r8`
/// (`Number`)). `CT_Property` also allows a date variant (`vt:filetime`) and several others
/// (vectors, blobs, currency..) not modeled here — same "simple case first, mirror the sibling
/// crate's own scope decision" posture as `word-ooxml`'s own doc comment for this exact type
/// explains.
#[derive(Debug, Clone, PartialEq)]
pub enum CustomPropertyValue {
    /// A text value (`vt:lpwstr`).
    Text(String),
    /// A boolean value (`vt:bool`).
    Bool(bool),
    /// A 32-bit signed integer value (`vt:i4`).
    Int(i32),
    /// A 64-bit floating-point value (`vt:r8`).
    Number(f64),
}

impl DocumentProperties {
    /// Creates document properties with every field unset (equivalent to
    /// `DocumentProperties::default()`, only useful as a starting point for the `with_*` builders).
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the title and returns the properties for chaining.
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Sets the author and returns the properties for chaining.
    pub fn with_author(mut self, author: impl Into<String>) -> Self {
        self.author = Some(author.into());
        self
    }

    /// Sets the subject and returns the properties for chaining.
    pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
        self.subject = Some(subject.into());
        self
    }

    /// Sets the keywords and returns the properties for chaining.
    pub fn with_keywords(mut self, keywords: impl Into<String>) -> Self {
        self.keywords = Some(keywords.into());
        self
    }

    /// Sets the company and returns the properties for chaining.
    pub fn with_company(mut self, company: impl Into<String>) -> Self {
        self.company = Some(company.into());
        self
    }

    /// Sets the manager and returns the properties for chaining.
    pub fn with_manager(mut self, manager: impl Into<String>) -> Self {
        self.manager = Some(manager.into());
        self
    }

    /// Sets the hyperlink base and returns the properties for chaining — point 57.
    pub fn with_hyperlink_base(mut self, hyperlink_base: impl Into<String>) -> Self {
        self.hyperlink_base = Some(hyperlink_base.into());
        self
    }

    /// Appends a custom document property and returns the properties for chaining. See
    /// `custom_properties`'s doc comment for why order matters (it determines each entry's `pid`).
    pub fn with_custom_property(
        mut self,
        name: impl Into<String>,
        value: CustomPropertyValue,
    ) -> Self {
        self.custom_properties.push((name.into(), value));
        self
    }
}

/// A "what-if" scenario (`<scenario>`, `CT_Scenario`). Represents one named "what if these cells
/// held these values instead" snapshot, as managed through Excel's own Data > What-If Analysis >
/// Scenario Manager. This crate only stores the scenario's definition (name/inputs/comment); it
/// never evaluates the workbook under any scenario (same "storage, not evaluation" posture as
/// formulas).
#[derive(Debug, Clone, PartialEq)]
pub struct Scenario {
    /// The scenario's name, shown in Excel's Scenario Manager.
    pub name: String,
    /// The cells this scenario overrides, as `(cell reference, value text)` pairs
    /// (`<inputCells>`/`<inputCell r=".." val="..">`) — `val` is written verbatim as text, matching
    /// `CT_InputCells`'s own `xsd:string` typing (Excel re-parses it as a number itself).
    pub inputs: Vec<(String, String)>,
    /// An optional comment (`comment`).
    pub comment: Option<String>,
}

impl Scenario {
    /// Creates a scenario with no inputs yet, no comment.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            inputs: Vec::new(),
            comment: None,
        }
    }

    /// Appends an input cell override and returns the scenario for chaining.
    pub fn with_input(mut self, cell: impl Into<String>, value: impl Into<String>) -> Self {
        self.inputs.push((cell.into(), value.into()));
        self
    }

    /// Sets the scenario's comment and returns it for chaining.
    pub fn with_comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }
}

/// One column's filter criteria within a [`Sheet::auto_filter_range`]
/// (`<filterColumn>`/`<filters>`/`<filter>`, `CT_FilterColumn`/ `CT_Filters`/`CT_Filter`). Only the
/// simplest, most common filter form is modeled: a fixed list of checked/visible values —
/// `CT_Filters`'s `CT_CustomFilters` (e.g. "greater than"), `CT_Top10`, `CT_DynamicFilter` (e.g.
/// "this month"), and `CT_ColorFilter`/`CT_IconFilter` forms are not.
#[derive(Debug, Clone, PartialEq)]
pub struct AutoFilterColumn {
    /// This column's 0-based offset from [`Sheet::auto_filter_range`]'s first column (`colId`) —
    /// e.g. `0` for the filter range's own first column, regardless of that column's real sheet
    /// position.
    pub column_offset: u32,
    /// The values that remain visible when this filter is applied (`<filter val="..">` per entry),
    /// written verbatim as text.
    pub visible_values: Vec<String>,
}

impl AutoFilterColumn {
    /// Creates a filter column with the given visible values.
    pub fn new(column_offset: u32, visible_values: Vec<String>) -> Self {
        Self {
            column_offset,
            visible_values,
        }
    }
}

/// A reference to another workbook, used by this workbook's formulas (`<externalReference>` in
/// `xl/workbook.xml`'s `<externalReferences>`, plus a dedicated
/// `xl/externalLinks/externalLinkN.xml` part, `CT_ExternalReference`/`CT_ExternalLink`). Storage
/// only: this crate neither resolves the referenced workbook nor recomputes any formula against it
/// — a formula cell referencing this link (e.g. `"[1]Feuil1!A1"` or `"'[Budget.xlsx]Feuil1'!A1"`)
/// is written/read as plain formula text like any other, this type only accounts for the *link
/// itself* (the part Excel needs to know the reference is legitimate and to cache a fallback value
/// while the other file is closed).
#[derive(Debug, Clone, PartialEq)]
pub struct ExternalWorkbookLink {
    /// The other workbook's path/URL, written as an external (`TargetMode="External"`) relationship
    /// target on this link's own `xl/externalLinks/_rels/externalLinkN.xml.rels` — same shape as
    /// [`HyperlinkTarget::External`]. Can be an absolute path (`"file:///C:/Budget.xlsx"`), a
    /// relative one (`"Budget.xlsx"`), or a URL.
    pub target: String,
    /// The other workbook's own sheet names, in order (`<sheetNames>`/`<sheetName val="..">`) —
    /// Excel uses these to resolve `[1]SheetName!..` formula references while the other file is
    /// closed.
    pub sheet_names: Vec<String>,
    /// Named ranges/constants defined in the other workbook that this one's formulas reference, as
    /// `(name, refersTo text)` pairs (`<definedNames>`/`<definedName name=".." refersTo="..">`).
    pub defined_names: Vec<(String, String)>,
}

impl ExternalWorkbookLink {
    /// Creates an external workbook link with no sheet names/defined names yet.
    pub fn new(target: impl Into<String>) -> Self {
        Self {
            target: target.into(),
            sheet_names: Vec::new(),
            defined_names: Vec::new(),
        }
    }

    /// Appends a sheet name and returns the link for chaining.
    pub fn with_sheet_name(mut self, name: impl Into<String>) -> Self {
        self.sheet_names.push(name.into());
        self
    }

    /// Appends a defined name reference and returns the link for chaining.
    pub fn with_defined_name(
        mut self,
        name: impl Into<String>,
        refers_to: impl Into<String>,
    ) -> Self {
        self.defined_names.push((name.into(), refers_to.into()));
        self
    }
}

/// A suppressed error-checking indicator over one range (`<ignoredError>`, `CT_IgnoredError`).
/// Confirmed against `sml.xsd` (`CT_IgnoredErrors`/`CT_IgnoredError`, ECMA-376 SpreadsheetML):
/// `sqref` is the only required attribute, every error-category flag is an optional boolean
/// defaulting to `false`. This crate models every flag `CT_IgnoredError` defines; real Excel's own
/// "Ignore Error" right-click menu only ever sets one flag at a time per range, but nothing in the
/// schema forbids several flags on the same entry, so this type allows it too (caller's choice,
/// same "don't second-guess the caller" posture as `ConditionalFormattingRule`).
#[derive(Debug, Clone, PartialEq)]
pub struct IgnoredError {
    /// The range this entry covers (`sqref`, e.g. `"B2:B10"` or a single cell `"C4"`) — like
    /// `ConditionalFormattingRule::range`, several disjoint cells can be packed into one `sqref`
    /// (space-separated) if the caller wants a single entry to cover them; this crate writes the
    /// string verbatim, no validation.
    pub range: String,
    /// Suppresses the "number stored as text" warning — by far the most common real-world use of
    /// `<ignoredError>` (e.g. a column of ZIP codes or reference numbers intentionally kept as
    /// text).
    pub number_stored_as_text: bool,
    /// Suppresses the "formula omits adjacent cells" warning.
    pub formula_range: bool,
    /// Suppresses the "inconsistent formula" warning (a formula that differs from the pattern of
    /// its neighboring cells).
    pub formula: bool,
    /// Suppresses the "unlocked cell containing a formula" warning.
    pub unlocked_formula: bool,
    /// Suppresses the "formula refers to an empty cell" warning.
    pub empty_cell_reference: bool,
    /// Suppresses the "value fails a list data validation rule" warning.
    pub list_data_validation: bool,
    /// Suppresses the "table's calculated column formula is inconsistent" warning.
    pub calculated_column: bool,
    /// Suppresses the "text year is ambiguous" warning (a two-digit year entered in a
    /// text-formatted cell).
    pub two_digit_text_year: bool,
    /// Suppresses the "formula results in an error" warning (e.g. a deliberate `#N/A` or
    /// `#DIV/0!`).
    pub eval_error: bool,
}

impl IgnoredError {
    /// Creates an ignored-error entry over `range` with every flag unset — use the `with_*`
    /// builders to enable the specific warning(s) to suppress.
    pub fn new(range: impl Into<String>) -> Self {
        Self {
            range: range.into(),
            number_stored_as_text: false,
            formula_range: false,
            formula: false,
            unlocked_formula: false,
            empty_cell_reference: false,
            list_data_validation: false,
            calculated_column: false,
            two_digit_text_year: false,
            eval_error: false,
        }
    }

    /// Suppresses the "number stored as text" warning and returns the entry for chaining — the
    /// common case (see this type's own doc comment).
    pub fn with_number_stored_as_text(mut self, value: bool) -> Self {
        self.number_stored_as_text = value;
        self
    }

    /// Suppresses the "formula omits adjacent cells" warning and returns the entry for chaining.
    pub fn with_formula_range(mut self, value: bool) -> Self {
        self.formula_range = value;
        self
    }

    /// Suppresses the "inconsistent formula" warning and returns the entry for chaining.
    pub fn with_formula(mut self, value: bool) -> Self {
        self.formula = value;
        self
    }

    /// Suppresses the "unlocked cell containing a formula" warning and returns the entry for
    /// chaining.
    pub fn with_unlocked_formula(mut self, value: bool) -> Self {
        self.unlocked_formula = value;
        self
    }

    /// Suppresses the "formula refers to an empty cell" warning and returns the entry for chaining.
    pub fn with_empty_cell_reference(mut self, value: bool) -> Self {
        self.empty_cell_reference = value;
        self
    }

    /// Suppresses the "value fails a list data validation rule" warning and returns the entry for
    /// chaining.
    pub fn with_list_data_validation(mut self, value: bool) -> Self {
        self.list_data_validation = value;
        self
    }

    /// Suppresses the "table's calculated column formula is inconsistent" warning and returns the
    /// entry for chaining.
    pub fn with_calculated_column(mut self, value: bool) -> Self {
        self.calculated_column = value;
        self
    }

    /// Suppresses the "text year is ambiguous" warning and returns the entry for chaining.
    pub fn with_two_digit_text_year(mut self, value: bool) -> Self {
        self.two_digit_text_year = value;
        self
    }

    /// Suppresses the "formula results in an error" warning and returns the entry for chaining.
    pub fn with_eval_error(mut self, value: bool) -> Self {
        self.eval_error = value;
        self
    }
}

// ============================================================================,: sheet drawing
// (embedded pictures/charts).
// ============================================================================

/// One corner of a cell-anchored drawing range (`<xdr:from>`/`<xdr:to>`, `CT_Marker`) — a cell
/// reference (0-based column/row, matching this crate's own 0-based [`Row`]/column conventions
/// elsewhere) plus an EMU offset *within* that cell, letting a picture/chart start or end partway
/// through a cell rather than exactly on a gridline.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CellAnchorPoint {
    pub column: u32,
    pub column_offset_emu: i64,
    pub row: u32,
    pub row_offset_emu: i64,
}

impl CellAnchorPoint {
    /// A corner exactly on the gridline at `(column, row)`, no offset.
    pub fn new(column: u32, row: u32) -> Self {
        Self {
            column,
            row,
            column_offset_emu: 0,
            row_offset_emu: 0,
        }
    }

    pub fn with_column_offset_emu(mut self, offset: i64) -> Self {
        self.column_offset_emu = offset;
        self
    }

    pub fn with_row_offset_emu(mut self, offset: i64) -> Self {
        self.row_offset_emu = offset;
        self
    }
}

/// A picture's raw image format — mirrors `word_ooxml::ImageFormat` exactly (same four formats,
/// same extension/content-type mapping), kept as its own type rather than shared across crates
/// since neither host crate depends on the other.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PictureFormat {
    Png,
    Jpeg,
    Gif,
    Bmp,
}

impl PictureFormat {
    pub(crate) fn extension(self) -> &'static str {
        match self {
            PictureFormat::Png => "png",
            PictureFormat::Jpeg => "jpeg",
            PictureFormat::Gif => "gif",
            PictureFormat::Bmp => "bmp",
        }
    }

    pub(crate) fn content_type(self) -> &'static str {
        match self {
            PictureFormat::Png => "image/png",
            PictureFormat::Jpeg => "image/jpeg",
            PictureFormat::Gif => "image/gif",
            PictureFormat::Bmp => "image/bmp",
        }
    }

    pub(crate) fn from_extension(extension: &str) -> Option<Self> {
        Some(match extension.to_ascii_lowercase().as_str() {
            "png" => PictureFormat::Png,
            "jpeg" | "jpg" => PictureFormat::Jpeg,
            "gif" => PictureFormat::Gif,
            "bmp" => PictureFormat::Bmp,
            _ => return None,
        })
    }
}

/// A picture embedded in a sheet's drawing (`<xdr:pic>`, `CT_Picture` — the spreadsheet-drawing
/// flavor, distinct from `a:CT_Picture`), anchored by its enclosing [`DrawingAnchor`].
///
/// Reuses `drawing::ShapeProperties`/`drawing::BlipFill` for the picture's own formatting
/// (fill/line/rotation via `spPr`), the same DrawingML content model `word-ooxml`'s own picture
/// support is being generalized toward — this is genuinely shared content, not a parallel
/// reimplementation. Raw image bytes are supplied directly (`data`/`format`), same "no separate
/// loader type" posture as `word_ooxml::Image`.
///
/// Not modeled: cropping (`a:srcRect`), picture-specific effects beyond what `ShapeProperties`
/// itself carries.
#[derive(Debug, Clone, PartialEq)]
pub struct SheetPicture {
    pub data: Vec<u8>,
    pub format: PictureFormat,
    /// Alt text / non-visual name (`<xdr:cNvPr name="..">`).
    pub name: String,
    pub shape_properties: Option<drawing::ShapeProperties>,
}

impl SheetPicture {
    pub fn new(data: impl Into<Vec<u8>>, format: PictureFormat) -> Self {
        Self {
            data: data.into(),
            format,
            name: String::new(),
            shape_properties: None,
        }
    }

    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    pub fn with_shape_properties(mut self, properties: drawing::ShapeProperties) -> Self {
        self.shape_properties = Some(properties);
        self
    }
}

/// A chart embedded in a sheet's drawing (`<xdr:graphicFrame>` referencing a dedicated
/// `xl/charts/chartN.xml` part via `<c:chart r:id="..">`), anchored by its enclosing
/// [`DrawingAnchor`]. Wraps the whole `chart::ChartSpace` this crate's `chart` dependency already
/// knows how to read/write in full — no Excel-specific chart modeling needed here, and no embedded
/// workbook needed either (an Excel chart reads its series directly from this same workbook's
/// cells, via each series' own cell-reference formulas already carried by
/// `chart::NumericDataSource`/`StringDataSource`).
#[derive(Debug, Clone, PartialEq)]
pub struct SheetChart {
    pub chart_space: chart::ChartSpace,
    /// Non-visual name (`<xdr:cNvPr name="..">`).
    pub name: String,
}

impl SheetChart {
    pub fn new(chart_space: chart::ChartSpace) -> Self {
        Self {
            chart_space,
            name: String::new(),
        }
    }

    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }
}

/// The object anchored by a [`DrawingAnchor`] — a picture or a chart.
#[derive(Debug, Clone, PartialEq)]
pub enum DrawingObject {
    /// Boxed: an embedded picture's own encoded bytes make it, in turn, the largest variant once
    /// `Chart` below was boxed (clippy's `large_enum_variant` moves on to whichever variant is now
    /// biggest).
    Picture(Box<SheetPicture>),
    /// Boxed for the same reason as `word-ooxml`'s `RunContent::Chart` and `powerpoint-ooxml`'s
    /// `Shape::Chart` — a chart's own nested `ChartSpace` otherwise forces every `DrawingObject`,
    /// picture or chart alike, to pay for the largest variant's size.
    Chart(Box<SheetChart>),
}

/// One cell-anchored drawing object (`<xdr:twoCellAnchor>`, `CT_TwoCellAnchor`).
///
/// Only the two-cell anchor is modeled (`from`/`to` cell markers, `editAs` always the schema
/// default `"twoCell"`) — by far the common case real spreadsheet tools generate
/// (`CT_OneCellAnchor`/ `CT_AbsoluteAnchor` exist in the schema but are rarely if ever generated,
/// only tolerated on read). A wholly absent anchor kind on read is simply skipped by this crate's
/// forgiving reader, consistent with the rest of this workspace's posture.
#[derive(Debug, Clone, PartialEq)]
pub struct DrawingAnchor {
    pub from: CellAnchorPoint,
    pub to: CellAnchorPoint,
    pub object: DrawingObject,
}

impl DrawingAnchor {
    pub fn new(from: CellAnchorPoint, to: CellAnchorPoint, object: DrawingObject) -> Self {
        Self { from, to, object }
    }
}

/// A sheet's drawing (`xl/drawings/drawingN.xml`, `CT_Drawing`/root `<xdr:wsDr>`) — an unbounded
/// list of anchored pictures/charts, matching the schema's own `EG_Anchor` choice group repeated
/// `maxOccurs="unbounded"`.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct SheetDrawing {
    pub anchors: Vec<DrawingAnchor>,
}

impl SheetDrawing {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_anchor(mut self, anchor: DrawingAnchor) -> Self {
        self.anchors.push(anchor);
        self
    }
}