rustypyxl 0.7.1

Fast, dependency-light Rust library for reading and writing Excel (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
//! Conditional formatting support for Excel workbooks.
//!
//! This module provides structures for creating and managing conditional formatting rules.

/// Type of conditional formatting rule.
#[derive(Clone, Debug, PartialEq)]
pub enum ConditionalFormatType {
    /// Format based on cell value.
    CellIs,
    /// Format based on formula result.
    Expression,
    /// Color scale (gradient).
    ColorScale,
    /// Data bar.
    DataBar,
    /// Icon set.
    IconSet,
    /// Top/bottom N values.
    Top10,
    /// Above/below average.
    AboveAverage,
    /// Duplicate values.
    DuplicateValues,
    /// Unique values.
    UniqueValues,
    /// Text contains.
    ContainsText,
    /// Text does not contain.
    NotContainsText,
    /// Text begins with.
    BeginsWith,
    /// Text ends with.
    EndsWith,
    /// Contains blanks.
    ContainsBlanks,
    /// Contains no blanks.
    NotContainsBlanks,
    /// Contains errors.
    ContainsErrors,
    /// Contains no errors.
    NotContainsErrors,
    /// Time period (today, yesterday, this week, etc.).
    TimePeriod,
}

impl ConditionalFormatType {
    /// Get the cfRule type attribute value.
    pub fn xml_value(&self) -> &'static str {
        match self {
            ConditionalFormatType::CellIs => "cellIs",
            ConditionalFormatType::Expression => "expression",
            ConditionalFormatType::ColorScale => "colorScale",
            ConditionalFormatType::DataBar => "dataBar",
            ConditionalFormatType::IconSet => "iconSet",
            ConditionalFormatType::Top10 => "top10",
            ConditionalFormatType::AboveAverage => "aboveAverage",
            ConditionalFormatType::DuplicateValues => "duplicateValues",
            ConditionalFormatType::UniqueValues => "uniqueValues",
            ConditionalFormatType::ContainsText => "containsText",
            ConditionalFormatType::NotContainsText => "notContainsText",
            ConditionalFormatType::BeginsWith => "beginsWith",
            ConditionalFormatType::EndsWith => "endsWith",
            ConditionalFormatType::ContainsBlanks => "containsBlanks",
            ConditionalFormatType::NotContainsBlanks => "notContainsBlanks",
            ConditionalFormatType::ContainsErrors => "containsErrors",
            ConditionalFormatType::NotContainsErrors => "notContainsErrors",
            ConditionalFormatType::TimePeriod => "timePeriod",
        }
    }

    /// Parse the cfRule type attribute back into a rule type.
    pub fn from_xml(value: &str) -> Option<Self> {
        Some(match value {
            "cellIs" => ConditionalFormatType::CellIs,
            "expression" => ConditionalFormatType::Expression,
            "colorScale" => ConditionalFormatType::ColorScale,
            "dataBar" => ConditionalFormatType::DataBar,
            "iconSet" => ConditionalFormatType::IconSet,
            "top10" => ConditionalFormatType::Top10,
            "aboveAverage" => ConditionalFormatType::AboveAverage,
            "duplicateValues" => ConditionalFormatType::DuplicateValues,
            "uniqueValues" => ConditionalFormatType::UniqueValues,
            "containsText" => ConditionalFormatType::ContainsText,
            "notContainsText" => ConditionalFormatType::NotContainsText,
            "beginsWith" => ConditionalFormatType::BeginsWith,
            "endsWith" => ConditionalFormatType::EndsWith,
            "containsBlanks" => ConditionalFormatType::ContainsBlanks,
            "notContainsBlanks" => ConditionalFormatType::NotContainsBlanks,
            "containsErrors" => ConditionalFormatType::ContainsErrors,
            "notContainsErrors" => ConditionalFormatType::NotContainsErrors,
            "timePeriod" => ConditionalFormatType::TimePeriod,
            _ => return None,
        })
    }
}

