ferroxl 0.2.0

ferroxl: read and write Excel 2007 xlsx/xlsm files with an openpyxl-compatible API
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
//! Writing the shared style table (`openpyxl/writer/styles.py`).
//!
//! The writer deduplicates the fonts, fills, borders and number formats referenced by the
//! workbook's cells, assigns each an index, and emits the `cellXfs` records that cells point
//! at. Style identity comes from the same field-based equality the Python `HashableObject`
//! uses.

use std::collections::HashMap;

use crate::styles::alignment::Alignment;
use crate::styles::borders::Border;
use crate::styles::fills::Fill;
use crate::styles::fonts::Font;
use crate::styles::numbers::NumberFormat;
use crate::styles::protection::{Protection, ProtectionFlag};
use crate::styles::style::{defaults, Style};
use crate::workbook::Workbook;
use crate::xml::constants::SHEET_MAIN_NS;
use crate::xml::functions::Element;

/// The first custom `numFmtId`; Excel reserves everything below 164 for builtins.
pub const FIRST_CUSTOM_FORMAT_ID: u32 = 165;

/// The identifier assigned to a style in the shared tables.
///
/// The style table starts at 1 because index 0 is the default style, which Excel always
/// expects to exist.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct StyleId(pub usize);

impl StyleId {
    /// The identifier as a number.
    pub fn value(self) -> usize {
        self.0
    }
}

/// The deduplicated style tables built from a workbook.
#[derive(Debug, Clone, Default)]
pub struct StyleTables {
    /// Every distinct style used by the workbook, in `cellXfs` order.
    pub style_list: Vec<Style>,
    /// Style to `cellXfs` index.
    pub style_ids: HashMap<Style, StyleId>,
    /// The workbook's named styles, which `<cellStyles>` and `<cellStyleXfs>` are built from.
    pub named_styles: crate::styles::named_style::NamedStyleList,
}

impl StyleTables {
    /// The index assigned to a style, if it is in the table.
    pub fn id_for(&self, style: &Style) -> Option<StyleId> {
        self.style_ids.get(style).copied()
    }

    /// The index of the style at a position in [`StyleTables::style_list`].
    pub fn id_at(&self, position: usize) -> Option<StyleId> {
        self.style_list
            .get(position)
            .and_then(|style| self.id_for(style))
    }

    /// The number of records, including the implicit default at index 0.
    pub fn len(&self) -> usize {
        self.style_list.len() + 1
    }

    /// Whether the workbook needs no records beyond the default.
    pub fn is_empty(&self) -> bool {
        self.style_list.is_empty()
    }
}

/// Build the deduplicated style tables for a workbook.
///
/// Every distinct style across all worksheets is collected, then sorted so the assignment
/// is deterministic rather than dependent on hash iteration order.
pub fn build_style_tables(workbook: &Workbook) -> StyleTables {
    // A named style's own formatting has to be in the tables, or its `<cellStyleXfs>` record
    // points at index 0 and every style renders as Normal.
    let named_styles = workbook.named_styles.clone();
    let mut distinct: Vec<Style> = Vec::new();
    for style in named_styles.iter() {
        let mut as_style = style.to_style();
        as_style.is_static = false;
        if !distinct.contains(&as_style) {
            distinct.push(as_style);
        }
    }
    for sheet in &workbook.worksheets {
        // Row-level styles are keyed by the row number as a string.
        for style in sheet_style_values(sheet) {
            if !distinct.contains(&style) {
                distinct.push(style);
            }
        }
    }
    // Sorting by a canonical rendering gives a stable, platform-independent ordering. Python
    // relies on hash-table iteration order here, which is insertion-dependent; sorting simply
    // guarantees the output is reproducible across runs.
    distinct.sort_by_key(Style::sort_key);
    let style_ids = distinct
        .iter()
        .enumerate()
        .map(|(index, style)| (style.clone(), StyleId(index + 1)))
        .collect();
    StyleTables {
        style_list: distinct,
        style_ids,
        named_styles,
    }
}

fn sheet_style_values(sheet: &crate::worksheet::Worksheet) -> Vec<Style> {
    let mut values = Vec::new();
    for style in sheet.style_values() {
        // Loaded styles carry a flag that is not part of the visual style.
        let mut normalised = style.clone();
        normalised.is_static = false;
        if !values.contains(&normalised) {
            values.push(normalised);
        }
    }
    values
}

/// Serialise `styles.xml`.
pub fn write_style_table(workbook: &Workbook) -> String {
    let tables = build_style_tables(workbook);
    let dxf_list = workbook
        .style_properties
        .as_ref()
        .map(|properties| properties.dxf_list.clone())
        .unwrap_or_default();

    let mut root = Element::new("styleSheet");
    root.set("xmlns", SHEET_MAIN_NS);

    write_number_formats(&mut root, &tables);
    write_fonts(&mut root, &tables);
    write_fills(&mut root, &tables);
    write_borders(&mut root, &tables);
    write_cell_style_xfs(&mut root, &tables);
    write_cell_xfs(&mut root, &tables);
    write_cell_styles(&mut root, &tables.named_styles);
    write_dxfs(&mut root, &dxf_list);
    write_table_styles(&mut root);
    root.to_pretty_string()
}

