rust_xlsxwriter 0.97.0

A Rust library for writing Excel 2007 xlsx files
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
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
// serializer - A serde serializer for use with `rust_xlsxwriter`.
//
// SPDX-License-Identifier: MIT OR Apache-2.0
//
// Copyright 2022-2026, John McNamara, jmcnamara@cpan.org

//! # Working with Serde
//!
//! Serialization is the process of converting data from one format to another
//! using rules shared between the data and the serializer. The
//! [Serde](https://serde.rs) crate allows you to attach these types of rules to
//! data, and it also provides traits that can be implemented by serializers to
//! convert that data into different formats. The `rust_xlsxwriter` crate
//! implements the Serde [`serde::Serializer`] trait for [`Worksheet`] structs
//! which allows you to serialize data directly to a worksheet.
//!
//! The following sections explain how to serialize Serde-enabled data to an
//! Excel worksheet using `rust_xlsxwriter`.
//!
//!
//! Contents:
//!
//! - [How serialization works in
//!   `rust_xlsxwriter`](#how-serialization-works-in-rust_xlsxwriter)
//! - [Setting serialization headers](#setting-serialization-headers)
//! - [Renaming fields when serializing](#renaming-fields-when-serializing)
//! - [Skipping fields when serializing](#skipping-fields-when-serializing)
//! - [Setting serialization formatting](#setting-serialization-formatting)
//! - [Serializing dates and times](#serializing-dates-and-times)
//! - [Controlling Excel output via `XlsxSerialize` and struct
//!   attributes](#controlling-excel-output-via-xlsxserialize-and-struct-attributes)
//!   - [Container `xlsx` attributes](#container-xlsx-attributes)
//!   - [Field `xlsx` attributes](#field-xlsx-attributes)
//! - [Limitations of serializing to
//!   Excel](#limitations-of-serializing-to-excel)
//!
//! **Note**: This functionality requires the use of the `serde` feature flag
//! with `rust_xlsxwriter`:
//!
//! ```bash
//! cargo add rust_xlsxwriter -F serde
//! ```
//!
//!
//!
//!
//! ## How serialization works in `rust_xlsxwriter`
//!
//! Serialization with `rust_xlsxwriter` needs to consider that the target
//! output is a 2D grid of cells into which the data can be serialized. As such,
//! the focus is on serializing data types that map to this 2D grid, such as
//! structs or compound collections of structs like vectors or tuples, and it
//! (currently) ignores compound types like maps.
//!
//! The image below shows the basic scheme for mapping a struct to a worksheet:
//! fields are mapped to a header and values are mapped to sequential cells
//! below the header.
//!
//! <img src="https://rustxlsxwriter.github.io/images/serialize_intro1.png">
//!
//! This scheme needs an initial (row, col) location from which to start
//! serializing to allow the data to be positioned anywhere on the worksheet.
//! Subsequent serializations will be in the same columns (for the target struct
//! type) but will be one row lower in the worksheet.
//!
//! The type name and fields of the struct being serialized is also required
//! information. We will look at that in more detail in the next section.
//!
//! Here is an example program that demonstrates the basic steps for serializing
//! data to an Excel worksheet:
//!
//! ```
//! # // This code is available in examples/doc_worksheet_serialize_intro2.rs
//! #
//! use rust_xlsxwriter::{Format, FormatBorder, Workbook, XlsxError};
//! use serde::{Serialize, Deserialize};
//!
//! fn main() -> Result<(), XlsxError> {
//!     let mut workbook = Workbook::new();
//!
//!     // Add a worksheet to the workbook.
//!     let worksheet = workbook.add_worksheet();
//!
//!     // Add some formats to use with the serialization data.
//!     let header_format = Format::new()
//!         .set_bold()
//!         .set_border(FormatBorder::Thin)
//!         .set_background_color("C6E0B4");
//!
//!     // Create a serializable struct.
//!     #[derive(Deserialize, Serialize)]
//!     #[serde(rename_all = "PascalCase")]
//!     struct Student<'a> {
//!         name: &'a str,
//!         age: u8,
//!         id: u32,
//!     }
//!
//!     let students = [
//!         Student {
//!             name: "Aoife",
//!             age: 25,
//!             id: 564351,
//!         },
//!         Student {
//!             name: "Caoimhe",
//!             age: 21,
//!             id: 443287,
//!         },
//!     ];
//!
//!     // Set up the start location and headers of the data to be serialized.
//!     worksheet.deserialize_headers_with_format::<Student>(1, 3, &header_format)?;
//!
//!     // Serialize the data.
//!     worksheet.serialize(&students)?;
//!
//!     // Save the file.
//!     workbook.save("serialize.xlsx")?;
//!
//!     Ok(())
//! }
//! ```
//!
//! Output file:
//!
//! <img src="https://rustxlsxwriter.github.io/images/serialize_intro2.png">
//!
//!
//!
//!
//! ## Setting serialization headers
//!
//! When serializing structs `rust_xlsxwriter` needs to know the location where
//! the serialization starts and also the type and field names of the struct
//! being serialized. The field names are used as headers, and the type name
//! allows for several distinct structs to be serialized to the same worksheet.
//!
//! The worksheet methods that perform this function fall into three types:
//!
//! 1. For structs that only derive [`Serialize`] `rust_xlsxwriter` will use the
//!    same serialization it uses to write data to figure out the required
//!    fields and headers. This has the minor disadvantage that it needs an
//!    instance of the type (and not just the type itself) in order to work.
//!
//!    The following methods are available for this approach:
//!
//!    - [`Worksheet::serialize_headers()`]: Requires a concrete instance of the
//!      type of struct that you wish to serialize. The library uses this to
//!      infer the struct name and fields.
//!
//!    - [`Worksheet::serialize_headers_with_format()`]: This is similar to the
//!      previous method but it allows you to add a cell format for the headers.
//!
//!    - [`Worksheet::serialize_headers_with_options()`]: Similar to the
//!      previous methods but also allows configuration of the headers and
//!      fields via [`SerializeFieldOptions`].
//!
//! 2. For structs that derive [`Serialize`] and [`Deserialize`]
//!    `rust_xlsxwriter` can use deserialization to figure out the required
//!    fields and headers. This has the minor advantage that it only needs the
//!    type and doesn't require an instance of the type.
//!
//!    The following methods are available for this approach:
//!
//!    - [`Worksheet::deserialize_headers()`]: This only requires the type of
//!      struct that you wish to serialize and that it derives the
//!      [`Deserialize`] and [`Serialize`] traits. The library uses this to
//!      infer the struct name and fields (via deserialization).
//!
//!    - [`Worksheet::deserialize_headers_with_format()`]: This is similar to
//!      the previous method but it allows you to add a cell format for the
//!      headers.
//!
//!    - [`Worksheet::deserialize_headers_with_options()`]: Similar to the
//!      previous methods but also allows configuration of the headers and
//!      fields via [`SerializeFieldOptions`].
//!
//! 3. For structs that derive [`Serialize`] and [`XlsxSerialize`] (a
//!    `rust_xlsxwriter` provided trait) the library uses proc macros associated
//!    with `XlsxSerialize` to figure out the required fields and headers. This
//!    has the advantage of allowing the user to specify header and field
//!    formatting via struct attributes. See [Controlling Excel output via
//!    `XlsxSerialize` and struct
//!    attributes](#controlling-excel-output-via-xlsxserialize-and-struct-attributes)
//!    for details on how this works.
//!
//!    Since the formatting can be encoded in struct attributes this approach
//!    only requires one worksheet method:
//!
//!    - [`Worksheet::set_serialize_headers()`]: This only requires the type of
//!      struct that you wish to serialize and that it derives the
//!      [`XlsxSerialize`] and [`Serialize`] traits.
//!
//! The availability of 3 different approaches (and associated methods) will
//! probably cause mild anxiety in the reader as they will sense that they are
//! required to make a choice without knowing which is the best approach. In
//! general you can decide as follows: if your struct derives only have
//! [`Serialize`] and changing it is outside your control you must use the
//! serialization method (Approach 1); if you struct also supports
//! [`Deserialize`] you can save yourself the step of requiring a concrete
//! instance type and use the deserialization method (Approach 2); finally, if
//! the definition of the struct is under your control and you can add
//! [`XlsxSerialize`] then can define the formatting along with the struct and
//! also save yourself a lot of additional structural code to set up formatting
//! (Approach 3). The [`XlsxSerialize`] approach does, however,  limit you to
//! having a fixed set of formatting per struct.
//!
//! The two examples below should help inform your decision. If not, note that
//! the author mainly uses [`XlsxSerialize`], but you can use whichever method
//! works for you without fear of judgment.
//!
//! The first example below shows the usage of some of the serialization and
//! deserialization methods.
//!
//! ```rust
//! # // This code is available in examples/doc_worksheet_serialize_headers3.rs
//! #
//! use rust_xlsxwriter::{
//!     CustomSerializeField, Format, FormatBorder, SerializeFieldOptions, Workbook, XlsxError,
//! };
//! use serde::{Deserialize, Serialize};
//!
//! fn main() -> Result<(), XlsxError> {
//!     let mut workbook = Workbook::new();
//!
//!     // Add a worksheet to the workbook.
//!     let worksheet = workbook.add_worksheet();
//!
//!     // Set some column widths for clarity.
//!     worksheet.set_column_width(2, 4)?;
//!     worksheet.set_column_width(5, 4)?;
//!     worksheet.set_column_width(8, 4)?;
//!
//!     // Add some formats to use with the serialization data.
//!     let header_format = Format::new()
//!         .set_bold()
//!         .set_border(FormatBorder::Thin)
//!         .set_background_color("C6EFCE");
//!
//!     let currency_format = Format::new().set_num_format("$0.00");
//!
//!     // Create a serializable struct.
//!     #[derive(Deserialize, Serialize)]
//!     struct Produce {
//!         fruit: &'static str,
//!         cost: f64,
//!     }
//!
//!     // Create some data instances.
//!     let item1 = Produce {
//!         fruit: "Peach",
//!         cost: 1.05,
//!     };
//!
//!     let item2 = Produce {
//!         fruit: "Plum",
//!         cost: 0.15,
//!     };
//!
//!     let item3 = Produce {
//!         fruit: "Pear",
//!         cost: 0.75,
//!     };
//!
//!     // 1. Set the serialization location and headers with `deserialize_headers()`
//!     //    and serialize some data.
//!     worksheet.deserialize_headers::<Produce>(0, 0)?;
//!
//!     worksheet.serialize(&item1)?;
//!     worksheet.serialize(&item2)?;
//!     worksheet.serialize(&item3)?;
//!
//!     // 2. Set the serialization location and formatted headers with
//!     //    `serialize_headers_with_format()` and serialize some data.
//!     worksheet.serialize_headers_with_format(0, 3, &item1, &header_format)?;
//!
//!     worksheet.serialize(&item1)?;
//!     worksheet.serialize(&item2)?;
//!     worksheet.serialize(&item3)?;
//!
//!     // 3. Set the serialization location and headers with custom headers. We use
//!     //    the customization to set the header format and also rename the cell format
//!     //    for the number values.
//!     let custom_headers = [
//!         CustomSerializeField::new("fruit").rename("Item"),
//!         CustomSerializeField::new("cost")
//!             .rename("Price")
//!             .set_value_format(currency_format),
//!     ];
//!     let header_options = SerializeFieldOptions::new()
//!         .set_header_format(header_format)
//!         .set_custom_headers(&custom_headers);
//!
//!     // Set the serialization location and custom headers.
//!     worksheet.deserialize_headers_with_options::<Produce>(0, 6, &header_options)?;
//!
//!     worksheet.serialize(&item1)?;
//!     worksheet.serialize(&item2)?;
//!     worksheet.serialize(&item3)?;
//!
//!     // 4. Set the serialization location and headers with custom options. We use
//!     //    the customization to turn off the headers.
//!     let header_options = SerializeFieldOptions::new().hide_headers(true);
//!
//!     // Set the serialization location and custom headers.
//!     worksheet.serialize_headers_with_options(0, 9, &item1, &header_options)?;
//!
//!     worksheet.serialize(&item1)?;
//!     worksheet.serialize(&item2)?;
//!     worksheet.serialize(&item3)?;
//!
//!     // Save the file.
//!     workbook.save("serialize.xlsx")?;
//!
//!     Ok(())
//! }
//! ```
//!
//! Output file:
//!
//! <img
//! src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers3.png">
//!
//!
//! The second example uses `XlsxSerialize` and struct attributes to define the
//! output. Note that there is a lot less structural code in comparison to the
//! previous examples and that the formatting definitions are inline with the
//! struct. On the other hand, you should also note that the previous example
//! where four different outputs are obtained for the same struct isn't possible
//! with this approach since the format definition is locked to the struct.
//!
//! ```
//! # // This code is available in examples/doc_xlsxserialize_intro.rs
//! #
//! use rust_xlsxwriter::{Workbook, XlsxError, XlsxSerialize};
//! use serde::Serialize;
//!
//! fn main() -> Result<(), XlsxError> {
//!     let mut workbook = Workbook::new();
//!
//!     // Add a worksheet to the workbook.
//!     let worksheet = workbook.add_worksheet();
//!
//!     // Create a serializable struct.
//!     #[derive(XlsxSerialize, Serialize)]
//!     #[xlsx(header_format = Format::new().set_bold())]
//!     struct Produce {
//!         #[xlsx(rename = "Item")]
//!         #[xlsx(column_width = 12.0)]
//!         fruit: &'static str,
//!
//!         #[xlsx(rename = "Price", num_format = "$0.00")]
//!         cost: f64,
//!     }
//!
//!     // Create some data instances.
//!     let item1 = Produce {
//!         fruit: "Peach",
//!         cost: 1.05,
//!     };
//!
//!     let item2 = Produce {
//!         fruit: "Plum",
//!         cost: 0.15,
//!     };
//!
//!     let item3 = Produce {
//!         fruit: "Pear",
//!         cost: 0.75,
//!     };
//!
//!     // Set the serialization location and headers.
//!     worksheet.set_serialize_headers::<Produce>(0, 0)?;
//!
//!     // Serialize the data.
//!     worksheet.serialize(&item1)?;
//!     worksheet.serialize(&item2)?;
//!     worksheet.serialize(&item3)?;
//!
//!     // Save the file to disk.
//!     workbook.save("serialize.xlsx")?;
//!
//!     Ok(())
//! }
//! ```
//!
//! Output file:
//!
//! <img src="https://rustxlsxwriter.github.io/images/xlsxserialize_intro.png">
//!
//!
//!
//!
//! ## Renaming fields when serializing
//!
//! As explained above, serialization converts the field names of structs to
//! column headers at the top of serialized data. The default field names are
//! generally `lowercase` and `snake_case` and may not be the way you want the
//! header names displayed in Excel. In such cases, you can use one of the three
//! main methods to rename the fields/headers:
//!
//! 1. Rename the field during serialization using the Serde:
//!    - [field attribute]: `#[serde(rename = "name")` or
//!    - [container attribute]: `#[serde(rename_all = "...")]`.
//! 2. Rename the header (not field) when setting up custom serialization
//!    headers via [`Worksheet::deserialize_headers_with_options()`] or
//!    [`Worksheet::serialize_headers_with_options()`] and
//!    [`CustomSerializeField::rename()`].
//! 3. Rename the field using the [`XlsxSerialize`] field attribute
//!    `#[xlsx(rename = "name")`. This is effectively the same as the Serde
//!    attribute but allows you to specify a different name for the Excel
//!    serialization. See [Field `xlsx` attributes](#field-xlsx-attributes) for
//!    details.
//!
//! [field attribute]: https://serde.rs/field-attrs.html
//! [container attribute]: https://serde.rs/container-attrs.html
//!
//! Examples of these methods are shown below.
//!
//! ### Examples of field renaming
//!
//! The following example demonstrates renaming fields during serialization by
//! using Serde field attributes.
//!
//! ```rust
//! # // This code is available in examples/doc_worksheet_serialize_headers_rename1.rs
//! #
//! # use rust_xlsxwriter::{Workbook, XlsxError};
//! # use serde::{Deserialize, Serialize};
//! #
//! # fn main() -> Result<(), XlsxError> {
//! #     let mut workbook = Workbook::new();
//! #
//! #     // Add a worksheet to the workbook.
//! #     let worksheet = workbook.add_worksheet();
//! #
//!     // Create a serializable struct. Note the serde attributes.
//!     #[derive(Deserialize, Serialize)]
//!     struct Produce {
//!         #[serde(rename = "Item")]
//!         fruit: &'static str,
//!
//!         #[serde(rename = "Price")]
//!         cost: f64,
//!     }
//!
//!     // Create some data instances.
//!     let items = [
//!         Produce {
//!             fruit: "Peach",
//!             cost: 1.05,
//!         },
//!         Produce {
//!             fruit: "Plum",
//!             cost: 0.15,
//!         },
//!         Produce {
//!             fruit: "Pear",
//!             cost: 0.75,
//!         },
//!     ];
//!
//!     // Set the serialization location and headers.
//!     worksheet.deserialize_headers::<Produce>(0, 0)?;
//!
//!     // Serialize the data.
//!     worksheet.serialize(&items)?;
//! #
//! #     // Save the file.
//! #     workbook.save("serialize.xlsx")?;
//! #
//! #     Ok(())
//! # }
//! ```
//!
//! Output file:
//!
//! <img
//! src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers_rename1.png">
//!
//!
//! The following example demonstrates renaming fields during serialization by
//! specifying custom headers and renaming them there. The output is the same as
//! the image above.
//!
//! ```rust
//! # // This code is available in examples/doc_worksheet_serialize_headers_rename2.rs
//! #
//! # use rust_xlsxwriter::{CustomSerializeField, SerializeFieldOptions, Workbook, XlsxError};
//! # use serde::{Deserialize, Serialize};
//! #
//! # fn main() -> Result<(), XlsxError> {
//! #     let mut workbook = Workbook::new();
//! #
//! #     // Add a worksheet to the workbook.
//! #     let worksheet = workbook.add_worksheet();
//! #
//!     // Create a serializable struct.
//!     #[derive(Deserialize, Serialize)]
//!     struct Produce {
//!         fruit: &'static str,
//!         cost: f64,
//!     }
//!
//!     // Create some data instances.
//!     let items = [
//!         Produce {
//!             fruit: "Peach",
//!             cost: 1.05,
//!         },
//!         Produce {
//!             fruit: "Plum",
//!             cost: 0.15,
//!         },
//!         Produce {
//!             fruit: "Pear",
//!             cost: 0.75,
//!         },
//!     ];
//!
//!     // Set up the custom headers.
//!     let custom_headers = [
//!         CustomSerializeField::new("fruit").rename("Item"),
//!         CustomSerializeField::new("cost").rename("Price"),
//!     ];
//!     let header_options = SerializeFieldOptions::new().set_custom_headers(&custom_headers);
//!
//!     // Set the serialization location and custom headers.
//!     worksheet.deserialize_headers_with_options::<Produce>(0, 0, &header_options)?;
//!
//!     // Serialize the data.
//!     worksheet.serialize(&items)?;
//! #
//! #     // Save the file.
//! #     workbook.save("serialize.xlsx")?;
//! #
//! #     Ok(())
//! # }
//! ```
//!
//! The following example demonstrates renaming fields during serialization by
//! using `XlsxSerialize` `xlsx` field attributes. The output is the same as the
//! image above.
//!
//! ```rust
//! # // This code is available in examples/doc_xlsxserialize_rename.rs
//! #
//! # use rust_xlsxwriter::{Workbook, XlsxError, XlsxSerialize};
//! # use serde::Serialize;
//! #
//! # fn main() -> Result<(), XlsxError> {
//! #     let mut workbook = Workbook::new();
//! #
//! #     // Add a worksheet to the workbook.
//! #     let worksheet = workbook.add_worksheet();
//! #
//!     // Create a serializable struct.
//!     #[derive(XlsxSerialize, Serialize)]
//!     struct Produce {
//!         #[xlsx(rename = "Item")]
//!         fruit: &'static str,
//!
//!         #[xlsx(rename = "Price")]
//!         cost: f64,
//!     }
//!
//!     // Create some data instances.
//!     let items = [
//!         Produce {
//!             fruit: "Peach",
//!             cost: 1.05,
//!         },
//!         Produce {
//!             fruit: "Plum",
//!             cost: 0.15,
//!         },
//!         Produce {
//!             fruit: "Pear",
//!             cost: 0.75,
//!         },
//!     ];
//!
//!     // Set the serialization location and headers.
//!     worksheet.set_serialize_headers::<Produce>(0, 0)?;
//!
//!     // Serialize the data.
//!     worksheet.serialize(&items)?;
//! #
//! #     // Save the file to disk.
//! #     workbook.save("serialize.xlsx")?;
//! #
//! #     Ok(())
//! # }
//! ```
//!
//!
//!
//!
//! ## Skipping fields when serializing
//!
//! When serializing a struct, you may not want all of the fields to be
//! serialized. For example, the struct may contain internal fields that aren't
//! of interest to the end user. There are several ways to skip fields:
//!
//! 1. Using the Serde [field attributes] `#[serde(skip)]`. This is the simplest
//!    and best method.
//! 2. Explicitly omitting the field by setting up custom serialization headers
//!    This method is useful when you can't add any additional attributes on the
//!    struct.
//! 3. Marking the field as skippable via custom headers and the
//!    [`CustomSerializeField::skip()`] method. This is only required in a few
//!    edge cases where other methods won't work.
//! 4. Skip the field using the [`XlsxSerialize`] field attribute
//!    `#[xlsx(skip)]`. This is effectively the same as the Serde attribute but
//!    allows you to specify a different behavior for the Excel serialization.
//!    See [Field `xlsx` attributes](#field-xlsx-attributes) for details.
//!
//! [field attributes]: https://serde.rs/field-attrs.html
//!
//! Examples of all four methods are shown below.
//!
//!
//! ### Examples of field skipping
//!
//! The following example demonstrates skipping fields during serialization by
//! using Serde field attributes. Since the field is no longer used, we also
//! need to tell `rustc` not to emit a `dead_code` warning.
//!
//! ```rust
//! # // This code is available in examples/doc_worksheet_serialize_headers_skip1.rs
//! #
//! use rust_xlsxwriter::{Workbook, XlsxError};
//! use serde::{Deserialize, Serialize};
//!
//! fn main() -> Result<(), XlsxError> {
//!     let mut workbook = Workbook::new();
//!
//!     // Add a worksheet to the workbook.
//!     let worksheet = workbook.add_worksheet();
//!
//!     // Create a serializable struct. Note the serde attribute.
//!     #[derive(Deserialize, Serialize)]
//!     struct Produce {
//!         fruit: &'static str,
//!         cost: f64,
//!
//!         #[serde(skip)]
//!         #[allow(dead_code)]
//!         in_stock: bool,
//!     }
//!
//!     // Create some data instances.
//!     let item1 = Produce {
//!         fruit: "Peach",
//!         cost: 1.05,
//!         in_stock: true,
//!     };
//!
//!     let item2 = Produce {
//!         fruit: "Plum",
//!         cost: 0.15,
//!         in_stock: true,
//!     };
//!
//!     let item3 = Produce {
//!         fruit: "Pear",
//!         cost: 0.75,
//!         in_stock: false,
//!     };
//!
//!     // Set the serialization location and headers.
//!     worksheet.deserialize_headers::<Produce>(0, 0)?;
//!
//!     // Serialize the data.
//!     worksheet.serialize(&item1)?;
//!     worksheet.serialize(&item2)?;
//!     worksheet.serialize(&item3)?;
//!
//!     // Save the file.
//!     workbook.save("serialize.xlsx")?;
//!
//!     Ok(())
//! }
//! ```
//!
//! Output file:
//!
//! <img
//! src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers_skip1.png">
//!
//!
//!
//! The following example demonstrates skipping fields during serialization by
//! omitting them from the serialization headers. To do this, we need to specify
//! custom headers and set [`SerializeFieldOptions::use_custom_headers_only()`].
//! The output is the same as the image above.
//!
//! ```rust
//! # // This code is available in examples/doc_worksheet_serialize_headers_skip2.rs
//! #
//! # use rust_xlsxwriter::{CustomSerializeField, SerializeFieldOptions, Workbook, XlsxError};
//! # use serde::{Deserialize, Serialize};
//! #
//! # fn main() -> Result<(), XlsxError> {
//! #     let mut workbook = Workbook::new();
//! #
//! #     // Add a worksheet to the workbook.
//! #     let worksheet = workbook.add_worksheet();
//! #
//!     // Create a serializable struct.
//!     #[derive(Deserialize, Serialize)]
//!     struct Produce {
//!         fruit: &'static str,
//!         cost: f64,
//!         in_stock: bool,
//!     }
//!
//!     // Create some data instances.
//!     let item1 = Produce {
//!         fruit: "Peach",
//!         cost: 1.05,
//!         in_stock: true,
//!     };
//!
//!     let item2 = Produce {
//!         fruit: "Plum",
//!         cost: 0.15,
//!         in_stock: true,
//!     };
//!
//!     let item3 = Produce {
//!         fruit: "Pear",
//!         cost: 0.75,
//!         in_stock: false,
//!     };
//!
//!     // Set up only the custom headers we want and omit "in_stock".
//!     let custom_headers = [
//!         CustomSerializeField::new("fruit"),
//!         CustomSerializeField::new("cost"),
//!     ];
//!
//!     // Note the use of "use_custom_headers_only" to only serialize the named
//!     // custom headers.
//!     let header_options = SerializeFieldOptions::new()
//!         .use_custom_headers_only(true)
//!         .set_custom_headers(&custom_headers);
//!
//!     // Set the serialization location and custom headers.
//!     worksheet.deserialize_headers_with_options::<Produce>(0, 0, &header_options)?;
//!
//!     // Serialize the data.
//!     worksheet.serialize(&item1)?;
//!     worksheet.serialize(&item2)?;
//!     worksheet.serialize(&item3)?;
//! #
//! #     // Save the file.
//! #     workbook.save("serialize.xlsx")?;
//! #
//! #     Ok(())
//! # }
//! ```
//!
//! The following example is similar in setup to the previous example but
//! demonstrates skipping fields by explicitly skipping them in the custom
//! headers. This method should only be required in a few edge cases. The output
//! is the same as the image above.
//!
//! ```rust
//! # // This code is available in examples/doc_worksheet_serialize_headers_skip3.rs
//! #
//! # use rust_xlsxwriter::{CustomSerializeField, SerializeFieldOptions, Workbook, XlsxError};
//! # use serde::{Deserialize, Serialize};
//! #
//! # fn main() -> Result<(), XlsxError> {
//! #     let mut workbook = Workbook::new();
//! #
//! #     // Add a worksheet to the workbook.
//! #     let worksheet = workbook.add_worksheet();
//! #
//! #     // Create a serializable struct.
//! #     #[derive(Deserialize, Serialize)]
//! #     struct Produce {
//! #         fruit: &'static str,
//! #         cost: f64,
//! #         in_stock: bool,
//! #     }
//! #
//! #     // Create some data instances.
//! #     let item1 = Produce {
//! #         fruit: "Peach",
//! #         cost: 1.05,
//! #         in_stock: true,
//! #     };
//! #
//! #     let item2 = Produce {
//! #         fruit: "Plum",
//! #         cost: 0.15,
//! #         in_stock: true,
//! #     };
//! #
//! #     let item3 = Produce {
//! #         fruit: "Pear",
//! #         cost: 0.75,
//! #         in_stock: false,
//! #     };
//! #
//!     // We only need to set a custom header for the field we want to skip.
//!     let header_options = SerializeFieldOptions::new()
//!         .set_custom_headers(&[CustomSerializeField::new("in_stock").skip(true)]);
//!
//!     // Set the serialization location and custom headers.
//!     worksheet.deserialize_headers_with_options::<Produce>(0, 0, &header_options)?;
//! #
//! #     // Serialize the data.
//! #     worksheet.serialize(&item1)?;
//! #     worksheet.serialize(&item2)?;
//! #     worksheet.serialize(&item3)?;
//! #
//! #     // Save the file.
//! #     workbook.save("serialize.xlsx")?;
//! #
//! #     Ok(())
//! # }
//! ```
//!
//! The following example demonstrates skipping fields during serialization by
//! using `XlsxSerialize` field attributes. Since the field is no longer used,
//! we also need to tell `rustc` not to emit a `dead_code` warning.
//!
//! ```rust
//! # // This code is available in examples/doc_xlsxserialize_skip2.rs
//! #
//! # use rust_xlsxwriter::{Workbook, XlsxError, XlsxSerialize};
//! # use serde::Serialize;
//! #
//! # fn main() -> Result<(), XlsxError> {
//! #     let mut workbook = Workbook::new();
//! #
//! #     // Add a worksheet to the workbook.
//! #     let worksheet = workbook.add_worksheet();
//! #
//!     // Create a serializable struct.
//!     #[derive(XlsxSerialize, Serialize)]
//!     struct Produce {
//!         fruit: &'static str,
//!         cost: f64,
//!
//!         #[xlsx(skip)]
//!         #[allow(dead_code)]
//!         in_stock: bool,
//!     }
//! #
//! #     // Create some data instances.
//! #     let item1 = Produce {
//! #         fruit: "Peach",
//! #         cost: 1.05,
//! #         in_stock: true,
//! #     };
//! #
//! #     let item2 = Produce {
//! #         fruit: "Plum",
//! #         cost: 0.15,
//! #         in_stock: true,
//! #     };
//! #
//! #     let item3 = Produce {
//! #         fruit: "Pear",
//! #         cost: 0.75,
//! #         in_stock: false,
//! #     };
//! #
//! #     // Set the serialization location and headers.
//! #     worksheet.set_serialize_headers::<Produce>(0, 0)?;
//! #
//! #     // Serialize the data.
//! #     worksheet.serialize(&item1)?;
//! #     worksheet.serialize(&item2)?;
//! #     worksheet.serialize(&item3)?;
//! #
//! #     // Save the file to disk.
//! #     workbook.save("serialize.xlsx")?;
//! #
//! #     Ok(())
//! # }
//! ```
//!
//! ## Setting serialization formatting
//!
//! Serialization will transfer your data to a worksheet, but it won't format it
//! without a few additional steps.
//!
//! The most common requirement is to format the headers/fields at the top of
//! the serialized data. The simplest way to do this is to use the
//! [`Worksheet::deserialize_headers_with_format()`] or
//! [`Worksheet::serialize_headers_with_format()`] methods, as shown in the
//! [Setting serialization headers](#setting-serialization-headers) section
//! above. Alternatively, you can use the `#[xlsx(header_format = Format)]`
//! attribute (see [Container `xlsx` attributes](#container-xlsx-attributes)).
//!
//! The other common requirement is to format values that are serialized below
//! the headers, such as numeric data where you need to control the number of
//! decimal places or make it appear as a currency.
//!
//! There are a few ways of formatting the values for a field:
//!
//! - Use [`Worksheet::set_column_format()`] to format the entire column.
//! - Use [`CustomSerializeField::set_column_format()`] to format the entire
//!   column. This is the same as the worksheet method but it has the advantage
//!   of having the column number calculated automatically based on the field
//!   name.
//! - Use [`CustomSerializeField::set_value_format()`] to format just the
//!   serialized data (and not the entire column).
//! - Using `XlsxSerialize` attributes. This is explained in detail in the
//!   section below on [Controlling Excel output via `XlsxSerialize` and struct
//!   attributes](#controlling-excel-output-via-xlsxserialize-and-struct-attributes).
//!
//! Examples of the first three methods are shown below. Examples of
//! `XlsxSerialize` attributes are shown in a subsequent section below.
//!
//! ### Examples of formatting
//!
//! The following example demonstrates serializing instances of a Serde derived
//! data structure to a worksheet with header and cell formatting.
//!
//! ```rust
//! # // This code is available in examples/doc_worksheet_serialize_headers_format4.rs
//! #
//! use rust_xlsxwriter::{Format, FormatBorder, Workbook, XlsxError};
//! use serde::{Deserialize, Serialize};
//!
//! fn main() -> Result<(), XlsxError> {
//!     let mut workbook = Workbook::new();
//!
//!     // Add a worksheet to the workbook.
//!     let worksheet = workbook.add_worksheet();
//!
//!     // Add some formats to use with the serialization data.
//!     let header_format = Format::new()
//!         .set_bold()
//!         .set_border(FormatBorder::Thin)
//!         .set_background_color("C6EFCE");
//!
//!     let currency_format = Format::new().set_num_format("$0.00");
//!
//!     // Create a serializable struct.
//!     #[derive(Deserialize, Serialize)]
//!     struct Produce {
//!         #[serde(rename = "Item")]
//!         fruit: &'static str,
//!
//!         #[serde(rename = "Price")]
//!         cost: f64,
//!     }
//!
//!     // Create some data instances.
//!     let item1 = Produce {
//!         fruit: "Peach",
//!         cost: 1.05,
//!     };
//!
//!     let item2 = Produce {
//!         fruit: "Plum",
//!         cost: 0.15,
//!     };
//!
//!     let item3 = Produce {
//!         fruit: "Pear",
//!         cost: 0.75,
//!     };
//!
//!     // Set a column format for the column. This is added to cell data that
//!     // doesn't have any other format so it doesn't affect the headers.
//!     worksheet.set_column_format(2, &currency_format)?;
//!
//!     // Set the serialization location and headers.
//!     worksheet.deserialize_headers_with_format::<Produce>(1, 1, &header_format)?;
//!
//!     // Serialize the data.
//!     worksheet.serialize(&item1)?;
//!     worksheet.serialize(&item2)?;
//!     worksheet.serialize(&item3)?;
//!
//!     // Save the file.
//!     workbook.save("serialize.xlsx")?;
//!
//!     Ok(())
//! }
//! ```
//!
//! Output file:
//!
//! <img
//! src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers_custom.png">
//!
//! The following variation on the example demonstrates setting formatting via
//! custom headers. This produces the same output as the previous example but
//! doesn't require you to manually, or programmatically, calculate the column
//! number.
//!
//! ```rust
//! # // This code is available in examples/doc_worksheet_serialize_headers_format5.rs
//! #
//! # use rust_xlsxwriter::{
//! #     CustomSerializeField, Format, FormatBorder, SerializeFieldOptions, Workbook, XlsxError,
//! # };
//! # use serde::{Deserialize, Serialize};
//! #
//! # fn main() -> Result<(), XlsxError> {
//! #     let mut workbook = Workbook::new();
//! #
//! #     // Add a worksheet to the workbook.
//! #     let worksheet = workbook.add_worksheet();
//! #
//! #     // Add some formats to use with the serialization data.
//! #     let header_format = Format::new()
//! #         .set_bold()
//! #         .set_border(FormatBorder::Thin)
//! #         .set_background_color("C6EFCE");
//! #
//! #     let currency_format = Format::new().set_num_format("$0.00");
//! #
//! #     // Create a serializable struct.
//! #     #[derive(Deserialize, Serialize)]
//! #     struct Produce {
//! #         #[serde(rename = "Item")]
//! #         fruit: &'static str,
//! #
//! #         #[serde(rename = "Price")]
//! #         cost: f64,
//! #     }
//! #
//! #     // Create some data instances.
//! #     let item1 = Produce {
//! #         fruit: "Peach",
//! #         cost: 1.05,
//! #     };
//! #
//! #     let item2 = Produce {
//! #         fruit: "Plum",
//! #         cost: 0.15,
//! #     };
//! #
//! #     let item3 = Produce {
//! #         fruit: "Pear",
//! #         cost: 0.75,
//! #     };
//! #
//!     // Set up the custom headers.
//!     let custom_headers =
//!         [CustomSerializeField::new("Price").set_column_format(currency_format)];
//!
//!     let header_options = SerializeFieldOptions::new()
//!         .set_header_format(header_format)
//!         .set_custom_headers(&custom_headers);
//!
//!     // Set the serialization location and headers.
//!     worksheet.deserialize_headers_with_options::<Produce>(1, 1, &header_options)?;
//! #
//! #     // Serialize the data.
//! #     worksheet.serialize(&item1)?;
//! #     worksheet.serialize(&item2)?;
//! #     worksheet.serialize(&item3)?;
//! #
//! #     // Save the file.
//! #     workbook.save("serialize.xlsx")?;
//! #
//! #     Ok(())
//! # }
//! ```
//!
//!
//! The following variation on the example demonstrates setting formatting for
//! the serialized values, rather than the entire column. This allows a little
//! bit more precision on cell formatting.
//!
//! ```rust
//! # // This code is available in examples/doc_worksheet_serialize_headers_format6.rs
//! #
//! # use rust_xlsxwriter::{
//! #     CustomSerializeField, Format, FormatBorder, SerializeFieldOptions, Workbook, XlsxError,
//! # };
//! # use serde::{Deserialize, Serialize};
//! #
//! # fn main() -> Result<(), XlsxError> {
//! #     let mut workbook = Workbook::new();
//! #
//! #     // Add a worksheet to the workbook.
//! #     let worksheet = workbook.add_worksheet();
//! #
//! #     // Add some formats to use with the serialization data.
//! #     let header_format = Format::new()
//! #         .set_bold()
//! #         .set_border(FormatBorder::Thin)
//! #         .set_background_color("C6EFCE");
//! #
//! #     let currency_format = Format::new().set_num_format("$0.00");
//! #
//! #     // Create a serializable struct.
//! #     #[derive(Deserialize, Serialize)]
//! #     struct Produce {
//! #         #[serde(rename = "Item")]
//! #         fruit: &'static str,
//! #
//! #         #[serde(rename = "Price")]
//! #         cost: f64,
//! #     }
//! #
//! #     // Create some data instances.
//! #     let item1 = Produce {
//! #         fruit: "Peach",
//! #         cost: 1.05,
//! #     };
//! #
//! #     let item2 = Produce {
//! #         fruit: "Plum",
//! #         cost: 0.15,
//! #     };
//! #
//! #     let item3 = Produce {
//! #         fruit: "Pear",
//! #         cost: 0.75,
//! #     };
//! #
//!     // Set up the custom headers.
//!     let custom_headers =
//!         [CustomSerializeField::new("Price").set_value_format(currency_format)];
//!
//!     let header_options = SerializeFieldOptions::new()
//!         .set_header_format(header_format)
//!         .set_custom_headers(&custom_headers);
//!
//!     // Set the serialization location and headers.
//!     worksheet.deserialize_headers_with_options::<Produce>(1, 1, &header_options)?;
//! #
//! #     // Serialize the data.
//! #     worksheet.serialize(&item1)?;
//! #     worksheet.serialize(&item2)?;
//! #     worksheet.serialize(&item3)?;
//! #
//! #     // Save the file.
//! #     workbook.save("serialize.xlsx")?;
//! #
//! #     Ok(())
//! # }
//! ```
//!
//!
//!
//!
//! ## Serializing dates and times
//!
//! Dates and times can be serialized to Excel from one of the following types:
//!
//! - [`ExcelDateTime`]: The inbuilt `rust_xlsxwriter` datetime type.
//! - [`Chrono`] naive (i.e., timezone unaware) types:
//!   - [`chrono::NaiveDateTime`]
//!   - [`chrono::NaiveDate`]
//!   - [`chrono::NaiveTime`]
//! - [`Jiff`] civil (i.e., timezone unaware) types:
//!   - [`jiff::civil::Datetime`]
//!   - [`jiff::civil::Date`]
//!   - [`jiff::civil::Time`]
//!
//! [`ExcelDateTime`]: crate::ExcelDateTime
//!
//! [`Chrono`]: https://docs.rs/chrono/latest/chrono
//! [`chrono::NaiveDate`]:
//!     https://docs.rs/chrono/latest/chrono/naive/struct.NaiveDate.html
//! [`chrono::NaiveTime`]:
//!     https://docs.rs/chrono/latest/chrono/naive/struct.NaiveTime.html
//! [`chrono::NaiveDateTime`]:
//!     https://docs.rs/chrono/latest/chrono/naive/struct.NaiveDateTime.html
//!
//! [`Jiff`]: https://docs.rs/jiff/latest/jiff
//! [`jiff::civil::Datetime`]:
//!     https://docs.rs/jiff/latest/jiff/civil/struct.DateTime.html
//! [`jiff::civil::Date`]:
//!     https://docs.rs/jiff/latest/jiff/civil/struct.Date.html
//! [`jiff::civil::Time`]:
//!     https://docs.rs/jiff/latest/jiff/civil/struct.Time.html
//!
//! The [`ExcelDateTime`] type is serialized automatically since it implements
//! the [`Serialize`] trait. The [`Chrono`] and [`Jiff`] types also implement
//! [`Serialize`] but they will serialize to a string. To serialize them to an
//! Excel number/datetime format requires a serializing function like
//! [`Utility::serialize_datetime_to_excel()`](crate::utility::serialize_datetime_to_excel())
//! (as shown in the example below) or
//! [`Utility::serialize_option_datetime_to_excel()`](crate::utility::serialize_option_datetime_to_excel()).
//!
//! Excel datetimes also need a number format to display them as a date/time
//! since they are stored as `f64` values. See [Datetimes in
//! Excel](crate::ExcelDateTime#datetimes-in-excel) and the previous section on
//! adding formatting.
//!
//! Note, Excel doesn't use time zones or try to convert or encode time zone
//! information in any way, so they aren't supported by `rust_xlsxwriter`.
//!
//! ### Examples of serializing dates
//!
//! The following example demonstrates serializing instances of a Serde derived
//! data structure with [`ExcelDateTime`] fields.
//!
//! ```rust
//! # // This code is available in examples/doc_worksheet_serialize_datetime1.rs
//! #
//! use rust_xlsxwriter::{
//!     CustomSerializeField, ExcelDateTime, Format, FormatBorder,
//!     SerializeFieldOptions, Workbook, XlsxError,
//! };
//! use serde::{Deserialize, Serialize};
//!
//! fn main() -> Result<(), XlsxError> {
//!     let mut workbook = Workbook::new();
//!
//!     // Add a worksheet to the workbook.
//!     let worksheet = workbook.add_worksheet();
//!
//!     // Widen the date column for clarity.
//!     worksheet.set_column_width(1, 12)?;
//!
//!     // Add some formats to use with the serialization data.
//!     let header_format = Format::new()
//!         .set_bold()
//!         .set_border(FormatBorder::Thin)
//!         .set_background_color("C6E0B4");
//!
//!     let date_format = Format::new().set_num_format("yyyy/mm/dd");
//!
//!     // Create a serializable struct.
//!     #[derive(Deserialize, Serialize)]
//!     struct Student<'a> {
//!         name: &'a str,
//!         dob: ExcelDateTime,
//!         id: u32,
//!     }
//!
//!     let students = [
//!         Student {
//!             name: "Aoife",
//!             dob: ExcelDateTime::from_ymd(1998, 1, 12)?,
//!             id: 564351,
//!         },
//!         Student {
//!             name: "Caoimhe",
//!             dob: ExcelDateTime::from_ymd(2000, 5, 1)?,
//!             id: 443287,
//!         },
//!     ];
//!
//!     // Set up the start location and headers of the data to be serialized. Note,
//!     // we need to add a cell format for the datetime data.
//!     let custom_headers = [
//!         CustomSerializeField::new("name").rename("Student"),
//!         CustomSerializeField::new("dob")
//!             .rename("Birthday")
//!             .set_value_format(date_format),
//!         CustomSerializeField::new("id").rename("ID"),
//!     ];
//!     let header_options = SerializeFieldOptions::new()
//!         .set_header_format(header_format)
//!         .set_custom_headers(&custom_headers);
//!
//!     worksheet.deserialize_headers_with_options::<Student>(0, 0, &header_options)?;
//!
//!     // Serialize the data.
//!     worksheet.serialize(&students)?;
//!
//!     // Save the file.
//!     workbook.save("serialize.xlsx")?;
//!
//!     Ok(())
//! }
//! ```
//!
//! Output file:
//!
//! <img
//! src="https://rustxlsxwriter.github.io/images/worksheet_serialize_datetime1.png">
//!
//! Here is an example which serializes a struct with a [`chrono::NaiveDate`]
//! field. The output is the same as the previous example.
//!
//! ```ignore
//! # // This code is available in examples/doc_worksheet_serialize_datetime2.rs
//! #
//! use rust_xlsxwriter::utility::serialize_datetime_to_excel;
//!
//! fn main() -> Result<(), XlsxError> {
//!     let mut workbook = Workbook::new();
//!
//!     // Add a worksheet to the workbook.
//!     let worksheet = workbook.add_worksheet();
//!
//!     // Widen the date column for clarity.
//!     worksheet.set_column_width(1, 12)?;
//!
//!     // Add some formats to use with the serialization data.
//!     let header_format = Format::new()
//!         .set_bold()
//!         .set_border(FormatBorder::Thin)
//!         .set_background_color("C6E0B4");
//!
//!     let date_format = Format::new().set_num_format("yyyy/mm/dd");
//!
//!     // Create a serializable struct.
//!     #[derive(Deserialize, Serialize)]
//!     struct Student<'a> {
//!         name: &'a str,
//!
//!         // Note, we add a `rust_xlsxwriter` function to serialize the date.
//!         #[serde(serialize_with = "serialize_datetime_to_excel")]
//!         dob: NaiveDate,
//!
//!         id: u32,
//!     }
//! #
//! #     let students = [
//! #         Student {
//! #             name: "Aoife",
//! #             dob: NaiveDate::from_ymd_opt(1998, 1, 12).unwrap(),
//! #             id: 564351,
//! #         },
//! #         Student {
//! #             name: "Caoimhe",
//! #             dob: NaiveDate::from_ymd_opt(2000, 5, 1).unwrap(),
//! #             id: 443287,
//! #         },
//! #     ];
//! #
//! #     // Set up the start location and headers of the data to be serialized. Note,
//! #     // we need to add a cell format for the datetime data.
//! #     let custom_headers = [
//! #         CustomSerializeField::new("name").rename("Student"),
//! #         CustomSerializeField::new("dob")
//! #             .rename("Birthday")
//! #             .set_value_format(&date_format),
//! #         CustomSerializeField::new("id").rename("ID"),
//! #     ];
//! #     let header_options = SerializeFieldOptions::new()
//! #         .set_header_format(&header_format)
//! #         .set_custom_headers(&custom_headers);
//! #
//! #     worksheet.deserialize_headers_with_options::<Student>(0, 0, &header_options)?;
//! #
//! #     // Serialize the data.
//! #     worksheet.serialize(&students)?;
//! #
//! #     // Save the file.
//! #     workbook.save("serialize.xlsx")?;
//!
//!     // ...
//!
//!     Ok(())
//! }
//! ```
//!
//!
//!
//! ## Controlling Excel output via `XlsxSerialize` and struct attributes
//!
//! In the sections above, we saw how to use [Serde
//! Attributes](https://serde.rs/attributes.html) to control some aspects for
//! the serialization output.
//!
//! It is also possible to use the `XlsxSerialize` derive trait and associate
//! attributes to set `rust_xlsxwriter` specific formatting and options. For
//! example:
//!
//!
//! ```
//! # // This code is available in examples/doc_xlsxserialize_intro.rs
//! #
//! use rust_xlsxwriter::{Workbook, XlsxError, XlsxSerialize};
//! use serde::Serialize;
//!
//! fn main() -> Result<(), XlsxError> {
//!     let mut workbook = Workbook::new();
//!
//!     // Add a worksheet to the workbook.
//!     let worksheet = workbook.add_worksheet();
//!
//!     // Create a serializable struct.
//!     #[derive(XlsxSerialize, Serialize)]
//!     #[xlsx(header_format = Format::new().set_bold())]
//!     struct Produce {
//!         #[xlsx(rename = "Item")]
//!         #[xlsx(column_width = 12.0)]
//!         fruit: &'static str,
//!
//!         #[xlsx(rename = "Price", num_format = "$0.00")]
//!         cost: f64,
//!     }
//!
//!     // Create some data instances.
//!     let item1 = Produce {
//!         fruit: "Peach",
//!         cost: 1.05,
//!     };
//!
//!     let item2 = Produce {
//!         fruit: "Plum",
//!         cost: 0.15,
//!     };
//!
//!     let item3 = Produce {
//!         fruit: "Pear",
//!         cost: 0.75,
//!     };
//!
//!     // Set the serialization location and headers.
//!     worksheet.set_serialize_headers::<Produce>(0, 0)?;
//!
//!     // Serialize the data.
//!     worksheet.serialize(&item1)?;
//!     worksheet.serialize(&item2)?;
//!     worksheet.serialize(&item3)?;
//!
//!     // Save the file to disk.
//!     workbook.save("serialize.xlsx")?;
//!
//!     Ok(())
//! }
//! ```
//!
//! Note the change of column width in Column A, the renamed headers and the
//! currency format in Column B numbers.
//!
//! <img src="https://rustxlsxwriter.github.io/images/xlsxserialize_intro.png">
//!
//! `XlsxSerializer` provides the same formatting functionality as
//! [`SerializeFieldOptions`] and [`CustomSerializeField`] (in fact it used them
//! in the background). The advantage of using `XlsxSerializer` is that the
//! formatting output can be kept with the data format and seen in the same
//! context. Some users may find this to be a cleaner abstraction.
//!
//!
//!
//!
//! ## The `XlsxSerializer` attributes
//!
//! The `XlsxSerializer` derived trait adds a wrapper around a Serde
//! serializable struct to add `rust_xlsxwriter` specific formatting options. It
//! achieves this via the `rust_xlsxwriter` [`SerializeFieldOptions`] and
//! [`CustomSerializeField`] serialization configuration structs. It is
//! available when you enable the `serde` feature.
//!
//! As in Serde, the [attributes](https://serde.rs/attributes.html) are divided
//! into "Container Attributes" which apply to the entire struct and "Field
//! Attributes" which apply to individual fields. In an Excel context, the
//! container attributes apply to all headers and field attributes apply to the
//! individual headers and the data below them.
//!
//! In order to demonstrate each attribute and its effect, we will use
//! variations of the following example with the relevant attribute applied in
//! the next sections.
//!
//! ### Base example (without attributes applied)
//!
//! ```
//! # // This code is available in examples/doc_xlsxserialize_base.rs
//! #
//! use rust_xlsxwriter::{Workbook, XlsxError, XlsxSerialize};
//! use serde::Serialize;
//!
//! fn main() -> Result<(), XlsxError> {
//!     let mut workbook = Workbook::new();
//!
//!     // Add a worksheet to the workbook.
//!     let worksheet = workbook.add_worksheet();
//!
//!     // Create a serializable struct.
//!     #[derive(XlsxSerialize, Serialize)]
//!     struct Produce {
//!         fruit: &'static str,
//!         cost: f64,
//!     }
//!
//!     // Create some data instances.
//!     let items = [
//!         Produce {
//!             fruit: "Peach",
//!             cost: 1.05,
//!         },
//!         Produce {
//!             fruit: "Plum",
//!             cost: 0.15,
//!         },
//!         Produce {
//!             fruit: "Pear",
//!             cost: 0.75,
//!         },
//!     ];
//!
//!     // Set the serialization location and headers.
//!     worksheet.set_serialize_headers::<Produce>(0, 0)?;
//!
//!     // Serialize the data.
//!     worksheet.serialize(&items)?;
//!
//!     // Save the file to disk.
//!     workbook.save("serialize.xlsx")?;
//!
//!     Ok(())
//! }
//! ```
//!
//! ### Container `xlsx` attributes
//!
//! The following are the "Container" attributes supported by `XlsxSerializer`:
//!
//! - `#[xlsx(header_format = Format)`
//!
//!   The `header_format` container attribute sets the [`Format`] property for
//!   headers. See the [Working with attribute
//!   Formats](#working-with-attribute-formats) section below for information on
//!   handling formats.
//!
//!   ```
//!   # use rust_xlsxwriter::XlsxSerialize;
//!   # use serde::Serialize;
//!   #
//!   # fn main() {
//!         #[derive(XlsxSerialize, Serialize)]
//!         #[xlsx(header_format = Format::new()
//!                .set_bold()
//!                .set_border(FormatBorder::Thin)
//!                .set_background_color("C6EFCE"))]
//!         struct Produce {
//!             fruit: &'static str,
//!             cost: f64,
//!         }
//!   # }
//!   ```
//!
//! <img
//!   src="https://rustxlsxwriter.github.io/images/xlsxserialize_header_format.png">
//!
//!
//! - `#[xlsx(hide_headers)`
//!
//!   The `hide_headers` container attribute hides the serialization headers:
//!
//!   ```
//!   # use rust_xlsxwriter::XlsxSerialize;
//!   # use serde::Serialize;
//!   #
//!   # fn main() {
//!         #[derive(XlsxSerialize, Serialize)]
//!         #[xlsx(hide_headers)]
//!         struct Produce {
//!             fruit: &'static str,
//!             cost: f64,
//!         }
//!   # }
//!   ```
//!
//!   <img
//!   src="https://rustxlsxwriter.github.io/images/xlsxserialize_hide_headers.png">
//!
//!
//! - `#[xlsx(table_default)`
//!
//!   The `table_default` container attribute adds a worksheet [`Table`]
//!   structure with default formatting to the serialized area:
//!
//!   ```
//!   # use rust_xlsxwriter::XlsxSerialize;
//!   # use serde::Serialize;
//!   #
//!   # fn main() {
//!         #[derive(XlsxSerialize, Serialize)]
//!         #[xlsx(table_default)]
//!         struct Produce {
//!             fruit: &'static str,
//!             cost: f64,
//!         }
//!   # }
//!   ```
//!
//!   <img
//!   src="https://rustxlsxwriter.github.io/images/xlsxserialize_table_default.png">
//!
//!
//! - `#[xlsx(table_style)`
//!
//!   The `table_style` container attribute adds a worksheet [`Table`] structure
//!   with a user specified [`TableStyle`] to the serialized area:
//!
//!   ```
//!   # use rust_xlsxwriter::XlsxSerialize;
//!   # use serde::Serialize;
//!   #
//!   # fn main() {
//!         #[derive(XlsxSerialize, Serialize)]
//!         #[xlsx(table_style = TableStyle::Medium10)]
//!         struct Produce {
//!             fruit: &'static str,
//!             cost: f64,
//!         }
//!   # }
//!   ```
//!
//!   <img
//!   src="https://rustxlsxwriter.github.io/images/xlsxserialize_table_style.png">
//!
//!
//! - `#[xlsx(table = Table)`
//!
//!   The `table` container attribute adds a user defined worksheet [`Table`]
//!   structure to the serialized area:
//!
//!   ```
//!   # use rust_xlsxwriter::XlsxSerialize;
//!   # use serde::Serialize;
//!   #
//!   # fn main() {
//!         #[derive(XlsxSerialize, Serialize)]
//!         #[xlsx(table = Table::new())]
//!         struct Produce {
//!             fruit: &'static str,
//!             cost: f64,
//!         }
//!   # }
//!   ```
//!
//!   <img
//!   src="https://rustxlsxwriter.github.io/images/xlsxserialize_table_default.png">
//!
//!   See the [Working with attribute Formats](#working-with-attribute-formats)
//!   section below for information on how to wrap complex objects like
//!   [`Format`] or [`Table`] in a function so it can be used as an attribute
//!   parameter.
//!
//!
//! ### Field `xlsx` attributes
//!
//! The following are the "Field" attributes supported by `XlsxSerializer`:
//!
//! - `#[xlsx(rename = "")`
//!
//!   The `rename` field attribute renames the Excel header. This is similar to
//!   the `#[serde(rename = "")` field attribute except that it doesn't rename
//!   the field for other types of serialization.
//!
//!   ```
//!   # use rust_xlsxwriter::XlsxSerialize;
//!   # use serde::Serialize;
//!   #
//!   # fn main() {
//!         #[derive(XlsxSerialize, Serialize)]
//!         struct Produce {
//!             #[xlsx(rename = "Item")]
//!             fruit: &'static str,
//!
//!             #[xlsx(rename = "Price")]
//!             cost: f64,
//!         }
//!   # }
//!   ```
//!
//!   <img
//!   src="https://rustxlsxwriter.github.io/images/xlsxserialize_rename.png">
//!
//!
//! - `#[xlsx(num_format = "")`
//!
//!   The `num_format` field attribute sets the property to change the number
//!   formatting of the output. It is a syntactic shortcut for
//!   [`Format::set_num_format()`].
//!
//!   ```
//!   # use rust_xlsxwriter::XlsxSerialize;
//!   # use serde::Serialize;
//!   #
//!   # fn main() {
//!         #[derive(XlsxSerialize, Serialize)]
//!         struct Produce {
//!             fruit: &'static str,
//!
//!             #[xlsx(num_format = "$0.00")]
//!             cost: f64,
//!         }
//!   # }
//!   ```
//!
//!   <img
//!   src="https://rustxlsxwriter.github.io/images/xlsxserialize_num_format.png">
//!
//!
//! - `#[xlsx(value_format = Format)`
//!
//!   The `value_format` field attribute sets the [`Format`] property for the
//!   fields below the header.
//!
//!   See the [Working with attribute Formats](#working-with-attribute-formats)
//!   section below for information on handling formats.
//!
//!   ```
//!   # use rust_xlsxwriter::XlsxSerialize;
//!   # use serde::Serialize;
//!   #
//!   # fn main() {
//!         #[derive(XlsxSerialize, Serialize)]
//!         struct Produce {
//!             #[xlsx(value_format = Format::new().set_font_color("#FF0000"))]
//!             fruit: &'static str,
//!             cost: f64,
//!         }
//!   # }
//!   ```
//!
//!   <img
//!   src="https://rustxlsxwriter.github.io/images/xlsxserialize_value_format.png">
//!
//!
//! - `#[xlsx(column_format = Format)`
//!
//!   The `column_format` field attribute is similar to the previous
//!   `value_format` attribute except that it sets the format for the entire
//!   column, including any data added manually below the serialized data.
//!
//!   <br>
//!
//! - `#[xlsx(header_format = Format)`
//!
//!   The `header_format` field attribute sets the [`Format`] property for the
//!   the header. It is similar to the container method of the same name except
//!   it only sets the format or one header:
//!
//!   ```
//!   # use rust_xlsxwriter::XlsxSerialize;
//!   # use serde::Serialize;
//!   #
//!   # fn main() {
//!         #[derive(XlsxSerialize, Serialize)]
//!         struct Produce {
//!             fruit: &'static str,
//!
//!             #[xlsx(header_format = Format::new().set_bold().set_font_color("#FF0000"))]
//!             cost: f64,
//!         }
//!   # }
//!   ```
//!
//!   <img
//!   src="https://rustxlsxwriter.github.io/images/xlsxserialize_field_header_format.png">
//!
//!
//! - `#[xlsx(column_width = float)`
//!
//!   The `column_width` field attribute sets the column width in character
//!   units.
//!
//!   ```
//!   # use rust_xlsxwriter::XlsxSerialize;
//!   # use serde::Serialize;
//!   #
//!   # fn main() {
//!         #[derive(XlsxSerialize, Serialize)]
//!         struct Produce {
//!             fruit: &'static str,
//!             #[xlsx(column_width = 20.0)]
//!             cost: f64,
//!         }
//!   # }
//!   ```
//!
//!   <img
//!   src="https://rustxlsxwriter.github.io/images/xlsxserialize_column_width.png">
//!
//!
//!
//! - `#[xlsx(column_width_pixels = int)`
//!
//!   The `column_width_pixels` field attribute field attribute is similar to
//!   the previous `column_width` attribute except that the width is specified
//!   in integer pixel units.
//!
//!   <br>
//!
//!
//!
//!
//! - `#[xlsx(skip)`
//!
//!   The `skip` field attribute skips writing the field to the target Excel
//!   file.  This is similar to the `#[serde(skip)` field attribute except that
//!   it doesn't skip the field for other types of serialization.
//!
//!   ```
//!   # use rust_xlsxwriter::XlsxSerialize;
//!   # use serde::Serialize;
//!   #
//!   # fn main() {
//!         #[derive(XlsxSerialize, Serialize)]
//!         struct Produce {
//!             fruit: &'static str,
//!
//!             #[xlsx(skip)]
//!             cost: f64,
//!         }
//!   # }
//!   ```
//!
//!   <img src="https://rustxlsxwriter.github.io/images/xlsxserialize_skip.png">
//!
//!
//! Note, if required you can group more than one attribute
//!
//! ```text
//! #[xlsx(rename = "Item", column_width = 20.0)]
//! ```
//!
//! ### Working with attribute Formats
//!
//! When working with `XlsxSerialize` attributes that deal with [`Format`]
//! objects the definition can become quite long for an attribute value:
//!
//! ```
//! # use rust_xlsxwriter::XlsxSerialize;
//! # use serde::Serialize;
//! #
//! # fn main() {
//!       #[derive(XlsxSerialize, Serialize)]
//!       #[xlsx(header_format = Format::new()
//!              .set_bold()
//!              .set_border(FormatBorder::Thin)
//!              .set_background_color("C6EFCE"))]
//!       struct Produce {
//!           fruit: &'static str,
//!           cost: f64,
//!       }
//! # }
//! ```
//!
//! <br>
//!
//! You might, in this case, be tempted to define the format in another part of
//! your code and use a variable to define the format:
//!
//! ```compile_fail
//! # use rust_xlsxwriter::{Format, FormatBorder, XlsxSerialize};
//! # use serde::Serialize;
//! #
//! # fn main() {
//!     let my_header_format = Format::new()
//!         .set_bold()
//!         .set_border(FormatBorder::Thin)
//!         .set_background_color("C6EFCE");
//!
//!     #[derive(XlsxSerialize, Serialize)]
//!     #[xlsx(header_format = &my_header_format)] // Won't work.
//!     struct Produce {
//!         fruit: &'static str,
//!         cost: f64,
//!     }
//! # }
//! ```
//!
//! <br>
//!
//! However, this won't work because Rust derive/proc macros are compiled
//! statically, and `&header_format` is a dynamic variable.
//!
//! A workaround for this is to define any formats you wish to use in functions:
//!
//! ```
//! # // This code is available in examples/doc_xlsxserialize_header_format_reuse.rs
//! #
//! # use rust_xlsxwriter::{FormatBorder, Workbook, XlsxError, XlsxSerialize, Format};
//! # use serde::Serialize;
//! #
//! # fn main() -> Result<(), XlsxError> {
//! #     let mut workbook = Workbook::new();
//! #
//! #     // Add a worksheet to the workbook.
//! #     let worksheet = workbook.add_worksheet();
//! #
//!     fn my_header_format() -> Format {
//!         Format::new()
//!             .set_bold()
//!             .set_border(FormatBorder::Thin)
//!             .set_background_color("C6EFCE")
//!     }
//!
//!     #[derive(XlsxSerialize, Serialize)]
//!     #[xlsx(header_format = my_header_format())]
//!     struct Produce {
//!         fruit: &'static str,
//!         cost: f64,
//!     }
//! #
//! #     // Create some data instances.
//! #     let items = [
//! #         Produce {
//! #             fruit: "Peach",
//! #             cost: 1.05,
//! #         },
//! #         Produce {
//! #             fruit: "Plum",
//! #             cost: 0.15,
//! #         },
//! #         Produce {
//! #             fruit: "Pear",
//! #             cost: 0.75,
//! #         },
//! #     ];
//! #
//! #     // Set the serialization location and headers.
//! #     worksheet.set_serialize_headers::<Produce>(0, 0)?;
//! #
//! #     // Serialize the data.
//! #     worksheet.serialize(&items)?;
//! #
//! #     // Save the file to disk.
//! #     workbook.save("serialize.xlsx")?;
//! #
//! #     Ok(())
//! # }
//! ```
//!
//! Output file:
//!
//! <img
//! src="https://rustxlsxwriter.github.io/images/xlsxserialize_header_format_reuse.png">
//!
//!
//!
//!
//! ## Limitations of serializing to Excel
//!
//! The cell/grid format of Excel sets a physical limitation on what can be
//! serialized to a worksheet. Unlike other formats such as JSON or XML, you
//! cannot serialize arbitrary nested data to Excel without making some
//! concessions to either the format or the contents of the data. When
//! serializing data to Excel via `rust_xlsxwriter`, it is best to consider what
//! that data will look like while designing your serialization.
//!
//! It is only possible to serialize structs or a vector of struct values.
//! Within a struct most native Rust types are supported (where there is some
//! mapping to an Excel cell type), as well as the Date/Time types listed above.
//!
//! Maps are not supported because they don't have a fixed schema that can be
//! mapped to a 2D grid of cells and the order of the fields is not guaranteed.
//! As a side effect of this it also not possible to serialize structs that use
//! the Serde [`flatten`] attribute, since Serde converts the fixed set of named
//! fields into a dynamically sized map. However, a struct that contains a map
//! field can be serialized if the field is omitted via one of the [field
//! skipping](#skipping-fields-when-serializing) methods such as the
//! `#[serde(skip)]`,`#[xlsx(skip)] or [`CustomSerializeField::skip()`]; or by
//! excluding it via [`SerializeFieldOptions::use_custom_headers_only()`].
//!
//! [`flatten`]: https://serde.rs/field-attrs.html#flatten
//! [Serde data model]: https://serde.rs/data-model.html
//!
//! Finally, if you hit some serialization limitation using `rust_xlsxwriter`,
//! remember that there are other non-serialization options available to use in
//! the standard [`Worksheet`] API to write scalar, vector, and matrix data
//! types:
//!
//! - [`Worksheet::write()`]
//! - [`Worksheet::write_row()`]
//! - [`Worksheet::write_column()`]
//! - [`Worksheet::write_row_matrix()`]
//! - [`Worksheet::write_column_matrix()`]
//!
//! Magic is great, but the direct approach will also work. Remember Terry
//! Pratchett's witches.
//!
#![warn(missing_docs)]