/// Operator for cell value comparisons.
#[derive(Clone, Debug, PartialEq)]
pub enum ConditionalOperator {
    /// Less than.
    LessThan,
    /// Less than or equal.
    LessThanOrEqual,
    /// Equal.
    Equal,
    /// Not equal.
    NotEqual,
    /// Greater than or equal.
    GreaterThanOrEqual,
    /// Greater than.
    GreaterThan,
    /// Between (inclusive).
    Between,
    /// Not between.
    NotBetween,
}

impl ConditionalOperator {
    /// Parse the XML attribute value back into an operator.
    pub fn from_xml(value: &str) -> Option<Self> {
        Some(match value {
            "lessThan" => ConditionalOperator::LessThan,
            "lessThanOrEqual" => ConditionalOperator::LessThanOrEqual,
            "equal" => ConditionalOperator::Equal,
            "notEqual" => ConditionalOperator::NotEqual,
            "greaterThanOrEqual" => ConditionalOperator::GreaterThanOrEqual,
            "greaterThan" => ConditionalOperator::GreaterThan,
            "between" => ConditionalOperator::Between,
            "notBetween" => ConditionalOperator::NotBetween,
            _ => return None,
        })
    }

    /// Get the XML attribute value for this operator.
    pub fn xml_value(&self) -> &'static str {
        match self {
            ConditionalOperator::LessThan => "lessThan",
            ConditionalOperator::LessThanOrEqual => "lessThanOrEqual",
            ConditionalOperator::Equal => "equal",
            ConditionalOperator::NotEqual => "notEqual",
            ConditionalOperator::GreaterThanOrEqual => "greaterThanOrEqual",
            ConditionalOperator::GreaterThan => "greaterThan",
            ConditionalOperator::Between => "between",
            ConditionalOperator::NotBetween => "notBetween",
        }
    }
}

/// Color for conditional formatting.
#[derive(Clone, Debug, PartialEq)]
pub struct ConditionalColor {
    /// RGB color value (e.g., "FF0000" for red).
    pub rgb: Option<String>,
    /// Theme color index.
    pub theme: Option<u32>,
    /// Tint value (-1.0 to 1.0).
    pub tint: Option<f64>,
}

impl ConditionalColor {
    /// Create a color from RGB hex string.
    pub fn rgb<S: Into<String>>(color: S) -> Self {
        ConditionalColor {
            rgb: Some(color.into()),
            theme: None,
            tint: None,
        }
    }

    /// Create a color from theme index.
    pub fn theme(index: u32) -> Self {
        ConditionalColor {
            rgb: None,
            theme: Some(index),
            tint: None,
        }
    }

    /// Common colors.
    pub fn red() -> Self {
        Self::rgb("FFFF0000")
    }

    pub fn green() -> Self {
        Self::rgb("FF00FF00")
    }

    pub fn yellow() -> Self {
        Self::rgb("FFFFFF00")
    }

    pub fn blue() -> Self {
        Self::rgb("FF0000FF")
    }

    pub fn white() -> Self {
        Self::rgb("FFFFFFFF")
    }
}

/// Color scale configuration (2 or 3 colors).
#[derive(Clone, Debug)]
pub struct ColorScale {
    /// Minimum value color.
    pub min_color: ConditionalColor,
    /// Middle value color (for 3-color scale).
    pub mid_color: Option<ConditionalColor>,
    /// Maximum value color.
    pub max_color: ConditionalColor,
    /// Minimum value type: "min", "num", "percent", "formula", "percentile".
    pub min_type: String,
    /// Minimum value (if type is "num", "percent", etc.).
    pub min_value: Option<String>,
    /// Middle value type.
    pub mid_type: Option<String>,
    /// Middle value.
    pub mid_value: Option<String>,
    /// Maximum value type.
    pub max_type: String,
    /// Maximum value.
    pub max_value: Option<String>,
}

impl ColorScale {
    /// Create a 2-color scale (min to max).
    pub fn two_color(min_color: ConditionalColor, max_color: ConditionalColor) -> Self {
        ColorScale {
            min_color,
            mid_color: None,
            max_color,
            min_type: "min".to_string(),
            min_value: None,
            mid_type: None,
            mid_value: None,
            max_type: "max".to_string(),
            max_value: None,
        }
    }