/// Build the font table and its style-to-index map.
fn font_table(tables: &StyleTables) -> (Vec<String>, HashMap<Font, usize>) {
    let default = defaults();
    let mut xml = Vec::new();
    let mut indices = HashMap::new();

    // Excel requires the first font to be the default; index 0 is written below.
    xml.push(default_font_xml());
    let mut index = 1usize;
    for style in &tables.style_list {
        if style.font == default.font {
            continue;
        }
        if indices.contains_key(&style.font) {
            continue;
        }
        indices.insert(style.font.clone(), index);
        xml.push(font_xml(&style.font));
        index += 1;
    }
    (xml, indices)
}

fn default_font_xml() -> String {
    let mut font = Element::new("font");
    font.append(Element::with_attributes("sz", [("val", "11")]));
    font.append(Element::with_attributes("color", [("theme", "1")]));
    font.append(Element::with_attributes("name", [("val", "Calibri")]));
    font.append(Element::with_attributes("family", [("val", "2")]));
    font.append(Element::with_attributes("scheme", [("val", "minor")]));
    font.to_pretty_string()
}

/// A boolean as OOXML writes it: `1` and `0`, not `true` and `false`.
fn flag(value: bool) -> String {
    if value {
        "1".to_string()
    } else {
        "0".to_string()
    }
}

fn font_xml(font: &Font) -> String {
    let mut node = Element::new("font");
    node.append(Element::with_attributes(
        "sz",
        [("val", &format!("{}", font.size))],
    ));
    unpack_color(&mut node, "color", &font.color.index);
    node.append(Element::with_attributes("name", [("val", &font.name)]));
    // `family` was hard-coded to 2, which is what Excel's default font carries. A file using
    // any other family index loaded with the wrong one and saved it back, so the distinction
    // between "not set" and "set to 2" had to be kept.
    let family = if font.family < 0 {
        "2".to_string()
    } else {
        font.family.to_string()
    };
    node.append(Element::with_attributes(
        "family",
        [("val", family.as_str())],
    ));
    if font.bold {
        node.append(Element::new("b"));
    }
    if font.italic {
        node.append(Element::new("i"));
    }
    if font.strikethrough {
        node.append(Element::new("strike"));
    }
    // Every underline style, not just `single`: `doubleAccounting` is what Excel writes for a
    // double underline in an accounting format, and it was being dropped to a bare `<u/>`.
    if !font.underline.is_empty() && font.underline != Font::UNDERLINE_NONE {
        node.append(Element::with_attributes("u", [("val", &font.underline)]));
    }
    if let Some(outline) = font.outline {
        node.append(Element::with_attributes(
            "outline",
            [("val", &flag(outline))],
        ));
    }
    if let Some(shadow) = font.shadow {
        node.append(Element::with_attributes("shadow", [("val", &flag(shadow))]));
    }
    if let Some(condense) = font.condense {
        node.append(Element::with_attributes(
            "condense",
            [("val", &flag(condense))],
        ));
    }
    if let Some(extend) = font.extend {
        node.append(Element::with_attributes("extend", [("val", &flag(extend))]));
    }
    if font.charset >= 0 {
        node.append(Element::with_attributes(
            "charset",
            [("val", &font.charset.to_string())],
        ));
    }
    // A themed font names the theme slot rather than a typeface. Writing `name` as well would
    // be harmless, but omitting `scheme` would pin the font to that name and defeat the theme.
    if !font.scheme.is_empty() {
        node.append(Element::with_attributes("scheme", [("val", &font.scheme)]));
    }
    if font.superscript {
        node.append(Element::with_attributes(
            "vertAlign",
            [("val", "superscript")],
        ));
    } else if font.subscript {
        node.append(Element::with_attributes(
            "vertAlign",
            [("val", "subscript")],
        ));
    }
    node.to_pretty_string()
}

/// Build the fill table and its style-to-index map.
fn fill_table(tables: &StyleTables) -> (Vec<String>, HashMap<Fill, usize>) {
    let default = defaults();
    let mut xml = Vec::new();
    let mut indices = HashMap::new();

    xml.push(plain_fill_xml("none"));
    xml.push(plain_fill_xml("gray125"));
    let mut index = 2usize;
    for style in &tables.style_list {
        if style.fill == default.fill {
            continue;
        }
        if indices.contains_key(&style.fill) {
            continue;
        }
        indices.insert(style.fill.clone(), index);
        xml.push(fill_xml(&style.fill, &default.fill));
        index += 1;
    }
    (xml, indices)
}

/// A `<gradientFill>` element.
///
/// `degree` is only meaningful for a linear gradient; a path gradient uses the direction
/// attributes instead, and Excel ignores `degree` on one. The stops go inside in position
/// order, which is the order they were created in.
fn gradient_xml(fill: &Fill) -> Element {
    let gradient_type = fill
        .fill_type
        .clone()
        .unwrap_or_else(|| Fill::FILL_GRADIENT_LINEAR.to_string());
    let mut attributes: Vec<(&str, String)> = vec![("type", gradient_type.clone())];
    if gradient_type == Fill::FILL_GRADIENT_LINEAR && fill.rotation != 0 {
        attributes.push(("degree", fill.rotation.to_string()));
    }
    let mut node = Element::with_attributes("gradientFill", attributes);
    for stop in &fill.stops {
        let mut child = Element::with_attributes(
            "stop",
            [(
                "position",
                crate::xml::functions::safe_string(stop.position),
            )],
        );
        unpack_color(&mut child, "color", &stop.color.index);
        node.append(child);
    }
    node
}