use std::collections::HashMap;
use std::sync::Arc;

use crate::{ColNum, Format, RowNum, Table, TableStyle, Worksheet, XlsxError};
use serde::de::Visitor;
use serde::{ser, Deserialize, Deserializer, Serialize};

// Convenience tuple struct Table data used for serialization formatting.
pub(crate) struct TableData(
    pub(crate) RowNum,
    pub(crate) ColNum,
    pub(crate) RowNum,
    pub(crate) ColNum,
    pub(crate) Table,
);

// -----------------------------------------------------------------------
// SerializerState, a struct to maintain row/column state and other metadata
// between serialized writes. This avoids passing around cell location
// information in the serializer.
// -----------------------------------------------------------------------
pub(crate) struct SerializerState {
    pub(crate) structs: HashMap<String, SerializationHeaderConfig>,
    pub(crate) current_struct: String,
    pub(crate) current_field: String,
}

impl SerializerState {
    // Create a new SerializerState struct.
    pub(crate) fn new() -> SerializerState {
        SerializerState {
            structs: HashMap::new(),
            current_struct: String::new(),
            current_field: String::new(),
        }
    }

    // Check if the current struct/field have been selected to be serialized by
    // the user. If it has then return the row value for the next `write()` call.
    pub(crate) fn current_state(&mut self) -> Result<(RowNum, ColNum, Arc<Option<Format>>), ()> {
        let Some(header_config) = self.structs.get_mut(&self.current_struct) else {
            return Err(());
        };

        let Some(field) = header_config.fields.get_mut(&self.current_field) else {
            return Err(());
        };

        // Set the "current" cell values used to write the serialized data.
        let row = header_config.max_row - 1;
        let col = field.col;
        let value_format = Arc::clone(&field.value_format);

        Ok((row, col, value_format))
    }