    /// Create a 3-color scale (min, mid, max).
    pub fn three_color(
        min_color: ConditionalColor,
        mid_color: ConditionalColor,
        max_color: ConditionalColor,
    ) -> Self {
        ColorScale {
            min_color,
            mid_color: Some(mid_color),
            max_color,
            min_type: "min".to_string(),
            min_value: None,
            mid_type: Some("percentile".to_string()),
            mid_value: Some("50".to_string()),
            max_type: "max".to_string(),
            max_value: None,
        }
    }

    /// Red-Yellow-Green scale.
    pub fn red_yellow_green() -> Self {
        Self::three_color(
            ConditionalColor::rgb("FFF8696B"),
            ConditionalColor::rgb("FFFFEB84"),
            ConditionalColor::rgb("FF63BE7B"),
        )
    }

    /// Green-Yellow-Red scale (reverse).
    pub fn green_yellow_red() -> Self {
        Self::three_color(
            ConditionalColor::rgb("FF63BE7B"),
            ConditionalColor::rgb("FFFFEB84"),
            ConditionalColor::rgb("FFF8696B"),
        )
    }
}

/// Data bar configuration.
#[derive(Clone, Debug)]
pub struct DataBar {
    /// Bar fill color.
    pub fill_color: ConditionalColor,
    /// Bar border color. NOTE: borders, solid fill, and negative colors are
    /// Excel-2010 x14 extensions; the strict OOXML dataBar element cannot
    /// express them, so these fields are not serialized yet.
    pub border_color: Option<ConditionalColor>,
    /// Minimum value type.
    pub min_type: String,
    /// Minimum value.
    pub min_value: Option<String>,
    /// Maximum value type.
    pub max_type: String,
    /// Maximum value.
    pub max_value: Option<String>,
    /// Show value in cell.
    pub show_value: bool,
    /// Gradient fill.
    pub gradient: bool,
    /// Negative bar color.
    pub negative_color: Option<ConditionalColor>,
}

impl DataBar {
    /// Create a new data bar with default settings.
    pub fn new() -> Self {
        DataBar {
            fill_color: ConditionalColor::rgb("FF638EC6"),
            border_color: None,
            min_type: "min".to_string(),
            min_value: None,
            max_type: "max".to_string(),
            max_value: None,
            show_value: true,
            gradient: true,
            negative_color: None,
        }
    }

    /// Set the fill color.
    pub fn with_color(mut self, color: ConditionalColor) -> Self {
        self.fill_color = color;
        self
    }

    /// Hide the cell value.
    pub fn hide_value(mut self) -> Self {
        self.show_value = false;
        self
    }

    /// Use solid fill instead of gradient.
    pub fn solid_fill(mut self) -> Self {
        self.gradient = false;
        self
    }
}

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

/// Icon set style.
#[derive(Clone, Debug, PartialEq)]
pub enum IconSetStyle {
    /// 3 arrows (up, right, down).
    ThreeArrows,
    /// 3 arrows gray.
    ThreeArrowsGray,
    /// 3 flags.
    ThreeFlags,
    /// 3 traffic lights.
    ThreeTrafficLights,
    /// 3 signs.
    ThreeSigns,
    /// 3 symbols.
    ThreeSymbols,
    /// 3 symbols 2.
    ThreeSymbols2,
    /// 4 arrows.
    FourArrows,
    /// 4 arrows gray.
    FourArrowsGray,
    /// 4 rating.
    FourRating,
    /// 4 traffic lights.
    FourTrafficLights,
    /// 5 arrows.
    FiveArrows,
    /// 5 arrows gray.
    FiveArrowsGray,
    /// 5 rating.
    FiveRating,
    /// 5 quarters.
    FiveQuarters,
}