fn plain_fill_xml(pattern: &str) -> String {
    let mut fill = Element::new("fill");
    fill.append(Element::with_attributes(
        "patternFill",
        [("patternType", pattern)],
    ));
    fill.to_pretty_string()
}

fn fill_xml(fill: &Fill, default: &Fill) -> String {
    let mut node = Element::new("fill");
    if fill.is_gradient() {
        node.append(gradient_xml(fill));
        return node.to_pretty_string();
    }
    if fill.fill_type.as_deref() == default.fill_type.as_deref() {
        return node.to_pretty_string();
    }
    // A fill with no pattern type is serialised as an empty `patternFill` element.
    let pattern = fill.fill_type.clone().unwrap_or_default();
    let mut pattern_node = Element::with_attributes("patternFill", [("patternType", &pattern)]);
    if fill.start_color != default.start_color {
        unpack_color(&mut pattern_node, "fgColor", &fill.start_color.index);
    }
    if fill.end_color != default.end_color {
        unpack_color(&mut pattern_node, "bgColor", &fill.end_color.index);
    }
    node.append(pattern_node);
    node.to_pretty_string()
}

/// Build the border table and its style-to-index map.
fn border_table(
    tables: &StyleTables,
) -> (Vec<String>, HashMap<crate::styles::borders::Borders, usize>) {
    let default = defaults();
    let mut xml = Vec::new();
    let mut indices = HashMap::new();

    xml.push(default_borders_xml());
    let mut index = 1usize;
    for style in &tables.style_list {
        if style.borders == default.borders {
            continue;
        }
        if indices.contains_key(&style.borders) {
            continue;
        }
        indices.insert(style.borders.clone(), index);
        xml.push(borders_xml(&style.borders));
        index += 1;
    }
    (xml, indices)
}

fn default_borders_xml() -> String {
    let mut border = Element::new("border");
    for side in ["left", "right", "top", "bottom", "diagonal"] {
        border.append(Element::new(side));
    }
    border.to_pretty_string()
}

fn borders_xml(borders: &crate::styles::borders::Borders) -> String {
    let mut node = Element::new("border");
    for (side, border) in [
        ("left", &borders.left),
        ("right", &borders.right),
        ("top", &borders.top),
        ("bottom", &borders.bottom),
        ("diagonal", &borders.diagonal),
    ] {
        let mut side_node = Element::new(side);
        match border.border_style.as_deref() {
            None | Some(Border::BORDER_NONE) => {}
            Some(style) => {
                side_node.set("style", style);
                unpack_color(&mut side_node, "color", &border.color.index);
            }
        }
        node.append(side_node);
    }
    node.to_pretty_string()
}

/// Split a colour token into `rgb`, or `theme`/`tint` when it is theme-prefixed.
fn unpack_color(parent: &mut Element, key: &str, color: &str) {
    let mut parts = color.splitn(3, ':');
    match (parts.next(), parts.next(), parts.next()) {
        (Some("theme"), Some(theme), tint) => {
            let mut node = Element::new(key);
            node.set("theme", theme);
            if let Some(tint) = tint {
                if !tint.is_empty() {
                    node.set("tint", tint);
                }
            }
            parent.append(node);
        }
        _ => {
            let mut node = Element::new(key);
            node.set("rgb", color);
            parent.append(node);
        }
    }
}

/// Build the number-format table, assigning custom ids from 165 upwards.
fn number_format_table(tables: &StyleTables) -> (HashMap<NumberFormat, u32>, Vec<(u32, String)>) {
    let mut ids = HashMap::new();
    let mut customs = Vec::new();
    let mut next_id = FIRST_CUSTOM_FORMAT_ID;
    for style in &tables.style_list {
        if ids.contains_key(&style.number_format) {
            continue;
        }
        let code = style.number_format.format_code().to_string();
        match style.number_format.builtin_id() {
            Some(builtin) => {
                ids.insert(style.number_format.clone(), builtin);
            }
            None => {
                ids.insert(style.number_format.clone(), next_id);
                customs.push((next_id, code));
                next_id += 1;
            }
        }
    }
    (ids, customs)
}

fn write_number_formats(root: &mut Element, tables: &StyleTables) {
    let (_, customs) = number_format_table(tables);
    let mut node = Element::new("numFmts");
    node.set("count", customs.len().to_string());
    for (id, code) in customs {
        node.append(Element::with_attributes(
            "numFmt",
            [("numFmtId", &id.to_string()), ("formatCode", &code)],
        ));
    }
    root.append(node);
}

fn write_fonts(root: &mut Element, tables: &StyleTables) {
    let (xml, _) = font_table(tables);
    let mut node = Element::new("fonts");
    node.set("count", xml.len().to_string());
    for entry in xml {
        node.append(crate::xml::functions::fromstring(entry.as_bytes()).unwrap_or_default());
    }
    root.append(node);
}