    // Check if the current field has been skipped from serialization via the
    // `#[xlsx(skip)]` attribute, `CustomSerializeField::skip()`, or by omitting
    // it from `SerializeFieldOptions::use_custom_headers_only()` headers.
    pub(crate) fn is_unselected_field(&self) -> bool {
        match self.structs.get(&self.current_struct) {
            Some(header_config) => !header_config.fields.contains_key(&self.current_field),
            None => false,
        }
    }

    // Store the name and max row of the current struct being serialized.
    pub(crate) fn set_current_struct(&mut self, struct_name: &str) {
        if struct_name != self.current_struct {
            self.current_struct = struct_name.to_string();
        }

        // Increment the max row every time we serialize a new struct instance.
        let Some(header_config) = self.structs.get_mut(&self.current_struct) else {
            return;
        };
        header_config.max_row += 1;
    }

    // Get dimensions of a serialization area. This is the internal function for
    // worksheet.get_serialize_dimensions().
    pub(crate) fn get_dimensions(
        &mut self,
        name: &str,
    ) -> Result<(RowNum, ColNum, RowNum, ColNum), XlsxError> {
        let Some(header_config) = self.structs.get(name) else {
            return Err(XlsxError::ParameterError(format!(
                "Unknown serialized struct '{name}'"
            )));
        };

        Ok((
            header_config.min_row,
            header_config.min_col,
            header_config.max_row - 1,
            header_config.max_col,
        ))
    }