impl IconSetStyle {
    /// Parse the iconSet attribute value back into a style.
    pub fn from_xml(value: &str) -> Option<Self> {
        Some(match value {
            "3Arrows" => IconSetStyle::ThreeArrows,
            "3ArrowsGray" => IconSetStyle::ThreeArrowsGray,
            "3Flags" => IconSetStyle::ThreeFlags,
            "3TrafficLights1" | "3TrafficLights2" => IconSetStyle::ThreeTrafficLights,
            "3Signs" => IconSetStyle::ThreeSigns,
            "3Symbols" => IconSetStyle::ThreeSymbols,
            "3Symbols2" => IconSetStyle::ThreeSymbols2,
            "4Arrows" => IconSetStyle::FourArrows,
            "4ArrowsGray" => IconSetStyle::FourArrowsGray,
            "4Rating" => IconSetStyle::FourRating,
            "4TrafficLights" => IconSetStyle::FourTrafficLights,
            "5Arrows" => IconSetStyle::FiveArrows,
            "5ArrowsGray" => IconSetStyle::FiveArrowsGray,
            "5Rating" => IconSetStyle::FiveRating,
            "5Quarters" => IconSetStyle::FiveQuarters,
            _ => return None,
        })
    }

    /// Get the XML type name.
    pub fn xml_type(&self) -> &'static str {
        match self {
            IconSetStyle::ThreeArrows => "3Arrows",
            IconSetStyle::ThreeArrowsGray => "3ArrowsGray",
            IconSetStyle::ThreeFlags => "3Flags",
            IconSetStyle::ThreeTrafficLights => "3TrafficLights1",
            IconSetStyle::ThreeSigns => "3Signs",
            IconSetStyle::ThreeSymbols => "3Symbols",
            IconSetStyle::ThreeSymbols2 => "3Symbols2",
            IconSetStyle::FourArrows => "4Arrows",
            IconSetStyle::FourArrowsGray => "4ArrowsGray",
            IconSetStyle::FourRating => "4Rating",
            IconSetStyle::FourTrafficLights => "4TrafficLights",
            IconSetStyle::FiveArrows => "5Arrows",
            IconSetStyle::FiveArrowsGray => "5ArrowsGray",
            IconSetStyle::FiveRating => "5Rating",
            IconSetStyle::FiveQuarters => "5Quarters",
        }
    }
}

/// Icon set configuration.
#[derive(Clone, Debug)]
pub struct IconSet {
    /// Icon set style.
    pub style: IconSetStyle,
    /// Show icon only (hide value).
    pub show_value: bool,
    /// Reverse icon order.
    pub reverse: bool,
    /// Custom thresholds (percentages by default).
    pub thresholds: Vec<(String, String)>, // (type, value)
}

impl IconSet {
    /// Create a new icon set.
    pub fn new(style: IconSetStyle) -> Self {
        IconSet {
            style,
            show_value: true,
            reverse: false,
            thresholds: Vec::new(),
        }
    }

    /// Hide the cell value.
    pub fn icon_only(mut self) -> Self {
        self.show_value = false;
        self
    }

    /// Reverse the icon order.
    pub fn reversed(mut self) -> Self {
        self.reverse = true;
        self
    }
}

/// Format to apply when condition is met.
/// Serialized as a `<dxf>` (differential format) entry in styles.xml and
/// referenced from the rule via `dxfId`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ConditionalFormat {
    /// Font color.
    pub font_color: Option<ConditionalColor>,
    /// Bold font.
    pub bold: Option<bool>,
    /// Italic font.
    pub italic: Option<bool>,
    /// Underline.
    pub underline: Option<bool>,
    /// Strikethrough.
    pub strikethrough: Option<bool>,
    /// Fill/background color.
    pub fill_color: Option<ConditionalColor>,
    /// Border color.
    pub border_color: Option<ConditionalColor>,
    /// Number format.
    pub number_format: Option<String>,
}

impl ConditionalFormat {
    /// Create a new format.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set font color.
    pub fn with_font_color(mut self, color: ConditionalColor) -> Self {
        self.font_color = Some(color);
        self
    }

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