fn write_fills(root: &mut Element, tables: &StyleTables) {
    let (xml, _) = fill_table(tables);
    let mut node = Element::new("fills");
    node.set("count", xml.len().to_string());
    for entry in xml {
        node.append(crate::xml::functions::fromstring(entry.as_bytes()).unwrap_or_default());
    }
    root.append(node);
}

fn write_borders(root: &mut Element, tables: &StyleTables) {
    let (xml, _) = border_table(tables);
    let mut node = Element::new("borders");
    node.set("count", xml.len().to_string());
    for entry in xml {
        node.append(crate::xml::functions::fromstring(entry.as_bytes()).unwrap_or_default());
    }
    root.append(node);
}

/// Write `<cellStyleXfs>`: the formatting behind each named style.
///
/// One record per named style, in list order, because a `<cellStyle>`'s `xfId` is an index
/// into this block. It was a single hard-coded record before, so a workbook with named styles
/// written every one of them pointing at the default formatting -- which Excel shows as
/// "Normal" under every name.
fn write_cell_style_xfs(root: &mut Element, tables: &StyleTables) {
    // The same tables `cellXfs` uses, so a named style's record points at the font and fill
    // that record describes rather than at index 0.
    let (_, fonts) = font_table(tables);
    let (_, fills) = fill_table(tables);
    let (_, borders) = border_table(tables);
    let named = &tables.named_styles;

    let mut xfs = Element::new("cellStyleXfs");
    let count = named.len().max(1).to_string();
    xfs.set("count", count.as_str());
    if named.is_empty() {
        xfs.append(Element::with_attributes(
            "xf",
            [
                ("numFmtId", "0"),
                ("fontId", "0"),
                ("fillId", "0"),
                ("borderId", "0"),
            ],
        ));
        root.append(xfs);
        return;
    }
    for style in named.iter() {
        let mut attributes: Vec<(&str, String)> = Vec::new();
        attributes.push((
            "numFmtId",
            format!("{}", number_format_id(&style.number_format)),
        ));
        attributes.push((
            "fontId",
            fonts.get(&style.font).copied().unwrap_or(0).to_string(),
        ));
        attributes.push((
            "fillId",
            fills.get(&style.fill).copied().unwrap_or(0).to_string(),
        ));
        attributes.push((
            "borderId",
            borders.get(&style.border).copied().unwrap_or(0).to_string(),
        ));
        // `alignment` lives on the cell's own `xf`, not on the style record: a named style
        // supplies the font and fill, and Excel resolves the alignment from the cell. Only
        // the flag that says the record carries one is written here.
        if style.alignment != Alignment::new() {
            attributes.push(("applyAlignment", "1".to_string()));
        }
        xfs.append(Element::with_attributes("xf", attributes));
    }
    root.append(xfs);
}

/// Write `<cellStyles>`: the names, each pointing at its record in `<cellStyleXfs>`.
fn write_cell_styles(root: &mut Element, named: &crate::styles::named_style::NamedStyleList) {
    let mut node = Element::new("cellStyles");
    let count = named.len().max(1).to_string();
    node.set("count", count.as_str());
    if named.is_empty() {
        node.append(Element::with_attributes(
            "cellStyle",
            [("name", "Normal"), ("xfId", "0"), ("builtinId", "0")],
        ));
        root.append(node);
        return;
    }
    for (index, style) in named.iter().enumerate() {
        let mut attributes: Vec<(&str, String)> =
            vec![("name", style.name.clone()), ("xfId", index.to_string())];
        if let Some(id) = &style.builtin_id {
            attributes.push(("builtinId", id.clone()));
        }
        if style.hidden == Some(true) {
            attributes.push(("hidden", "1".to_string()));
        }
        node.append(Element::with_attributes("cellStyle", attributes));
    }
    root.append(node);
}

/// The `numFmtId` a number format needs, registering a custom code at 164 or above.
///
/// openpyxl's rule: below 164 is the built-in range, above it is the workbook's own table.
/// Getting this wrong shows a cell with the wrong format rather than an error.
fn number_format_id(format: &crate::styles::numbers::NumberFormat) -> u32 {
    let code = format.format_code();
    if code == crate::styles::numbers::NumberFormat::FORMAT_GENERAL {
        return 0;
    }
    for (id, builtin) in crate::styles::numbers::BUILTIN_FORMATS.iter() {
        if *builtin == code {
            return *id;
        }
    }
    164
}

/// The `<cellStyleXfs>` index of the named style this cell's formatting came from.
///
/// A match has to be exact: a cell the user has since altered no longer *is* the named style,
/// and pointing it at one anyway would make Excel's "modify style" edit cells the user never
/// asked it to touch. Returning `None` sends it to `Normal` instead, which is at least true.
fn matching_named_style_index(tables: &StyleTables, style: &Style) -> Option<usize> {
    tables.named_styles.iter().position(|named| {
        let mut candidate = named.to_style();
        // `build_style_tables` clears this when it seeds the table; the flag is bookkeeping and
        // excluded from equality anyway, so leaving it set here changes nothing either way.
        candidate.is_static = style.is_static;
        candidate == *style
    })
}