    // Get dimensions of a column in a serialization area. This is the internal
    // function for worksheet.get_serialize_column_dimensions().
    pub(crate) fn get_column_dimensions(
        &mut self,
        struct_name: &str,
        field_name: &str,
    ) -> Result<(RowNum, ColNum, RowNum, ColNum), XlsxError> {
        let Some(header_config) = self.structs.get(struct_name) else {
            return Err(XlsxError::ParameterError(format!(
                "Unknown serialized struct '{struct_name}'"
            )));
        };

        let Some(field) = header_config.fields.get(field_name) else {
            return Err(XlsxError::ParameterError(format!(
                "Unknown serialized field '{field_name}'"
            )));
        };

        Ok((
            header_config.min_row,
            field.col,
            header_config.max_row - 1,
            field.col,
        ))
    }

    // Get all/any tables defined for serialization areas.
    pub(crate) fn get_tables(&mut self) -> Vec<TableData> {
        let mut tables = vec![];

        for header_config in self.structs.values_mut() {
            if let Some(table) = header_config.get_table() {
                tables.push(table);
            }
        }

        tables
    }
}

// -----------------------------------------------------------------------
// HeaderConfig, a struct to capture the metadata for fields associated
// with a struct.
// -----------------------------------------------------------------------
pub(crate) struct SerializationHeaderConfig {
    pub(crate) fields: HashMap<String, CustomSerializeField>,
    pub(crate) min_row: RowNum,
    pub(crate) min_col: ColNum,
    pub(crate) max_row: RowNum,
    pub(crate) max_col: ColNum,
    pub(crate) table: Option<Table>,
}