    /// Set fill color.
    pub fn with_fill(mut self, color: ConditionalColor) -> Self {
        self.fill_color = Some(color);
        self
    }
}

/// A conditional formatting rule.
#[derive(Clone, Debug)]
pub struct ConditionalRule {
    /// Rule type.
    pub rule_type: ConditionalFormatType,
    /// Priority (lower = higher priority).
    pub priority: u32,
    /// Operator for cell value rules.
    pub operator: Option<ConditionalOperator>,
    /// First formula/value.
    pub formula1: Option<String>,
    /// Second formula/value (for between operators).
    pub formula2: Option<String>,
    /// Text to match (for text rules).
    pub text: Option<String>,
    /// Format to apply.
    pub format: Option<ConditionalFormat>,
    /// Color scale configuration.
    pub color_scale: Option<ColorScale>,
    /// Data bar configuration.
    pub data_bar: Option<DataBar>,
    /// Icon set configuration.
    pub icon_set: Option<IconSet>,
    /// Stop if true.
    pub stop_if_true: bool,
    /// Bottom N instead of top N.
    pub bottom: bool,
    /// Percent instead of count.
    pub percent: bool,
    /// Rank/count for top/bottom rules.
    pub rank: Option<u32>,
    /// Above average (true) or below (false).
    pub above_average: bool,
    /// Equal to average allowed.
    pub equal_average: bool,
    /// Standard deviation value.
    pub std_dev: Option<u32>,
    /// Time period for date rules.
    pub time_period: Option<String>,
}

impl Default for ConditionalRule {
    fn default() -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::Expression,
            priority: 1,
            operator: None,
            formula1: None,
            formula2: None,
            text: None,
            format: None,
            color_scale: None,
            data_bar: None,
            icon_set: None,
            stop_if_true: false,
            bottom: false,
            percent: false,
            rank: None,
            above_average: true,
            equal_average: false,
            std_dev: None,
            time_period: None,
        }
    }
}

impl ConditionalRule {
    /// Create a rule of the given type with default settings.
    pub fn of_type(rule_type: ConditionalFormatType) -> Self {
        ConditionalRule {
            rule_type,
            ..Default::default()
        }
    }

    /// Create a cell value rule.
    pub fn cell_is(operator: ConditionalOperator, value: &str) -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::CellIs,
            operator: Some(operator),
            formula1: Some(value.to_string()),
            ..Default::default()
        }
    }

    /// Create a formula-based rule.
    pub fn formula(formula: &str) -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::Expression,
            formula1: Some(formula.to_string()),
            ..Default::default()
        }
    }

    /// Create a color scale rule.
    pub fn with_color_scale(scale: ColorScale) -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::ColorScale,
            color_scale: Some(scale),
            ..Default::default()
        }
    }

    /// Create a data bar rule.
    pub fn with_data_bar(bar: DataBar) -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::DataBar,
            data_bar: Some(bar),
            ..Default::default()
        }
    }

    /// Create an icon set rule.
    pub fn with_icon_set(icons: IconSet) -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::IconSet,
            icon_set: Some(icons),
            ..Default::default()
        }
    }

    /// Create a top N rule.
    pub fn top(n: u32) -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::Top10,
            rank: Some(n),
            ..Default::default()
        }
    }

    /// Create a "cell contains text" rule.
    pub fn contains_text(text: &str) -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::ContainsText,
            text: Some(text.to_string()),
            ..Default::default()
        }
    }

    /// Create a "cell does not contain text" rule.
    pub fn not_contains_text(text: &str) -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::NotContainsText,
            text: Some(text.to_string()),
            ..Default::default()
        }
    }

    /// Create a "text begins with" rule.
    pub fn begins_with(text: &str) -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::BeginsWith,
            text: Some(text.to_string()),
            ..Default::default()
        }
    }

    /// Create a "text ends with" rule.
    pub fn ends_with(text: &str) -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::EndsWith,
            text: Some(text.to_string()),
            ..Default::default()
        }
    }

    /// Create a time-period rule. `period` is one of the ST_TimePeriod
    /// values: today, yesterday, tomorrow, last7Days, thisWeek, lastWeek,
    /// nextWeek, thisMonth, lastMonth, nextMonth.
    pub fn time_period(period: &str) -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::TimePeriod,
            time_period: Some(period.to_string()),
            ..Default::default()
        }
    }

    /// Create an above-average rule. Use `equal_average` to include values
    /// equal to the mean, and `std_dev` for "N standard deviations above".
    pub fn above_average() -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::AboveAverage,
            ..Default::default()
        }
    }

    /// Create a below-average rule.
    pub fn below_average() -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::AboveAverage,
            above_average: false,
            ..Default::default()
        }
    }

    /// Create a duplicate-values rule.
    pub fn duplicate_values() -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::DuplicateValues,
            ..Default::default()
        }
    }

    /// Create a unique-values rule.
    pub fn unique_values() -> Self {
        ConditionalRule {
            rule_type: ConditionalFormatType::UniqueValues,
            ..Default::default()
        }
    }

    /// Create a bottom N rule.
    pub fn bottom(n: u32) -> Self {
        let mut rule = Self::top(n);
        rule.bottom = true;
        rule
    }

    /// Set the format to apply.
    pub fn with_format(mut self, format: ConditionalFormat) -> Self {
        self.format = Some(format);
        self
    }

    /// Set the priority.
    pub fn with_priority(mut self, priority: u32) -> Self {
        self.priority = priority;
        self
    }
}