fn write_cell_xfs(root: &mut Element, tables: &StyleTables) {
    let default = defaults();
    let (number_formats, _) = number_format_table(tables);
    let (_, fonts) = font_table(tables);
    let (_, fills) = fill_table(tables);
    let (_, borders) = border_table(tables);

    let mut xfs = Element::new("cellXfs");
    xfs.set("count", tables.len().to_string());
    // Index 0 is always the default.
    xfs.append(Element::with_attributes(
        "xf",
        [
            ("numFmtId", "0"),
            ("fontId", "0"),
            ("fillId", "0"),
            ("xfId", "0"),
            ("borderId", "0"),
        ],
    ));
    for style in &tables.style_list {
        let mut node = Element::new("xf");
        node.set("numFmtId", "0");
        node.set("fontId", "0");
        node.set("fillId", "0");
        // `xfId` is the index into `<cellStyleXfs>` that this cell's formatting came from.
        // Writing 0 unconditionally claims every cell derives from Normal, which is why
        // `cell.style` read back `'Normal'` in openpyxl even for a cell carrying Good's
        // colours. A cell whose formatting matches a named style points at it; one the user
        // has since tweaked away from it points at Normal, which is the honest answer.
        let xf_id = matching_named_style_index(tables, style)
            .unwrap_or(0)
            .to_string();
        node.set("xfId", xf_id.as_str());
        node.set("borderId", "0");
        // The number format's id is always written, but the flag that says to apply it was
        // not. Excel reads the id regardless, which is why nothing looked wrong -- and a
        // stricter reader would show a cell with the wrong format.
        if style.number_format != default.number_format {
            node.set("applyNumberFormat", "1");
        }
        if style.font != default.font {
            node.set("fontId", fonts.get(&style.font).unwrap_or(&0).to_string());
            node.set("applyFont", "1");
        }
        if style.borders != default.borders {
            node.set(
                "borderId",
                borders.get(&style.borders).unwrap_or(&0).to_string(),
            );
            node.set("applyBorder", "1");
        }
        // A quote prefix is a *style* property, not a cell value: it makes Excel treat a
        // leading apostrophe as part of the display rather than as text that was escaped.
        // It has to survive a round trip or a numeric-looking string changes meaning.
        if style.quote_prefix {
            node.set("quotePrefix", "1");
        }
        if style.pivot_button {
            node.set("pivotButton", "1");
        }
        if style.fill != default.fill {
            node.set("fillId", fills.get(&style.fill).unwrap_or(&0).to_string());
            node.set("applyFill", "1");
        }
        if style.number_format != default.number_format {
            let id = number_formats
                .get(&style.number_format)
                .copied()
                .unwrap_or(0);
            node.set("numFmtId", id.to_string());
            node.set("applyNumberFormat", "1");
        }
        if style.alignment != default.alignment {
            node.set("applyAlignment", "1");
            let attributes = alignment_attributes(&style.alignment);
            if !attributes.is_empty() {
                node.append(Element::with_attributes("alignment", attributes));
            }
        }
        if style.protection != default.protection {
            node.set("applyProtection", "1");
            let attributes = style.protection.attributes();
            if !attributes.is_empty() {
                node.append(Element::with_attributes("protection", attributes));
            }
        }
        xfs.append(node);
    }
    root.append(xfs);
}

/// The `<alignment/>` attributes for a style that deviates from the default.
fn alignment_attributes(alignment: &Alignment) -> Vec<(String, String)> {
    alignment.attributes()
}

fn write_dxfs(root: &mut Element, dxf_list: &[crate::formatting::DxfStyle]) {
    let mut dxfs = Element::new("dxfs");
    dxfs.set("count", dxf_list.len().to_string());
    for dxf in dxf_list {
        let mut node = Element::new("dxf");
        if let Some(font) = &dxf.font {
            let mut font_node = Element::new("font");
            unpack_color(&mut font_node, "color", &font.color.index);
            if font.bold {
                font_node.append(Element::with_attributes("b", [("val", "1")]));
            }
            if font.italic {
                font_node.append(Element::with_attributes("i", [("val", "1")]));
            }
            if font.underline != Font::UNDERLINE_NONE {
                font_node.append(Element::with_attributes("u", [("val", &font.underline)]));
            }
            if font.strikethrough {
                font_node.append(Element::new("strike"));
            }
            node.append(font_node);
        }
        if let Some(fill) = &dxf.fill {
            let default = defaults();
            let mut fill_node = Element::new("fill");
            let mut pattern = match &fill.fill_type {
                Some(pattern) => {
                    Element::with_attributes("patternFill", [("patternType", pattern)])
                }
                None => Element::new("patternFill"),
            };
            if fill.start_color != default.fill.start_color {
                unpack_color(&mut pattern, "fgColor", &fill.start_color.index);
            }
            if fill.end_color != default.fill.end_color {
                unpack_color(&mut pattern, "bgColor", &fill.end_color.index);
            }
            fill_node.append(pattern);
            node.append(fill_node);
        }
        if let Some(borders) = &dxf.border {
            let mut border_node = Element::new("border");
            for (side, border) in [
                ("left", &borders.left),
                ("right", &borders.right),
                ("top", &borders.top),
                ("bottom", &borders.bottom),
            ] {
                let mut side_node = Element::new(side);
                match border.border_style.as_deref() {
                    None | Some(Border::BORDER_NONE) => {}
                    Some(style) => {
                        side_node.set("style", style);
                        unpack_color(&mut side_node, "color", &border.color.index);
                    }
                }
                border_node.append(side_node);
            }
            node.append(border_node);
        }
        dxfs.append(node);
    }
    root.append(dxfs);
}