impl SerializationHeaderConfig {
    // Get table object and dimensions for the a serialization area.
    pub(crate) fn get_table(&mut self) -> Option<TableData> {
        let table = self.table.take();

        match table {
            Some(table) => Some(TableData(
                self.min_row,
                self.min_col,
                self.max_row - 1,
                self.max_col,
                table,
            )),
            None => None,
        }
    }
}

// -----------------------------------------------------------------------
// SerializeFieldOptions.
// -----------------------------------------------------------------------

/// The `SerializeFieldOptions` struct represents custom field/header options.
///
/// `SerializeFieldOptions` can be used to set column headers to map serialized
/// data to. It allows you to reorder, rename, format or skip headers and also
/// define formatting for field values.
///
/// It is used in conjunction with the [`CustomSerializeField`] struct and
/// [`Worksheet::deserialize_headers_with_options()`] and
/// [`Worksheet::serialize_headers_with_options()`] methods.
///
/// See [Working with Serde](crate::serializer) for an introduction to
/// serialization with `rust_xlsxwriter`.
///
/// # Examples
///
/// The following example demonstrates serializing instances of a Serde derived
/// data structure to a worksheet with custom headers and cell formatting.
///
/// ```
/// # // This code is available in examples/doc_worksheet_serialize_headers_custom.rs
/// #
/// # use rust_xlsxwriter::{
/// #     CustomSerializeField, Format, FormatBorder, SerializeFieldOptions, Workbook, XlsxError,
/// # };
/// # use serde::{Deserialize, Serialize};
/// #
/// # fn main() -> Result<(), XlsxError> {
/// #     let mut workbook = Workbook::new();
/// #
/// #     // Add a worksheet to the workbook.
/// #     let worksheet = workbook.add_worksheet();
/// #
/// #     // Add some formats to use with the serialization data.
/// #     let header_format = Format::new()
/// #         .set_bold()
/// #         .set_border(FormatBorder::Thin)
/// #         .set_background_color("C6EFCE");
/// #
/// #     let currency_format = Format::new().set_num_format("$0.00");
/// #
/// #     // Create a serializable struct.
///     #[derive(Deserialize, Serialize)]
///     struct Produce {
///         fruit: &'static str,
///         cost: f64,
///     }
///
///     // Create some data instances.
///     let item1 = Produce {
///         fruit: "Peach",
///         cost: 1.05,
///     };
///
///     let item2 = Produce {
///         fruit: "Plum",
///         cost: 0.15,
///     };
///
///     let item3 = Produce {
///         fruit: "Pear",
///         cost: 0.75,
///     };
///
///     // Set up the custom headers.
///     let custom_headers = [
///         CustomSerializeField::new("fruit")
///             .rename("Item"),
///         CustomSerializeField::new("cost")
///             .rename("Price")
///             .set_value_format(currency_format),
///     ];
///
///     let header_options = SerializeFieldOptions::new()
///         .set_header_format(header_format)
///         .set_custom_headers(&custom_headers);
///
///     // Set the serialization location and custom headers.
///     worksheet.deserialize_headers_with_options::<Produce>(1, 1, &header_options)?;
///
///     // Serialize the data.
///     worksheet.serialize(&item1)?;
///     worksheet.serialize(&item2)?;
///     worksheet.serialize(&item3)?;
/// #
/// #     // Save the file.
/// #     workbook.save("serialize.xlsx")?;
/// #
/// #     Ok(())
/// # }
/// ```
///
/// Output file:
///
/// <img src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers_custom.png">
///
#[derive(Clone)]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
pub struct SerializeFieldOptions {
    pub(crate) struct_name: String,
    pub(crate) header_format: Option<Format>,
    pub(crate) has_headers: bool,
    pub(crate) custom_headers: Vec<CustomSerializeField>,
    pub(crate) use_custom_headers_only: bool,
    pub(crate) table: Option<Table>,
}

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

impl SerializeFieldOptions {
    /// Create serialization header options.
    ///
    /// Create a `SerializeFieldOptions` struct to be used with the
    /// [`Worksheet::deserialize_headers_with_options()`] or
    /// [`Worksheet::serialize_headers_with_options()`] methods.
    ///
    /// This can be used to set or skip column headers as well as specifying
    /// column and field specific formatting.
    ///
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn new() -> SerializeFieldOptions {
        SerializeFieldOptions {
            struct_name: String::new(),
            header_format: None,
            has_headers: true,
            custom_headers: vec![],
            use_custom_headers_only: false,
            table: None,
        }
    }

    /// Set the header format for a serialization headers.
    ///
    /// See [`Format`] for more information on formatting.
    ///
    /// # Parameters
    ///
    /// - `format`: The [`Format`] property for the header.
    ///
    ///
    /// # Examples
    ///
    /// The following example demonstrates formatting headers during serialization.
    ///
    ///
    /// ```
    /// # // This code is available in examples/doc_worksheet_serialize_headers_format2.rs
    /// #
    /// # use rust_xlsxwriter::{Format, FormatBorder, SerializeFieldOptions, Workbook, XlsxError};
    /// # use serde::Serialize;
    /// #
    /// # fn main() -> Result<(), XlsxError> {
    /// #     let mut workbook = Workbook::new();
    /// #
    /// #     // Add a worksheet to the workbook.
    /// #     let worksheet = workbook.add_worksheet();
    /// #
    ///     // Set a header format.
    ///     let header_format = Format::new()
    ///         .set_bold()
    ///         .set_border(FormatBorder::Thin)
    ///         .set_background_color("C6EFCE");
    ///
    ///     // Create a serializable struct.
    ///     #[derive(Serialize)]
    ///     struct Produce {
    ///         fruit: &'static str,
    ///         cost: f64,
    ///     }
    ///
    ///     // Create some data instances.
    ///     let item1 = Produce {
    ///         fruit: "Peach",
    ///         cost: 1.05,
    ///     };
    ///
    ///     let item2 = Produce {
    ///         fruit: "Plum",
    ///         cost: 0.15,
    ///     };
    ///
    ///     let item3 = Produce {
    ///         fruit: "Pear",
    ///         cost: 0.75,
    ///     };
    ///
    ///     // Set the serialization location and headers.
    ///     let header_options = SerializeFieldOptions::new().set_header_format(header_format);
    ///
    ///     worksheet.serialize_headers_with_options(1, 1, &item1, &header_options)?;
    ///
    ///     // Serialize the data.
    ///     worksheet.serialize(&item1)?;
    ///     worksheet.serialize(&item2)?;
    ///     worksheet.serialize(&item3)?;
    /// #
    /// #     // Save the file.
    /// #     workbook.save("serialize.xlsx")?;
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Output file:
    ///
    /// <img src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers_format1.png">
    ///
    ///
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn set_header_format(mut self, format: impl Into<Format>) -> SerializeFieldOptions {
        self.header_format = Some(format.into());
        self
    }

    /// Hide all the headers.
    ///
    /// If you want to serialize data without outputting the headers above the
    /// data you can set the `hide_headers` parameters to any of the custom
    /// headers.
    ///
    /// # Parameters
    ///
    /// - `enable`: Turn the property on/off. It is off by default.
    ///
    /// # Examples
    ///
    /// The following example demonstrates turning off headers during serialization.
    /// The example in columns "D:E" have the headers turned off.
    ///
    ///
    /// ```
    /// # // This code is available in examples/doc_worksheet_serialize_headers_format7.rs
    /// #
    /// # use rust_xlsxwriter::{SerializeFieldOptions, Workbook, XlsxError};
    /// # use serde::{Deserialize, Serialize};
    /// #
    /// # fn main() -> Result<(), XlsxError> {
    /// #     let mut workbook = Workbook::new();
    /// #
    /// #     // Add a worksheet to the workbook.
    /// #     let worksheet = workbook.add_worksheet();
    /// #
    /// #     // Create a serializable struct.
    /// #     #[derive(Deserialize, Serialize)]
    /// #     struct Produce {
    /// #         fruit: &'static str,
    /// #         cost: f64,
    /// #     }
    /// #
    /// #     // Create some data instances.
    /// #     let items = [
    /// #         Produce {
    /// #             fruit: "Peach",
    /// #             cost: 1.05,
    /// #         },
    /// #         Produce {
    /// #             fruit: "Plum",
    /// #             cost: 0.15,
    /// #         },
    /// #         Produce {
    /// #             fruit: "Pear",
    /// #             cost: 0.75,
    /// #         },
    /// #     ];
    /// #
    ///     // Default serialization with headers (fruit and cost).
    ///     worksheet.deserialize_headers::<Produce>(0, 0)?;
    ///     worksheet.serialize(&items)?;
    ///
    ///     // Serialize the data but hide headers.
    ///     let header_options = SerializeFieldOptions::new().hide_headers(true);
    ///
    ///     worksheet.deserialize_headers_with_options::<Produce>(0, 3, &header_options)?;
    ///     worksheet.serialize(&items)?;
    /// #
    /// #     // Save the file.
    /// #     workbook.save("serialize.xlsx")?;
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Output file:
    ///
    /// <img src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers_format7.png">
    ///
    ///
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn hide_headers(mut self, enable: bool) -> SerializeFieldOptions {
        self.has_headers = !enable;
        self
    }