/// Conditional formatting for a range.
#[derive(Clone, Debug)]
pub struct ConditionalFormatting {
    /// Cell range (e.g., "A1:B10").
    pub range: String,
    /// Rules to apply.
    pub rules: Vec<ConditionalRule>,
}

impl ConditionalFormatting {
    /// Create conditional formatting for a range.
    pub fn new<S: Into<String>>(range: S) -> Self {
        ConditionalFormatting {
            range: range.into(),
            rules: Vec::new(),
        }
    }

    /// Add a rule.
    pub fn add_rule(&mut self, rule: ConditionalRule) {
        self.rules.push(rule);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cell_is_rule() {
        let rule = ConditionalRule::cell_is(ConditionalOperator::GreaterThan, "100")
            .with_format(ConditionalFormat::new().with_fill(ConditionalColor::green()));

        assert_eq!(rule.rule_type, ConditionalFormatType::CellIs);
        assert_eq!(rule.operator, Some(ConditionalOperator::GreaterThan));
        assert_eq!(rule.formula1, Some("100".to_string()));
    }

    #[test]
    fn test_color_scale() {
        let scale = ColorScale::red_yellow_green();
        let rule = ConditionalRule::with_color_scale(scale);

        assert_eq!(rule.rule_type, ConditionalFormatType::ColorScale);
        assert!(rule.color_scale.is_some());
    }

    #[test]
    fn test_data_bar() {
        let bar = DataBar::new()
            .with_color(ConditionalColor::blue())
            .hide_value();
        let rule = ConditionalRule::with_data_bar(bar);

        assert_eq!(rule.rule_type, ConditionalFormatType::DataBar);
        assert!(rule.data_bar.is_some());
        assert!(!rule.data_bar.unwrap().show_value);
    }

    #[test]
    fn test_icon_set() {
        let icons = IconSet::new(IconSetStyle::ThreeArrows).icon_only();
        let rule = ConditionalRule::with_icon_set(icons);

        assert_eq!(rule.rule_type, ConditionalFormatType::IconSet);
        assert!(rule.icon_set.is_some());
    }

    #[test]
    fn test_conditional_formatting() {
        let mut cf = ConditionalFormatting::new("A1:A100");
        cf.add_rule(
            ConditionalRule::top(10).with_format(
                ConditionalFormat::new()
                    .with_bold(true)
                    .with_fill(ConditionalColor::yellow()),
            ),
        );

        assert_eq!(cf.range, "A1:A100");
        assert_eq!(cf.rules.len(), 1);
    }
}

#[cfg(test)]
mod coverage_tests {
    use super::*;