fn write_table_styles(root: &mut Element) {
    root.append(Element::with_attributes(
        "tableStyles",
        [
            ("count", "0"),
            ("defaultTableStyle", "TableStyleMedium9"),
            ("defaultPivotStyle", "PivotStyleLight16"),
        ],
    ));
}

/// Serialise the protection attributes for a style.
pub fn protection_attributes(protection: &Protection) -> Vec<(String, String)> {
    if protection.locked == ProtectionFlag::Protected
        && protection.hidden == ProtectionFlag::Protected
    {
        vec![
            ("locked".to_string(), "1".to_string()),
            ("hidden".to_string(), "1".to_string()),
        ]
    } else {
        protection.attributes()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cell::CellValue;
    use crate::styles::colors::Color;
    use crate::styles::style::Style;
    use crate::xml::functions::fromstring;

    fn workbook_with_styles() -> Workbook {
        let mut workbook = Workbook::new();
        let context = workbook.cell_context();
        {
            let sheet = &mut workbook.worksheets[0];
            let mut bold = Style::new();
            bold.font.bold = true;
            bold.font.name = "Arial".to_string();
            bold.font.size = 14.0;
            bold.set_number_format_code("0.00%");
            let mut filled = Style::new();
            filled.fill = crate::styles::Fill::solid(Color::new("FFFF0000"));
            filled.alignment = crate::styles::Alignment::new()
                .with_horizontal("center")
                .with_wrap_text(true);
            sheet.context = context;
            sheet.set("A1", CellValue::text("a")).unwrap();
            sheet.set_style("A1", bold).unwrap();
            sheet.set("A2", CellValue::text("b")).unwrap();
            sheet.set_style("A2", filled).unwrap();
            sheet.set("B1", CellValue::text("c")).unwrap();
        }
        workbook
    }

    #[test]
    fn deduplicates_styles() {
        let workbook = workbook_with_styles();
        let tables = build_style_tables(&workbook);
        assert_eq!(tables.style_list.len(), 2);
        assert_eq!(tables.len(), 3, "index 0 is the implicit default");
    }

    #[test]
    fn identical_styles_share_an_index() {
        let mut workbook = Workbook::new();
        let style = Style::new();
        {
            let sheet = &mut workbook.worksheets[0];
            sheet.set("A1", CellValue::text("a")).unwrap();
            sheet.set("A2", CellValue::text("b")).unwrap();
            sheet.set_style("A1", style.clone()).unwrap();
            sheet.set_style("A2", style).unwrap();
        }
        let tables = build_style_tables(&workbook);
        assert_eq!(tables.style_list.len(), 1);
    }

    #[test]
    fn custom_number_formats_start_at_165() {
        let mut workbook = Workbook::new();
        {
            let sheet = &mut workbook.worksheets[0];
            let mut style = Style::new();
            style.set_number_format_code("0.000");
            sheet.set("A1", CellValue::text("a")).unwrap();
            sheet.set_style("A1", style).unwrap();
        }
        let tables = build_style_tables(&workbook);
        let (ids, customs) = number_format_table(&tables);
        assert_eq!(customs.len(), 1);
        assert_eq!(customs[0].0, FIRST_CUSTOM_FORMAT_ID);
        let format = NumberFormat::with_code("0.000");
        assert_eq!(ids.get(&format), Some(&165));
    }

    #[test]
    fn builtin_number_formats_reuse_their_id() {
        let mut workbook = Workbook::new();
        {
            let sheet = &mut workbook.worksheets[0];
            let mut style = Style::new();
            style.set_number_format_code("0.00%");
            sheet.set("A1", CellValue::text("a")).unwrap();
            sheet.set_style("A1", style).unwrap();
        }
        let tables = build_style_tables(&workbook);
        let (ids, customs) = number_format_table(&tables);
        assert!(customs.is_empty());
        assert_eq!(ids.get(&NumberFormat::with_code("0.00%")), Some(&10));
    }

    #[test]
    fn stylesheet_is_well_formed_and_complete() {
        let workbook = workbook_with_styles();
        let xml = write_style_table(&workbook);
        let root = fromstring(xml.as_bytes()).expect("styles.xml must parse");
        for section in [
            "numFmts",
            "fonts",
            "fills",
            "borders",
            "cellStyleXfs",
            "cellXfs",
            "cellStyles",
            "dxfs",
            "tableStyles",
        ] {
            assert!(root.find(section).is_some(), "missing {section}");
        }
    }

    #[test]
    fn cell_xfs_count_matches_the_tables() {
        let workbook = workbook_with_styles();
        let xml = write_style_table(&workbook);
        let root = fromstring(xml.as_bytes()).unwrap();
        let xfs = root.find("cellXfs").unwrap();
        assert_eq!(xfs.get("count"), Some("3"));
        assert_eq!(xfs.children().len(), 3);
    }

    #[test]
    fn non_default_styles_carry_apply_flags() {
        let workbook = workbook_with_styles();
        let root = fromstring(write_style_table(&workbook).as_bytes()).unwrap();
        let xfs = root.find("cellXfs").unwrap();
        let applied: Vec<&str> = xfs
            .children()
            .iter()
            .skip(1)
            .filter_map(|node| node.get("applyFont").or_else(|| node.get("applyFill")))
            .collect();
        assert!(!applied.is_empty());
    }

    #[test]
    fn theme_colours_are_split_into_theme_and_tint() {
        let mut node = Element::new("font");
        unpack_color(&mut node, "color", "theme:9:0.5");
        let child = node.children()[0].clone();
        assert_eq!(child.get("theme"), Some("9"));
        assert_eq!(child.get("tint"), Some("0.5"));
        assert_eq!(child.get("rgb"), None);

        let mut node = Element::new("font");
        unpack_color(&mut node, "color", "theme:9:");
        let child = node.children()[0].clone();
        assert_eq!(child.get("theme"), Some("9"));
        assert_eq!(child.get("tint"), None);

        let mut node = Element::new("font");
        unpack_color(&mut node, "color", "FFFF0000");
        let child = node.children()[0].clone();
        assert_eq!(child.get("rgb"), Some("FFFF0000"));
        assert_eq!(child.get("theme"), None);
    }

    #[test]
    fn default_fills_are_always_written() {
        let root = fromstring(write_style_table(&Workbook::new()).as_bytes()).unwrap();
        let fills = root.find("fills").unwrap();
        assert_eq!(fills.get("count"), Some("2"));
        let patterns: Vec<Option<&str>> = fills
            .children()
            .iter()
            .map(|fill| fill.find("patternFill").and_then(|p| p.get("patternType")))
            .collect();
        assert_eq!(patterns, vec![Some("none"), Some("gray125")]);
    }

    #[test]
    fn dxf_styles_are_emitted_when_present() {
        let mut workbook = workbook_with_styles();
        let mut properties = workbook.style_properties.clone().unwrap_or_default();
        let mut dxf = crate::formatting::DxfStyle::default();
        let mut font = Font::new();
        font.bold = true;
        font.color = Color::new("FFFF0000");
        dxf.font = Some(font);
        properties.dxf_list.push(dxf);
        workbook.style_properties = Some(properties);

        let root = fromstring(write_style_table(&workbook).as_bytes()).unwrap();
        let dxfs = root.find("dxfs").unwrap();
        assert_eq!(dxfs.get("count"), Some("1"));
        let font_node = dxfs.children()[0].find("font").unwrap();
        assert!(font_node.find("b").is_some());
    }

    #[test]
    fn empty_dxf_list_is_written_as_zero() {
        let root = fromstring(write_style_table(&Workbook::new()).as_bytes()).unwrap();
        assert_eq!(root.find("dxfs").unwrap().get("count"), Some("0"));
    }

    #[test]
    fn style_lookup_by_identity() {
        let workbook = workbook_with_styles();
        let tables = build_style_tables(&workbook);
        let style = &tables.style_list[0];
        assert_eq!(tables.id_for(style), Some(StyleId(1)));
        assert_eq!(tables.id_at(0), Some(StyleId(1)));
        assert_eq!(tables.id_at(99), None);
    }

    #[test]
    fn protection_attributes_match_python_rules() {
        let both = Protection {
            locked: ProtectionFlag::Protected,
            hidden: ProtectionFlag::Protected,
        };
        assert_eq!(
            protection_attributes(&both),
            vec![
                ("locked".to_string(), "1".to_string()),
                ("hidden".to_string(), "1".to_string())
            ]
        );
        let mixed = Protection {
            locked: ProtectionFlag::Unprotected,
            hidden: ProtectionFlag::Inherit,
        };
        assert_eq!(
            protection_attributes(&mixed),
            vec![("locked".to_string(), "0".to_string())]
        );
    }

    #[test]
    fn negative_text_rotation_is_encoded_in_alignment() {
        let alignment = Alignment::new().with_text_rotation(-45);
        let attrs = alignment_attributes(&alignment);
        assert!(attrs.iter().any(|(k, v)| k == "textRotation" && v == "135"));
    }

    #[test]
    fn a_gradient_fill_survives_a_package_round_trip() {
        // This is the test the missing gradient branch failed: a workbook using one loaded
        // with every cell falling back to a plain fill, silently, and it looked correct
        // because a missing gradient is just a background colour.
        use crate::cell::cell::CellValue;
        use crate::styles::colors::Color;
        use crate::styles::fills::Fill;
        use crate::workbook::Workbook;

        let gradient = Fill::linear_gradient(&[Color::new("FF102030"), Color::new("FFA0B0C0")]);
        let mut workbook = Workbook::new();
        let sheet = workbook.active_sheet_mut().expect("sheet");
        sheet.set("A1", CellValue::text("x")).expect("cell");
        sheet
            .set_style(
                "A1",
                crate::styles::style::Style {
                    fill: gradient.clone(),
                    ..crate::styles::style::Style::default()
                },
            )
            .expect("styled");
        let bytes = workbook.to_bytes().expect("saved");

        let loaded = crate::reader::excel::load_workbook_from_bytes(bytes, Default::default())
            .expect("loaded");
        let style = loaded.worksheets[0].get_style("A1");

        assert!(style.fill.is_gradient(), "the fill became {:?}", style.fill);
        assert_eq!(
            style.fill.fill_type.as_deref(),
            Some(Fill::FILL_GRADIENT_LINEAR)
        );
        assert_eq!(style.fill.stops.len(), 2);
        assert_eq!(style.fill.stops[0].color.index, "FF102030");
        assert_eq!(style.fill.stops[1].color.index, "FFA0B0C0");
    }
}

#[cfg(test)]
mod named_style_tests {
    use super::*;
    use crate::cell::cell::CellValue;
    use crate::styles::fills::Fill;
    use crate::styles::fonts::Font;
    use crate::styles::named_style::NamedStyle;
    use crate::xml::functions::fromstring;

    /// Every `xf` in `<cellXfs>` as `(xfId, fillId)`.
    fn cell_xfs(xml: &str) -> Vec<(String, String)> {
        let root = fromstring(xml.as_bytes()).expect("parses");
        root.find("cellXfs")
            .expect("cellXfs")
            .children()
            .into_iter()
            .map(|xf| {
                let attribute = |name: &str| xf.get(name).unwrap_or("0").to_string();
                (attribute("xfId"), attribute("fillId"))
            })
            .collect()
    }

    fn workbook_with_a_named_style() -> Workbook {
        let mut workbook = Workbook::new();
        workbook
            .add_named_style(
                NamedStyle::new("Band")
                    .with_number_format("0.00%")
                    .with_font(Font::new().with_bold(true)),
            )
            .expect("registered");
        workbook
            .active_sheet_mut()
            .expect("sheet")
            .set("A1", CellValue::number(0.5))
            .expect("cell");
        workbook
            .apply_named_style(0, "A1", "Band")
            .expect("applied");
        workbook
    }

    #[test]
    fn a_cell_whose_formatting_matches_a_named_style_points_at_it() {
        // This is what makes openpyxl report `cell.style` as the name rather than "Normal".
        let workbook = workbook_with_a_named_style();
        let xml = write_style_table(&workbook);
        let band = workbook
            .named_styles
            .index_of("Band")
            .expect("Band is at an index")
            .to_string();

        let xfs = cell_xfs(&xml);
        // The default xf at 0 stays at xfId 0, which is Normal by construction.
        assert_eq!(xfs[0].0, "0", "the default xf is Normal");
        assert!(
            xfs.iter().any(|(xf_id, _)| *xf_id == band),
            "some xf points at Band's index {band}: {xfs:?}"
        );
    }

    #[test]
    fn an_untouched_cell_points_at_normal() {
        let mut workbook = Workbook::new();
        workbook
            .active_sheet_mut()
            .expect("sheet")
            .set("A1", CellValue::number(1.0))
            .expect("cell");
        workbook
            .add_named_style(NamedStyle::new("Band").with_font(Font::new().with_bold(true)))
            .expect("registered");
        let xml = write_style_table(&workbook);
        let xfs = cell_xfs(&xml);
        // `build_style_tables` seeds `<cellXfs>` with each named style's formatting so that a
        // cell matching one can share its entry. That leaves an unreferenced echo of Band at
        // the end, which costs a few bytes and changes nothing. What must not happen is the
        // *cell's* xf claiming Band, and the cell's xf is the first after the synthetic
        // default.
        assert_eq!(xfs[0].0, "0", "the synthetic default is Normal");
        assert_eq!(xfs[1].0, "0", "the unstyled cell is Normal");
        let claiming_band = xfs.iter().filter(|(xf_id, _)| *xf_id == "1").count();
        assert_eq!(
            claiming_band, 1,
            "only Band's own echo references it: {xfs:?}"
        );
    }

    #[test]
    fn a_style_the_user_altered_no_longer_points_at_the_named_style() {
        let mut workbook = workbook_with_a_named_style();
        let sheet = workbook.active_sheet_mut().expect("sheet");
        let mut style = sheet.get_style("A1");
        style.fill = Fill {
            fill_type: Some(Fill::FILL_SOLID.to_string()),
            start_color: crate::styles::colors::Color::new("FFFF0000"),
            ..Fill::new()
        };
        sheet.set_style("A1", style).expect("restyled");

        let xml = write_style_table(&workbook);
        let band = workbook
            .named_styles
            .index_of("Band")
            .expect("Band")
            .to_string();
        let xfs = cell_xfs(&xml);
        // The filled xf is the altered cell's, and it must not still claim to be Band --
        // otherwise editing "Band" in Excel would silently restyle a cell the user had
        // already moved on from.
        let filled = xfs
            .iter()
            .find(|(_, fill_id)| fill_id != "0")
            .expect("the altered cell has a fill");
        assert_ne!(
            filled.0, band,
            "the altered cell must not point at Band: {xfs:?}"
        );
    }
}