    /// Set custom properties for serialized fields.
    ///
    /// This method allows customization of of the serialization output of
    /// individual fields. It allows you to rename field headers, set
    /// formatting for serialized values, set the column width and other properties.
    ///
    /// See [`CustomSerializeField`] for more details.
    ///
    /// # Parameters
    ///
    /// - `custom_headers`: An array of [`CustomSerializeField`] values.
    ///
    /// # Examples
    ///
    /// The following example demonstrates serializing instances of a Serde
    /// derived data structure to a worksheet with custom headers and cell
    /// formatting.
    ///
    /// ```
    /// # // This code is available in examples/doc_worksheet_serialize_headers_custom.rs
    /// #
    /// # use rust_xlsxwriter::{
    /// #     CustomSerializeField, Format, FormatBorder, SerializeFieldOptions, Workbook, XlsxError,
    /// # };
    /// # use serde::{Deserialize, Serialize};
    /// #
    /// # fn main() -> Result<(), XlsxError> {
    /// #     let mut workbook = Workbook::new();
    /// #
    /// #     // Add a worksheet to the workbook.
    /// #     let worksheet = workbook.add_worksheet();
    /// #
    /// #     // Add some formats to use with the serialization data.
    /// #     let header_format = Format::new()
    /// #         .set_bold()
    /// #         .set_border(FormatBorder::Thin)
    /// #         .set_background_color("C6EFCE");
    /// #
    /// #     let currency_format = Format::new().set_num_format("$0.00");
    /// #
    /// #     // Create a serializable struct.
    ///     #[derive(Deserialize, Serialize)]
    ///     struct Produce {
    ///         fruit: &'static str,
    ///         cost: f64,
    ///     }
    ///
    ///     // Create some data instances.
    ///     let item1 = Produce {
    ///         fruit: "Peach",
    ///         cost: 1.05,
    ///     };
    ///
    ///     let item2 = Produce {
    ///         fruit: "Plum",
    ///         cost: 0.15,
    ///     };
    ///
    ///     let item3 = Produce {
    ///         fruit: "Pear",
    ///         cost: 0.75,
    ///     };
    ///
    ///     // Set up the custom headers.
    ///     let custom_headers = [
    ///         CustomSerializeField::new("fruit")
    ///             .rename("Item"),
    ///         CustomSerializeField::new("cost")
    ///             .rename("Price")
    ///             .set_value_format(currency_format),
    ///     ];
    ///
    ///     let header_options = SerializeFieldOptions::new()
    ///         .set_header_format(header_format)
    ///         .set_custom_headers(&custom_headers);
    ///
    ///     // Set the serialization location and custom headers.
    ///     worksheet.deserialize_headers_with_options::<Produce>(1, 1, &header_options)?;
    ///
    ///     // Serialize the data.
    ///     worksheet.serialize(&item1)?;
    ///     worksheet.serialize(&item2)?;
    ///     worksheet.serialize(&item3)?;
    /// #
    /// #     // Save the file.
    /// #     workbook.save("serialize.xlsx")?;
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Output file:
    ///
    /// <img
    /// src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers_custom.png">
    ///
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn set_custom_headers(
        mut self,
        custom_headers: &[CustomSerializeField],
    ) -> SerializeFieldOptions {
        self.custom_headers = custom_headers.to_vec();
        self
    }

    /// Add a default table structure to the serialized fields.
    ///
    /// This method can be used to add a default worksheet [`Table`] structure
    /// to a serialized area.
    ///
    /// See [`Table`] for more details on worksheet tables.
    ///
    /// # Examples
    ///
    /// The following example demonstrates serializing instances of a Serde
    /// derived data structure to a worksheet and a default worksheet table
    /// structure.
    ///
    /// ```
    /// # // This code is available in examples/doc_worksheet_serialize_table1.rs
    /// #
    /// # use rust_xlsxwriter::{SerializeFieldOptions, Workbook, XlsxError};
    /// # use serde::{Deserialize, Serialize};
    /// #
    /// # fn main() -> Result<(), XlsxError> {
    /// #     let mut workbook = Workbook::new();
    /// #
    /// #     // Add a worksheet to the workbook.
    /// #     let worksheet = workbook.add_worksheet();
    /// #
    ///     // Create a serializable struct.
    ///     #[derive(Deserialize, Serialize)]
    ///     struct Produce {
    ///         fruit: &'static str,
    ///         cost: f64,
    ///     }
    ///
    ///     // Create some data instances.
    ///     let item1 = Produce {
    ///         fruit: "Peach",
    ///         cost: 1.05,
    ///     };
    ///
    ///     let item2 = Produce {
    ///         fruit: "Plum",
    ///         cost: 0.15,
    ///     };
    ///
    ///     let item3 = Produce {
    ///         fruit: "Pear",
    ///         cost: 0.75,
    ///     };
    ///
    ///     // Set the header options.
    ///     let header_options = SerializeFieldOptions::new().set_table_default();
    ///
    ///     // Set the serialization location and custom headers.
    ///     worksheet.deserialize_headers_with_options::<Produce>(0, 0, &header_options)?;
    ///
    ///     // Serialize the data.
    ///     worksheet.serialize(&item1)?;
    ///     worksheet.serialize(&item2)?;
    ///     worksheet.serialize(&item3)?;
    /// #
    /// #     // Save the file.
    /// #     workbook.save("serialize.xlsx")?;
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Output file:
    ///
    /// <img
    /// src="https://rustxlsxwriter.github.io/images/worksheet_serialize_table1.png">
    ///
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn set_table_default(mut self) -> SerializeFieldOptions {
        self.table = Some(Table::new());
        self
    }

    /// Add a table structure to the serialized fields with a user defined style.
    ///
    /// This method can be used to add a  worksheet [`Table`] structure
    /// to a serialized area with a user defined [`TableStyle`].
    ///
    /// See [`Table`] for more details on worksheet tables.
    ///
    /// # Parameters
    ///
    /// - `style`: A [`TableStyle`] enum value.
    ///
    /// # Examples
    ///
    /// The following example demonstrates serializing instances of a Serde derived
    /// data structure to a worksheet with a worksheet table and a user defined
    /// style.
    ///
    /// ```
    /// # // This code is available in examples/doc_worksheet_serialize_table2.rs
    /// #
    /// # use rust_xlsxwriter::{SerializeFieldOptions, Workbook, XlsxError};
    /// # use serde::{Deserialize, Serialize};
    /// #
    /// # fn main() -> Result<(), XlsxError> {
    /// #     let mut workbook = Workbook::new();
    /// #
    /// #     // Add a worksheet to the workbook.
    /// #     let worksheet = workbook.add_worksheet();
    /// #
    ///     // Create a serializable struct.
    ///     #[derive(Deserialize, Serialize)]
    ///     struct Produce {
    ///         fruit: &'static str,
    ///         cost: f64,
    ///     }
    ///
    ///     // Create some data instances.
    ///     let item1 = Produce {
    ///         fruit: "Peach",
    ///         cost: 1.05,
    ///     };
    ///
    ///     let item2 = Produce {
    ///         fruit: "Plum",
    ///         cost: 0.15,
    ///     };
    ///
    ///     let item3 = Produce {
    ///         fruit: "Pear",
    ///         cost: 0.75,
    ///     };
    ///
    ///     // Set the header options.
    ///     let header_options =
    ///         SerializeFieldOptions::new().set_table_style(rust_xlsxwriter::TableStyle::Medium10);
    ///
    ///     // Set the serialization location and custom headers.
    ///     worksheet.deserialize_headers_with_options::<Produce>(0, 0, &header_options)?;
    ///
    ///     // Serialize the data.
    ///     worksheet.serialize(&item1)?;
    ///     worksheet.serialize(&item2)?;
    ///     worksheet.serialize(&item3)?;
    /// #
    /// #     // Save the file.
    /// #     workbook.save("serialize.xlsx")?;
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Output file:
    ///
    /// <img src="https://rustxlsxwriter.github.io/images/worksheet_serialize_table2.png">
    ///
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn set_table_style(mut self, style: TableStyle) -> SerializeFieldOptions {
        self.table = Some(Table::new().set_style(style));
        self
    }

    /// Add a user defined table structure to the serialized fields.
    ///
    /// This method can be used to add a user defined worksheet [`Table`]
    /// structure to a serialized area.
    ///
    /// See [`Table`] for more details on worksheet tables.
    ///
    /// # Parameters
    ///
    /// - `table`: A [`Table`] or object that implements `Into<Table>`.
    ///
    /// # Examples
    ///
    /// The following example demonstrates serializing instances of a Serde
    /// derived data structure to a worksheet with a user defined worksheet
    /// table.
    ///
    /// ```
    /// # // This code is available in examples/doc_worksheet_serialize_table3.rs
    /// #
    /// # use rust_xlsxwriter::{
    /// #     SerializeFieldOptions, Table, TableColumn, TableFunction, Workbook, XlsxError,
    /// # };
    /// # use serde::{Deserialize, Serialize};
    /// #
    /// # fn main() -> Result<(), XlsxError> {
    /// #     let mut workbook = Workbook::new();
    /// #
    /// #     // Add a worksheet to the workbook.
    /// #     let worksheet = workbook.add_worksheet();
    /// #
    ///     // Create a serializable struct.
    ///     #[derive(Deserialize, Serialize)]
    ///     #[serde(rename_all = "PascalCase")]
    ///     struct Produce {
    ///         fruit: &'static str,
    ///         cost: f64,
    ///     }
    ///
    ///     // Create some data instances.
    ///     let item1 = Produce {
    ///         fruit: "Peach",
    ///         cost: 1.05,
    ///     };
    ///
    ///     let item2 = Produce {
    ///         fruit: "Plum",
    ///         cost: 0.15,
    ///     };
    ///
    ///     let item3 = Produce {
    ///         fruit: "Pear",
    ///         cost: 0.75,
    ///     };
    ///
    ///     // Set the caption and subtotal in the total row.
    ///     let columns = vec![
    ///         TableColumn::new().set_total_label("Total"),
    ///         TableColumn::new().set_total_function(TableFunction::Sum),
    ///     ];
    ///
    ///     // Create a new table and configure the total row.
    ///     let table = Table::new().set_total_row(true).set_columns(&columns);
    ///
    ///     // Set the header options.
    ///     let header_options = SerializeFieldOptions::new().set_table(table);
    ///
    ///     // Set the serialization location and custom headers.
    ///     worksheet.deserialize_headers_with_options::<Produce>(0, 0, &header_options)?;
    ///
    ///     // Serialize the data.
    ///     worksheet.serialize(&item1)?;
    ///     worksheet.serialize(&item2)?;
    ///     worksheet.serialize(&item3)?;
    /// #
    /// #     // Save the file.
    /// #     workbook.save("serialize.xlsx")?;
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Output file:
    ///
    /// <img
    /// src="https://rustxlsxwriter.github.io/images/worksheet_serialize_table3.png">
    ///
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn set_table(mut self, table: impl Into<Table>) -> SerializeFieldOptions {
        self.table = Some(table.into());
        self
    }

    /// Set the option to use only the specified custom headers.
    ///
    /// The default behavior when using custom headers is that the custom
    /// properties are merged over the default properties. So if you have a
    /// struct with three fields "item", "cost" and "availability" and you
    /// specify a custom header just for "cost" will still get all three fields
    /// output in the serialization.
    ///
    /// However, you may wish to output only the custom selected fields for use
    /// cases where you wish to skip fields or reorder them. The
    /// `use_custom_headers_only` property allow you to so that. See the
    /// example below for the effect of the option.
    ///
    /// # Parameters
    ///
    /// - `enable`: Turn the property on/off. It is off by default.
    ///
    /// # Examples
    ///
    /// The following example demonstrates different methods of handling custom
    /// properties. The user can either merge them with the default properties
    /// or use the custom properties exclusively.
    ///
    ///
    /// ```
    /// # // This code is available in examples/doc_worksheet_serialize_headers_format8.rs
    /// #
    /// # use rust_xlsxwriter::{CustomSerializeField, SerializeFieldOptions, Workbook, XlsxError};
    /// # use serde::{Deserialize, Serialize};
    /// #
    /// # fn main() -> Result<(), XlsxError> {
    /// #     let mut workbook = Workbook::new();
    /// #
    /// #     // Add a worksheet to the workbook.
    /// #     let worksheet = workbook.add_worksheet();
    /// #
    /// #     // Create a serializable struct.
    /// #     #[derive(Deserialize, Serialize)]
    /// #     struct Produce {
    /// #         fruit: &'static str,
    /// #         cost: f64,
    /// #         in_stock: bool,
    /// #     }
    /// #
    /// #     // Create some data instances.
    /// #     let items = [
    /// #         Produce {
    /// #             fruit: "Peach",
    /// #             cost: 1.05,
    /// #             in_stock: true,
    /// #         },
    /// #         Produce {
    /// #             fruit: "Plum",
    /// #             cost: 0.15,
    /// #             in_stock: false,
    /// #         },
    /// #         Produce {
    /// #             fruit: "Pear",
    /// #             cost: 0.75,
    /// #             in_stock: true,
    /// #         },
    /// #     ];
    /// #
    ///     // Default handling of customized headers: the formatting is merged with the
    ///     // default values so "in_stock" is still shown.
    ///     let custom_headers = [
    ///         CustomSerializeField::new("fruit").rename("Item"),
    ///         CustomSerializeField::new("cost").rename("Price"),
    ///         CustomSerializeField::new("in_stock").rename("Foo"),
    ///     ];
    ///     let header_options = SerializeFieldOptions::new().set_custom_headers(&custom_headers);
    ///
    ///     worksheet.deserialize_headers_with_options::<Produce>(0, 0, &header_options)?;
    ///     worksheet.serialize(&items)?;
    ///
    ///     // Set the "use_custom_headers_only" option to shown only the specified
    ///     // custom headers.
    ///     let custom_headers = [
    ///         CustomSerializeField::new("fruit").rename("Item"),
    ///         CustomSerializeField::new("cost").rename("Price"),
    ///     ];
    ///     let header_options = SerializeFieldOptions::new()
    ///         .set_custom_headers(&custom_headers)
    ///         .use_custom_headers_only(true);
    ///
    ///     worksheet.deserialize_headers_with_options::<Produce>(0, 4, &header_options)?;
    ///     worksheet.serialize(&items)?;
    ///
    ///     // This can also be used to set the order of the output.
    ///     let custom_headers = [
    ///         CustomSerializeField::new("cost").rename("Price"),
    ///         CustomSerializeField::new("fruit").rename("Item"),
    ///     ];
    ///     let header_options = SerializeFieldOptions::new()
    ///         .set_custom_headers(&custom_headers)
    ///         .use_custom_headers_only(true);
    ///
    ///     worksheet.deserialize_headers_with_options::<Produce>(0, 7, &header_options)?;
    ///     worksheet.serialize(&items)?;
    /// #
    /// #     // Save the file.
    /// #     workbook.save("serialize.xlsx")?;
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Output file:
    ///
    /// <img
    /// src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers_format8.png">
    ///
    ///
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn use_custom_headers_only(mut self, enable: bool) -> SerializeFieldOptions {
        self.use_custom_headers_only = enable;
        self
    }

    /// Set the name of the struct to be serialized.
    ///
    /// Note, this is a semi public method. End users won't and shouldn't need
    /// to use this since the struct name will be determine by the worksheet
    /// method that sets the header location. The method is here to allow full
    /// `SerializeFieldOptions` options to be generated programmatically by the
    /// [`XlsxSerialize`] proc macros.
    ///
    /// # Parameters
    ///
    /// - `name`: The name of the struct being serialized.
    ///
    #[doc(hidden)]
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn set_struct_name(mut self, name: impl Into<String>) -> SerializeFieldOptions {
        self.struct_name = name.into();
        self
    }
}

// -----------------------------------------------------------------------
// CustomSerializeField.
// -----------------------------------------------------------------------