    #[test]
    fn type_and_operator_xml_roundtrip() {
        for t in [
            ConditionalFormatType::CellIs,
            ConditionalFormatType::Expression,
            ConditionalFormatType::ColorScale,
            ConditionalFormatType::DataBar,
            ConditionalFormatType::IconSet,
            ConditionalFormatType::Top10,
            ConditionalFormatType::ContainsText,
        ] {
            let x = t.xml_value();
            assert_eq!(ConditionalFormatType::from_xml(x), Some(t));
        }
        assert_eq!(ConditionalFormatType::from_xml("nonsense"), None);

        for op in [
            ConditionalOperator::GreaterThan,
            ConditionalOperator::LessThan,
            ConditionalOperator::Between,
            ConditionalOperator::Equal,
        ] {
            assert_eq!(ConditionalOperator::from_xml(op.xml_value()), Some(op));
        }
    }

    #[test]
    fn conditional_colors() {
        assert!(ConditionalColor::rgb("FF0000").rgb.is_some());
        assert!(ConditionalColor::theme(3).theme.is_some());
        let _ = (
            ConditionalColor::red(),
            ConditionalColor::green(),
            ConditionalColor::yellow(),
            ConditionalColor::blue(),
            ConditionalColor::white(),
        );
    }

    #[test]
    fn color_scales() {
        let two = ColorScale::two_color(ConditionalColor::red(), ConditionalColor::green());
        assert!(two.mid_color.is_none());
        let three = ColorScale::three_color(
            ConditionalColor::red(),
            ConditionalColor::yellow(),
            ConditionalColor::green(),
        );
        assert!(three.mid_color.is_some());
        assert!(ColorScale::red_yellow_green().mid_color.is_some());
        assert!(ColorScale::green_yellow_red().mid_color.is_some());
    }

    #[test]
    fn data_bars_and_icon_sets() {
        let bar = DataBar::new()
            .with_color(ConditionalColor::blue())
            .hide_value()
            .solid_fill();
        assert!(!bar.show_value, "hide_value clears show_value");
        assert!(!bar.gradient, "solid_fill clears gradient");

        let icons = IconSet::new(IconSetStyle::ThreeTrafficLights)
            .icon_only()
            .reversed();
        assert!(icons.reverse && !icons.show_value);
        assert_eq!(
            IconSetStyle::from_xml(IconSetStyle::ThreeTrafficLights.xml_type()),
            Some(IconSetStyle::ThreeTrafficLights)
        );
    }

    #[test]
    fn rule_constructors_and_formatting() {
        let fmt = ConditionalFormat::new()
            .with_font_color(ConditionalColor::red())
            .with_bold(true)
            .with_fill(ConditionalColor::yellow());
        let _ = ConditionalRule::of_type(ConditionalFormatType::Expression);
        let _ = ConditionalRule::cell_is(ConditionalOperator::GreaterThan, "10")
            .with_format(fmt)
            .with_priority(1);
        let _ = ConditionalRule::formula("$A$1>0");
        let _ = ConditionalRule::with_color_scale(ColorScale::red_yellow_green());
        let _ = ConditionalRule::with_data_bar(DataBar::new());
        let _ = ConditionalRule::with_icon_set(IconSet::new(IconSetStyle::ThreeArrows));
        let _ = ConditionalRule::top(10);
        let _ = ConditionalRule::bottom(5);
        let _ = ConditionalRule::contains_text("x");
        let _ = ConditionalRule::not_contains_text("y");
        let _ = ConditionalRule::begins_with("a");
        let _ = ConditionalRule::ends_with("z");
        let _ = ConditionalRule::time_period("today");
        let _ = ConditionalRule::above_average();
        let _ = ConditionalRule::below_average();
        let _ = ConditionalRule::duplicate_values();
        let _ = ConditionalRule::unique_values();

        let mut cf = ConditionalFormatting::new("A1:A10");
        cf.add_rule(ConditionalRule::top(3));
        cf.add_rule(ConditionalRule::formula("$A1>5"));
        assert_eq!(cf.rules.len(), 2);
    }
}