/// The `CustomSerializeField` struct represents a custom serializer
/// field/header.
///
/// `CustomSerializeField` can be used to set column headers to map serialized
/// fields to. It allows you to rename, format or skip headers and also to define
/// formatting for field values.
///
/// It is used in conjunction with the [`SerializeFieldOptions`] struct and
/// [`Worksheet::deserialize_headers_with_options()`] and
/// [`Worksheet::serialize_headers_with_options()`] methods.
///
/// See [Working with Serde](crate::serializer) for an introduction to
/// serialization with `rust_xlsxwriter`.
///
/// # Examples
///
/// The following example demonstrates serializing instances of a Serde derived
/// data structure to a worksheet with custom headers and cell formatting.
///
/// ```
/// # // This code is available in examples/doc_worksheet_serialize_headers_custom.rs
/// #
/// use rust_xlsxwriter::{
///     CustomSerializeField, Format, FormatBorder, SerializeFieldOptions, Workbook, XlsxError,
/// };
/// use serde::{Deserialize, Serialize};
///
/// fn main() -> Result<(), XlsxError> {
///     let mut workbook = Workbook::new();
///
///     // Add a worksheet to the workbook.
///     let worksheet = workbook.add_worksheet();
///
///     // Add some formats to use with the serialization data.
///     let header_format = Format::new()
///         .set_bold()
///         .set_border(FormatBorder::Thin)
///         .set_background_color("C6EFCE");
///
///     let currency_format = Format::new().set_num_format("$0.00");
///
///     // Create a serializable struct.
///     #[derive(Deserialize, Serialize)]
///     struct Produce {
///         fruit: &'static str,
///         cost: f64,
///     }
///
///     // Create some data instances.
///     let item1 = Produce {
///         fruit: "Peach",
///         cost: 1.05,
///     };
///
///     let item2 = Produce {
///         fruit: "Plum",
///         cost: 0.15,
///     };
///
///     let item3 = Produce {
///         fruit: "Pear",
///         cost: 0.75,
///     };
///
///     // Set up the custom headers.
///     let custom_headers = [
///         CustomSerializeField::new("fruit")
///             .rename("Item"),
///         CustomSerializeField::new("cost")
///             .rename("Price")
///             .set_value_format(currency_format),
///     ];
///
///     let header_options = SerializeFieldOptions::new()
///         .set_header_format(header_format)
///         .set_custom_headers(&custom_headers);
///
///     // Set the serialization location and custom headers.
///     worksheet.deserialize_headers_with_options::<Produce>(1, 1, &header_options)?;
///
///     // Serialize the data.
///     worksheet.serialize(&item1)?;
///     worksheet.serialize(&item2)?;
///     worksheet.serialize(&item3)?;
///
///     // Save the file.
///     workbook.save("serialize.xlsx")?;
///
///     Ok(())
/// }
/// ```
///
/// Output file:
///
/// <img
/// src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers_custom.png">
///
///
#[derive(Clone)]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
pub struct CustomSerializeField {
    pub(crate) field_name: String,
    pub(crate) header_name: String,
    pub(crate) header_format: Option<Format>,
    pub(crate) column_format: Option<Format>,
    pub(crate) value_format: Arc<Option<Format>>,
    pub(crate) skip: bool,
    pub(crate) col: ColNum,
    pub(crate) width: Option<f64>,
    pub(crate) pixel_width: Option<u32>,
}

impl CustomSerializeField {
    /// Create custom serialize field/header options.
    ///
    /// Create a `CustomSerializeField` to be used with
    /// [`SerializeFieldOptions::set_custom_headers()`].
    ///
    /// The `field_name` argument must correspond to a struct field being
    /// serialized.
    ///
    /// # Parameters
    ///
    /// - `field_name`: The name of the serialized field to map to the header.
    ///
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn new(field_name: impl Into<String>) -> CustomSerializeField {
        let field_name = field_name.into();
        let header_name = field_name.clone();

        CustomSerializeField {
            field_name,
            header_name,
            header_format: None,
            column_format: None,
            value_format: Arc::new(None),
            skip: false,
            col: 0,
            width: None,
            pixel_width: None,
        }
    }

    /// Rename the field name displayed a custom serialize header.
    ///
    /// The field names of structs are serialized as column headers at the top
    /// of serialized data. The default field names may not be the header names
    /// that you want displayed in Excel in which case you can use one of the
    /// two main methods to rename the fields/headers:
    ///
    /// 1. Rename the field during serialization using the Serde:
    ///    - [field attribute]: `#[serde(rename = "name")` or
    ///    - [container attribute]: `#[serde(rename_all = "...")]`.
    /// 2. Rename the header (not field) when setting up custom serialization
    ///    headers via [`Worksheet::deserialize_headers_with_options()`] or
    ///    [`Worksheet::serialize_headers_with_options()`] and
    ///    [`CustomSerializeField::rename()`].
    ///
    /// [field attribute]: https://serde.rs/field-attrs.html
    /// [container attribute]: https://serde.rs/container-attrs.html
    ///
    /// See [Renaming fields when
    /// serializing](crate::serializer#renaming-fields-when-serializing) for
    /// more details.
    ///
    /// # Parameters
    ///
    /// - `name`: A string like name to use as the header.
    ///
    /// # Examples
    ///
    /// The following example demonstrates renaming fields during serialization
    /// by specifying custom headers and renaming them there. You must still
    /// specify the actual field name to serialize in the `new()` constructor.
    ///
    /// ```
    /// # // This code is available in examples/doc_worksheet_serialize_headers_rename2.rs
    /// #
    /// # use rust_xlsxwriter::{CustomSerializeField, SerializeFieldOptions, Workbook, XlsxError};
    /// # use serde::{Deserialize, Serialize};
    /// #
    /// # fn main() -> Result<(), XlsxError> {
    /// #     let mut workbook = Workbook::new();
    /// #
    /// #     // Add a worksheet to the workbook.
    /// #     let worksheet = workbook.add_worksheet();
    /// #
    /// #     // Create a serializable struct.
    ///     #[derive(Deserialize, Serialize)]
    ///     struct Produce {
    ///         fruit: &'static str,
    ///         cost: f64,
    ///     }
    ///
    ///     // Create some data instances.
    ///     let item1 = Produce {
    ///         fruit: "Peach",
    ///         cost: 1.05,
    ///     };
    ///
    ///     let item2 = Produce {
    ///         fruit: "Plum",
    ///         cost: 0.15,
    ///     };
    ///
    ///     let item3 = Produce {
    ///         fruit: "Pear",
    ///         cost: 0.75,
    ///     };
    ///
    ///     // Set up the custom headers.
    ///     let custom_headers = [
    ///         CustomSerializeField::new("fruit").rename("Item"),
    ///         CustomSerializeField::new("cost").rename("Price"),
    ///     ];
    ///     let header_options = SerializeFieldOptions::new().set_custom_headers(&custom_headers);
    ///
    ///     // Set the serialization location and custom headers.
    ///     worksheet.deserialize_headers_with_options::<Produce>(0, 0, &header_options)?;
    ///
    ///     // Serialize the data.
    ///     worksheet.serialize(&item1)?;
    ///     worksheet.serialize(&item2)?;
    ///     worksheet.serialize(&item3)?;
    /// #
    /// #     // Save the file.
    /// #     workbook.save("serialize.xlsx")?;
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Output file:
    ///
    /// <img
    /// src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers_rename1.png">
    ///
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn rename(mut self, name: impl Into<String>) -> CustomSerializeField {
        self.header_name = name.into();
        self
    }

    /// Set the header format for a custom serialize header.
    ///
    /// In general the [`SerializeFieldOptions::set_header_format()`] method
    /// should be used to set the header format for all custom headers but if
    /// you require individual headers to have different header formats you can
    /// use this method.
    ///
    /// See [`Format`] for more information on formatting.
    ///
    /// # Parameters
    ///
    /// - `format`: The [`Format`] property for the custom header.
    ///
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn set_header_format(mut self, format: impl Into<Format>) -> CustomSerializeField {
        self.header_format = Some(format.into());
        self
    }

    /// Set the format for the column corresponding to a serialize header/field.
    ///
    /// This method can be used to set a number format, or other properties, for
    /// data that is serialized below the header. This method sets the format
    /// for the entire column whereas the
    /// [`CustomSerializeField::set_value_format()`] method below only sets it
    /// for serialized data within the column.
    ///
    /// This a a wrapper around the [`Worksheet::set_column_format()`] method
    /// with the advantage that it doesn't require you to keep track of the
    /// actual column number to use it.
    ///
    /// See [`Format`] and [`Format::set_num_format()`] for more information on
    /// formatting.
    ///
    /// # Parameters
    ///
    /// - `format`: The [`Format`] property for the conditional format.
    ///
    /// # Examples
    ///
    /// The following example demonstrates serializing instances of a Serde
    /// derived data structure to a worksheet with header and column formatting.
    ///
    /// ```
    /// # // This code is available in examples/doc_worksheet_serialize_headers_format5.rs
    /// #
    /// # use rust_xlsxwriter::{
    /// #     CustomSerializeField, Format, FormatBorder, SerializeFieldOptions, Workbook, XlsxError,
    /// # };
    /// # use serde::{Deserialize, Serialize};
    /// #
    /// # fn main() -> Result<(), XlsxError> {
    /// #     let mut workbook = Workbook::new();
    /// #
    /// #     // Add a worksheet to the workbook.
    /// #     let worksheet = workbook.add_worksheet();
    /// #
    ///     // Add some formats to use with the serialization data.
    ///     let header_format = Format::new()
    ///         .set_bold()
    ///         .set_border(FormatBorder::Thin)
    ///         .set_background_color("C6EFCE");
    ///
    ///     let currency_format = Format::new().set_num_format("$0.00");
    /// #
    /// #     // Create a serializable struct.
    /// #     #[derive(Deserialize, Serialize)]
    /// #     struct Produce {
    /// #         #[serde(rename = "Item")]
    /// #         fruit: &'static str,
    /// #
    /// #         #[serde(rename = "Price")]
    /// #         cost: f64,
    /// #     }
    /// #
    /// #     // Create some data instances.
    /// #     let item1 = Produce {
    /// #         fruit: "Peach",
    /// #         cost: 1.05,
    /// #     };
    /// #
    /// #     let item2 = Produce {
    /// #         fruit: "Plum",
    /// #         cost: 0.15,
    /// #     };
    /// #
    /// #     let item3 = Produce {
    /// #         fruit: "Pear",
    /// #         cost: 0.75,
    /// #     };
    /// #
    ///     // Set up the custom headers.
    ///     let custom_headers =
    ///         [CustomSerializeField::new("Price").set_column_format(currency_format)];
    ///
    ///     let header_options = SerializeFieldOptions::new()
    ///         .set_header_format(header_format)
    ///         .set_custom_headers(&custom_headers);
    ///
    ///     // Set the serialization location and headers.
    ///     worksheet.deserialize_headers_with_options::<Produce>(1, 1, &header_options)?;
    /// #
    /// #     // Serialize the data.
    /// #     worksheet.serialize(&item1)?;
    /// #     worksheet.serialize(&item2)?;
    /// #     worksheet.serialize(&item3)?;
    /// #
    /// #     // Save the file.
    /// #     workbook.save("serialize.xlsx")?;
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Output file:
    ///
    /// <img
    /// src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers_custom.png">
    ///
    pub fn set_column_format(mut self, format: impl Into<Format>) -> CustomSerializeField {
        self.column_format = Some(format.into());
        self
    }

    /// Set the cell format for values corresponding to a serialize
    /// header/field.
    ///
    /// This method can be used to set a number format, or other properties, for
    /// data that is serialized below the header. This method sets the format
    /// for the serialized data within the column whereas the
    /// [`CustomSerializeField::set_column_format()`] method above sets it for
    /// the the entire column.
    ///
    /// See [`Format`] and [`Format::set_num_format()`] for more information on
    /// formatting.
    ///
    /// # Parameters
    ///
    /// - `format`: The [`Format`] property for cells corresponding to the
    ///   field/header.
    ///
    /// # Examples
    ///
    /// The following example demonstrates formatting cells during
    /// serialization. Note the currency format for the `cost` cells.
    ///
    /// ```
    /// # // This code is available in examples/doc_worksheet_serialize_headers_format3.rs
    /// #
    /// # use rust_xlsxwriter::{
    /// #     CustomSerializeField, Format, SerializeFieldOptions, Workbook, XlsxError,
    /// # };
    /// # use serde::{Deserialize, Serialize};
    /// #
    /// # fn main() -> Result<(), XlsxError> {
    /// #     let mut workbook = Workbook::new();
    /// #
    /// #     // Add a worksheet to the workbook.
    /// #     let worksheet = workbook.add_worksheet();
    /// #
    ///     // Set a cell value format.
    ///     let value_format = Format::new().set_num_format("$0.00");
    /// #
    /// #     // Create a serializable struct.
    /// #     #[derive(Deserialize, Serialize)]
    /// #     struct Produce {
    /// #         fruit: &'static str,
    /// #         cost: f64,
    /// #     }
    /// #
    /// #     // Create some data instances.
    /// #     let item1 = Produce {
    /// #         fruit: "Peach",
    /// #         cost: 1.05,
    /// #     };
    /// #
    /// #     let item2 = Produce {
    /// #         fruit: "Plum",
    /// #         cost: 0.15,
    /// #     };
    /// #
    /// #     let item3 = Produce {
    /// #         fruit: "Pear",
    /// #         cost: 0.75,
    /// #     };
    /// #
    ///     // Set the custom headers.
    ///     let header_options = SerializeFieldOptions::new()
    ///         .set_custom_headers(
    ///             &[CustomSerializeField::new("cost").set_value_format(value_format)]
    ///         );
    ///
    ///     // Set the serialization location and headers.
    ///     worksheet.deserialize_headers_with_options::<Produce>(0, 0, &header_options)?;
    /// #
    /// #     // Serialize the data.
    /// #     worksheet.serialize(&item1)?;
    /// #     worksheet.serialize(&item2)?;
    /// #     worksheet.serialize(&item3)?;
    /// #
    /// #     // Save the file.
    /// #     workbook.save("serialize.xlsx")?;
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Output file:
    ///
    /// <img
    /// src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers_format3.png">
    ///
    ///
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn set_value_format(mut self, format: impl Into<Format>) -> CustomSerializeField {
        self.value_format = Arc::new(Some(format.into()));
        self
    }

    /// Skip a field when serializing.
    ///
    /// When serializing a struct you may not want all of the fields to be
    /// serialized. For example, the struct may contain internal fields that
    /// aren't of interest to the end user. There are several ways to skip
    /// fields:
    ///
    /// 1. Using the Serde [field attributes] `#[serde(skip)]`. This is the
    ///    simplest and best method.
    /// 2. Explicitly omitting the field when setting up custom serialization
    ///    headers This method is useful when you can't add any additional
    ///    attributes on the struct.
    /// 3. Marking the field as skippable via custom headers and this `skip()`
    ///    method. This is only required in a few edge cases where the previous
    ///    methods won't work.
    ///
    /// [field attributes]: https://serde.rs/field-attrs.html
    ///
    /// See [Skipping fields when
    /// serializing](crate::serializer#skipping-fields-when-serializing) for
    /// more details.
    ///
    /// # Parameters
    ///
    /// - `enable`: Turn the property on/off. It is off by default.
    ///
    /// # Examples
    ///
    /// The following example demonstrates skipping fields during serialization
    /// by explicitly skipping them via custom headers.
    ///
    /// ```
    /// # // This code is available in examples/doc_worksheet_serialize_headers_skip3.rs
    /// #
    /// # use rust_xlsxwriter::{CustomSerializeField, SerializeFieldOptions, Workbook, XlsxError};
    /// # use serde::{Deserialize, Serialize};
    /// #
    /// # fn main() -> Result<(), XlsxError> {
    /// #     let mut workbook = Workbook::new();
    /// #
    /// #     // Add a worksheet to the workbook.
    /// #     let worksheet = workbook.add_worksheet();
    /// #
    /// #     // Create a serializable struct.
    ///     #[derive(Deserialize, Serialize)]
    ///     struct Produce {
    ///         fruit: &'static str,
    ///         cost: f64,
    ///         in_stock: bool,
    ///     }
    ///
    ///     // Create some data instances.
    ///     let item1 = Produce {
    ///         fruit: "Peach",
    ///         cost: 1.05,
    ///         in_stock: true,
    ///     };
    ///
    ///     let item2 = Produce {
    ///         fruit: "Plum",
    ///         cost: 0.15,
    ///         in_stock: true,
    ///     };
    ///
    ///     let item3 = Produce {
    ///         fruit: "Pear",
    ///         cost: 0.75,
    ///         in_stock: false,
    ///     };
    ///
    ///     // We only need to set a custom header for the field we want to skip.
    ///     let header_options = SerializeFieldOptions::new()
    ///         .set_custom_headers(&[CustomSerializeField::new("in_stock").skip(true)]);
    ///
    ///     // Set the serialization location and custom headers.
    ///     worksheet.deserialize_headers_with_options::<Produce>(0, 0, &header_options)?;
    ///
    ///     // Serialize the data.
    ///     worksheet.serialize(&item1)?;
    ///     worksheet.serialize(&item2)?;
    ///     worksheet.serialize(&item3)?;
    /// #
    /// #     // Save the file.
    /// #     workbook.save("serialize.xlsx")?;
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Output file:
    ///
    /// <img
    /// src="https://rustxlsxwriter.github.io/images/worksheet_serialize_headers_skip1.png">
    ///
    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    pub fn skip(mut self, enable: bool) -> CustomSerializeField {
        self.skip = enable;
        self
    }

    /// Set the width for the column corresponding to a serialize header/field.
    ///
    /// The `set_column_width()` method is used to change the default width of a
    /// worksheet column in character units.
    ///
    /// This a a wrapper around the [`Worksheet::set_column_width()`] method
    /// with the advantage that it doesn't require you to keep track of the
    /// actual column number to use it.
    ///
    /// # Parameters
    ///
    /// - `width`: The row width in character units.
    ///
    pub fn set_column_width(mut self, width: impl Into<f64>) -> CustomSerializeField {
        self.width = Some(width.into());
        self
    }

    /// Set the width for the column corresponding to a serialize header/field.
    ///
    /// The `set_column_width_pixels()` method is used to change the default
    /// width of a worksheet column in pixel units.
    ///
    /// This a a wrapper around the [`Worksheet::set_column_width_pixels()`]
    /// method with the advantage that it doesn't require you to keep track of
    /// the actual column number to use it.
    ///
    /// # Parameters
    ///
    /// - `width`: The row width in character units.
    ///
    pub fn set_column_width_pixels(mut self, width: u32) -> CustomSerializeField {
        self.pixel_width = Some(width);
        self
    }
}

// -----------------------------------------------------------------------
// Worksheet Serializer. This is the implementation of the Serializer trait to
// serialized a serde derived struct to an Excel worksheet.
// -----------------------------------------------------------------------
#[allow(unused_variables)]
impl ser::Serializer for &mut Worksheet {
    #[doc(hidden)]
    type Ok = ();
    #[doc(hidden)]
    type Error = XlsxError;
    #[doc(hidden)]
    type SerializeSeq = Self;
    #[doc(hidden)]
    type SerializeTuple = Self;
    #[doc(hidden)]
    type SerializeTupleStruct = Self;
    #[doc(hidden)]
    type SerializeTupleVariant = Self;
    #[doc(hidden)]
    type SerializeMap = Self;
    #[doc(hidden)]
    type SerializeStruct = Self;
    #[doc(hidden)]
    type SerializeStructVariant = Self;

    // Serialize all the default number types that fit into Excel's f64 type.
    #[doc(hidden)]
    fn serialize_bool(self, data: bool) -> Result<(), XlsxError> {
        self.serialize_to_worksheet_cell(data)
    }

    #[doc(hidden)]
    fn serialize_i8(self, data: i8) -> Result<(), XlsxError> {
        self.serialize_to_worksheet_cell(data)
    }

    #[doc(hidden)]
    fn serialize_u8(self, data: u8) -> Result<(), XlsxError> {
        self.serialize_to_worksheet_cell(data)
    }

    #[doc(hidden)]
    fn serialize_i16(self, data: i16) -> Result<(), XlsxError> {
        self.serialize_to_worksheet_cell(data)
    }

    #[doc(hidden)]
    fn serialize_u16(self, data: u16) -> Result<(), XlsxError> {
        self.serialize_to_worksheet_cell(data)
    }

    #[doc(hidden)]
    fn serialize_i32(self, data: i32) -> Result<(), XlsxError> {
        self.serialize_to_worksheet_cell(data)
    }

    #[doc(hidden)]
    fn serialize_u32(self, data: u32) -> Result<(), XlsxError> {
        self.serialize_to_worksheet_cell(data)
    }

    #[doc(hidden)]
    fn serialize_i64(self, data: i64) -> Result<(), XlsxError> {
        self.serialize_to_worksheet_cell(data)
    }

    #[doc(hidden)]
    fn serialize_u64(self, data: u64) -> Result<(), XlsxError> {
        self.serialize_to_worksheet_cell(data)
    }

    #[doc(hidden)]
    fn serialize_f32(self, data: f32) -> Result<(), XlsxError> {
        self.serialize_to_worksheet_cell(data)
    }

    #[doc(hidden)]
    fn serialize_f64(self, data: f64) -> Result<(), XlsxError> {
        self.serialize_to_worksheet_cell(data)
    }

    // Serialize strings types.
    #[doc(hidden)]
    fn serialize_str(self, data: &str) -> Result<(), XlsxError> {
        self.serialize_to_worksheet_cell(data)
    }

    // Excel doesn't have a character type. Serialize a char as a
    // single-character string.
    #[doc(hidden)]
    fn serialize_char(self, data: char) -> Result<(), XlsxError> {
        self.serialize_str(&data.to_string())
    }

    // Excel doesn't have a type equivalent to a byte array.
    #[doc(hidden)]
    fn serialize_bytes(self, data: &[u8]) -> Result<(), XlsxError> {
        Ok(())
    }

    // Serialize Some(T) values.
    #[doc(hidden)]
    fn serialize_some<T>(self, data: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        data.serialize(self)
    }

    // Empty/None/Null values in Excel are ignored unless the cell has
    // formatting in which case they are handled as a "blank" cell. For all of
    // these cases we write an empty string and the worksheet writer methods
    // will handle it correctly based on context.

    #[doc(hidden)]
    fn serialize_none(self) -> Result<(), XlsxError> {
        self.serialize_str("")
    }

    #[doc(hidden)]
    fn serialize_unit(self) -> Result<(), XlsxError> {
        self.serialize_none()
    }

    #[doc(hidden)]
    fn serialize_unit_struct(self, _name: &'static str) -> Result<(), XlsxError> {
        self.serialize_none()
    }

    // Serialize enum style unit variants.
    #[doc(hidden)]
    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
    ) -> Result<(), XlsxError> {
        variant.serialize(self)
    }

    // Try to handle this as a single value.
    #[doc(hidden)]
    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        value.serialize(self)
    }

    // Serialize the value of enum style newtype variants.
    #[doc(hidden)]
    fn serialize_newtype_variant<T>(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        value: &T,
    ) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        value.serialize(&mut *self)
    }

    // Compound types.
    //
    // The only compound types we map into the Excel data model are structs.

    // Structs are the main primary data type used to map data structures into
    // Excel.
    fn serialize_struct(
        self,
        name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStruct, XlsxError> {
        // Store the struct type name to check against user defined structs.
        self.serializer_state.set_current_struct(name);

        Ok(self)
    }

    #[doc(hidden)]
    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, XlsxError> {
        Ok(self)
    }

    // Not used.
    #[doc(hidden)]
    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, XlsxError> {
        self.serialize_seq(Some(len))
    }

    // Not used.
    #[doc(hidden)]
    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleStruct, XlsxError> {
        self.serialize_seq(Some(len))
    }

    // Not used.
    #[doc(hidden)]
    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleVariant, XlsxError> {
        variant.serialize(&mut *self)?;
        Ok(self)
    }

    // Maps, and structs that use `#[serde(flatten)]`, are serialized by Serde
    // as maps. These don't carry a struct name or a static list of field names
    // so they can't be mapped onto Excel's fixed 2D grid of cells. We reject
    // them with an explicit error rather than silently writing nothing. However
    // we also check if the map can be explicitly skipped by the user.
    #[doc(hidden)]
    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, XlsxError> {
        if self.serializer_state.is_unselected_field() {
            return Ok(self);
        }

        Err(XlsxError::SerdeError(
            "Map types and structs that use `#[serde(flatten)]` cannot be serialized to Excel. \
            See the limitations section in the `rust_xlsxwriter::serializer` documentation."
                .to_string(),
        ))
    }

    // Not used.
    #[doc(hidden)]
    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStructVariant, XlsxError> {
        variant.serialize(&mut *self)?;
        Ok(self)
    }
}

// The following impls deal with the serialization of compound types.
// Currently we only support/use SerializeStruct and SerializeSeq.

// Structs are the main sequence type used by `rust_xlsxwriter`.
#[doc(hidden)]
impl ser::SerializeStruct for &mut Worksheet {
    type Ok = ();
    type Error = XlsxError;

    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        // Store field name to allow us to map to the correct header/column.
        self.serializer_state.current_field = key.to_string();

        value.serialize(&mut **self)
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

// We also serialize sequences to map vectors/arrays to Excel.
#[doc(hidden)]
impl ser::SerializeSeq for &mut Worksheet {
    type Ok = ();
    type Error = XlsxError;

    // Serialize a single element of the sequence.
    fn serialize_element<T>(&mut self, value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        value.serialize(&mut **self)
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

// Serialize tuple sequences.
#[doc(hidden)]
impl ser::SerializeTuple for &mut Worksheet {
    type Ok = ();
    type Error = XlsxError;

    fn serialize_element<T>(&mut self, value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        value.serialize(&mut **self)
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

// Serialize tuple struct sequences.
#[doc(hidden)]
impl ser::SerializeTupleStruct for &mut Worksheet {
    type Ok = ();
    type Error = XlsxError;

    fn serialize_field<T>(&mut self, value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        value.serialize(&mut **self)
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

// Serialize tuple variant sequences.
#[doc(hidden)]
impl ser::SerializeTupleVariant for &mut Worksheet {
    type Ok = ();
    type Error = XlsxError;

    fn serialize_field<T>(&mut self, value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        value.serialize(&mut **self)
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

// Maps only get to this point if they are in a skipped/deselected field, see
// `serialize_map()` above. Ignore the keys and values without traversing them.
#[doc(hidden)]
impl ser::SerializeMap for &mut Worksheet {
    type Ok = ();
    type Error = XlsxError;

    fn serialize_key<T>(&mut self, _key: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        Ok(())
    }

    fn serialize_value<T>(&mut self, _value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        Ok(())
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

// Serialize struct variant sequences.
#[doc(hidden)]
impl ser::SerializeStructVariant for &mut Worksheet {
    type Ok = ();
    type Error = XlsxError;

    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        key.serialize(&mut **self)?;
        value.serialize(&mut **self)
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

// -----------------------------------------------------------------------
// SerializerHeader. A struct used to store header/field name during
// serialization of the headers.
// -----------------------------------------------------------------------
pub(crate) struct SerializerHeader {
    pub(crate) struct_name: String,
    pub(crate) field_names: Vec<String>,
}

// -----------------------------------------------------------------------
// Header Serializer. This is the a simplified implementation of the Serializer
// trait to capture the headers/field names only.
// -----------------------------------------------------------------------
#[allow(unused_variables)]
impl ser::Serializer for &mut SerializerHeader {
    type Ok = ();
    type Error = XlsxError;
    type SerializeSeq = Self;
    type SerializeTuple = Self;
    type SerializeTupleStruct = Self;
    type SerializeTupleVariant = Self;
    type SerializeMap = Self;
    type SerializeStruct = Self;
    type SerializeStructVariant = Self;

    // Serialize strings types to capture the field names but ignore all other
    // types.
    fn serialize_str(self, data: &str) -> Result<(), XlsxError> {
        self.field_names.push(data.to_string());
        Ok(())
    }

    // Store the struct type/name to allow us to disambiguate structs.
    fn serialize_struct(
        self,
        name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStruct, XlsxError> {
        self.struct_name = name.to_string();
        Ok(self)
    }

    // Ignore all other primitive types.
    fn serialize_bool(self, data: bool) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_i8(self, data: i8) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_u8(self, data: u8) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_i16(self, data: i16) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_u16(self, data: u16) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_i32(self, data: i32) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_u32(self, data: u32) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_i64(self, data: i64) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_u64(self, data: u64) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_f32(self, data: f32) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_f64(self, data: f64) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_char(self, data: char) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_bytes(self, data: &[u8]) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_some<T>(self, data: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        Ok(())
    }

    fn serialize_none(self) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_unit(self) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_unit_struct(self, _name: &'static str) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
    ) -> Result<(), XlsxError> {
        Ok(())
    }

    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        Ok(())
    }

    fn serialize_newtype_variant<T>(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        value: &T,
    ) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        Ok(())
    }

    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, XlsxError> {
        Ok(self)
    }

    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, XlsxError> {
        self.serialize_seq(Some(len))
    }

    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleStruct, XlsxError> {
        self.serialize_seq(Some(len))
    }

    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleVariant, XlsxError> {
        variant.serialize(&mut *self)?;
        Ok(self)
    }

    // See the comment on the equivalent `Worksheet` method above.
    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, XlsxError> {
        Err(XlsxError::SerdeError(
            "Map types and structs that use `#[serde(flatten)]` cannot be serialized to Excel. \
            See the limitations section in the `rust_xlsxwriter::serializer` documentation."
                .to_string(),
        ))
    }

    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStructVariant, XlsxError> {
        variant.serialize(&mut *self)?;
        Ok(self)
    }
}

// We are only interested in Struct fields. Other compound types are ignored.
impl ser::SerializeStruct for &mut SerializerHeader {
    type Ok = ();
    type Error = XlsxError;

    fn serialize_field<T>(&mut self, key: &'static str, _value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        // Serialize the key/field name but ignore the values.
        key.serialize(&mut **self)
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

impl ser::SerializeSeq for &mut SerializerHeader {
    type Ok = ();
    type Error = XlsxError;

    fn serialize_element<T>(&mut self, _value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        Ok(())
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

impl ser::SerializeTuple for &mut SerializerHeader {
    type Ok = ();
    type Error = XlsxError;

    fn serialize_element<T>(&mut self, value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        value.serialize(&mut **self)
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

impl ser::SerializeTupleStruct for &mut SerializerHeader {
    type Ok = ();
    type Error = XlsxError;

    fn serialize_field<T>(&mut self, _value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        Ok(())
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

impl ser::SerializeTupleVariant for &mut SerializerHeader {
    type Ok = ();
    type Error = XlsxError;

    fn serialize_field<T>(&mut self, _value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        Ok(())
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

impl ser::SerializeMap for &mut SerializerHeader {
    type Ok = ();
    type Error = XlsxError;

    fn serialize_key<T>(&mut self, _key: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        Ok(())
    }

    fn serialize_value<T>(&mut self, _value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        Ok(())
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

impl ser::SerializeStructVariant for &mut SerializerHeader {
    type Ok = ();
    type Error = XlsxError;

    fn serialize_field<T>(&mut self, _key: &'static str, _value: &T) -> Result<(), XlsxError>
    where
        T: ?Sized + Serialize,
    {
        Ok(())
    }

    fn end(self) -> Result<(), XlsxError> {
        Ok(())
    }
}

// -----------------------------------------------------------------------
// Header Deserializer. This is the a simplified implementation of the
// Deserializer trait to capture the headers/field names only.
// -----------------------------------------------------------------------
pub(crate) struct DeSerializerHeader<'a> {
    pub(crate) struct_name: &'a mut &'static str,
    pub(crate) field_names: &'a mut &'static [&'static str],
}

impl<'de> Deserializer<'de> for DeSerializerHeader<'_> {
    type Error = XlsxError;

    fn deserialize_struct<V>(
        self,
        name: &'static str,
        fields: &'static [&'static str],
        _visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        *self.struct_name = name;
        *self.field_names = fields;
        Err(XlsxError::SerdeError("Deserialization error".to_string()))
    }

    fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        Err(XlsxError::SerdeError("Deserialization error".to_string()))
    }

    serde::forward_to_deserialize_any! {
        bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
        byte_buf option unit unit_struct newtype_struct seq tuple
        tuple_struct map enum identifier ignored_any
    }
}

pub(crate) fn deserialize_headers<'de, T>() -> SerializerHeader
where
    T: Deserialize<'de>,
{
    let mut struct_name = "";
    let mut field_names: &[&str] = &[""];

    // Ignore the deserialization return since we have set up all the
    // Deserializer methods (above) to return quickly/with an error.
    let _ = T::deserialize(DeSerializerHeader {
        struct_name: &mut struct_name,
        field_names: &mut field_names,
    });

    let struct_name = struct_name.to_string();
    let field_names = field_names.iter().map(|&s| s.to_string()).collect();

    SerializerHeader {
        struct_name,
        field_names,
    }
}

// -----------------------------------------------------------------------
// XlsxSerializer trait. Trait to map `#[xlsx()]` attributes to
// `SerializeFieldOptions` options.
// -----------------------------------------------------------------------

/// Trait to map `#[xlsx()]` attributes to `SerializeFieldOptions` options.
///
/// The trait is mainly used by the `rust_xlsxwriter_derive` proc macros to
/// convert from `#[xlsx()]` attributes to [`SerializeFieldOptions`] and
/// [`CustomSerializeField`] options to configure the output of Serde
/// serialization.
///
/// See [Working with Serde](crate::serializer#working-with-serde).
///
pub trait XlsxSerialize {
    /// Map `#[xlsx()]` attributes to [`SerializeFieldOptions`].
    fn to_serialize_field_options() -> SerializeFieldOptions;
}