laravel-excel 0.3.0

Excel, CSV, ODS, HTML and PDF exports and imports with typed columns for Laravel Rust: a port of Laravel Excel (maatwebsite/excel).
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
//! The workbook that an export builds before it's written: the part of PhpSpreadsheet's
//! `Spreadsheet` and `Worksheet` that Laravel Excel and its event listeners use.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::coordinate::{CellRange, Coordinate, column_index_from_string, string_from_column_index};
use crate::error::ExcelError;
use crate::style::Style;
use crate::value::Value;

/// The document properties: `config('excel.exports.properties')` and `WithProperties`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Properties {
    /// The creator.
    pub creator: Option<String>,
    /// Who last modified the document.
    pub last_modified_by: Option<String>,
    /// The title.
    pub title: Option<String>,
    /// The description.
    pub description: Option<String>,
    /// The subject.
    pub subject: Option<String>,
    /// The keywords.
    pub keywords: Option<String>,
    /// The category.
    pub category: Option<String>,
    /// The manager.
    pub manager: Option<String>,
    /// The company.
    pub company: Option<String>,
}

impl Properties {
    /// Applies the non-empty values of `other`, like `array_merge` of the non-empty properties.
    pub fn apply(&mut self, other: &Properties) {
        let pairs: [(&mut Option<String>, &Option<String>); 9] = [
            (&mut self.creator, &other.creator),
            (&mut self.last_modified_by, &other.last_modified_by),
            (&mut self.title, &other.title),
            (&mut self.description, &other.description),
            (&mut self.subject, &other.subject),
            (&mut self.keywords, &other.keywords),
            (&mut self.category, &other.category),
            (&mut self.manager, &other.manager),
            (&mut self.company, &other.company),
        ];
        for (target, source) in pairs {
            if let Some(value) = source.as_ref().filter(|value| !value.is_empty()) {
                *target = Some(value.clone());
            }
        }
    }
}

/// A workbook: its sheets, document properties and default style.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Spreadsheet {
    sheets: Vec<Worksheet>,
    /// The document properties.
    pub properties: Properties,
    /// The style every cell starts from: `getDefaultStyle()`.
    pub default_style: Style,
}

impl Spreadsheet {
    /// An empty workbook without sheets.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a sheet titled `Worksheet`, `Worksheet 1`, `Worksheet 2`.. like `createSheet()`, at
    /// `index` or at the end, and returns its index.
    pub fn create_sheet(&mut self, index: Option<usize>) -> usize {
        let mut title = "Worksheet".to_owned();
        let mut counter = 1;
        while self.sheets.iter().any(|sheet| sheet.title.eq_ignore_ascii_case(&title)) {
            title = format!("Worksheet {counter}");
            counter += 1;
        }
        let sheet = Worksheet::new(title);
        match index {
            Some(index) if index < self.sheets.len() => {
                self.sheets.insert(index, sheet);
                index
            }
            _ => {
                self.sheets.push(sheet);
                self.sheets.len() - 1
            }
        }
    }

    /// The sheets, in order.
    pub fn sheets(&self) -> &[Worksheet] {
        &self.sheets
    }

    /// The sheets, in order, to change.
    pub fn sheets_mut(&mut self) -> &mut [Worksheet] {
        &mut self.sheets
    }

    /// The number of sheets.
    pub fn sheet_count(&self) -> usize {
        self.sheets.len()
    }

    /// The sheet at `index`.
    pub fn sheet(&self, index: usize) -> Option<&Worksheet> {
        self.sheets.get(index)
    }

    /// The sheet at `index`, to change.
    pub fn sheet_mut(&mut self, index: usize) -> Option<&mut Worksheet> {
        self.sheets.get_mut(index)
    }

    /// The sheet titled `name`.
    pub fn sheet_by_name(&self, name: &str) -> Option<&Worksheet> {
        self.sheets.iter().find(|sheet| sheet.title == name)
    }
}

/// A cell: its value and its own style.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Cell {
    /// The value.
    #[serde(with = "crate::value::stored")]
    pub value: Value,
    /// The cell's style, on top of its row's and column's.
    #[serde(default, skip_serializing_if = "Style::is_empty")]
    pub style: Style,
}

/// A column's width: `getColumnDimension()`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ColumnDimension {
    /// The width in characters, or `None` for the default width (`-1` in PhpSpreadsheet).
    pub width: Option<f64>,
    /// Whether the width fits the content when the file is written.
    pub auto_size: bool,
    /// Whether the column is hidden: `setVisible(false)`.
    #[serde(default)]
    pub hidden: bool,
    /// Whether the column is collapsed: `setCollapsed(true)`.
    #[serde(default)]
    pub collapsed: bool,
}

/// A cell's link: `getHyperlink()`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Hyperlink {
    /// The link.
    pub url: String,
    /// The tooltip shown on hover.
    pub tooltip: Option<String>,
}

/// A cell's comment: `getComment()`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Comment {
    /// The text.
    pub text: String,
    /// The author.
    pub author: Option<String>,
    /// The width in pixels, or Excel's default.
    pub width: Option<u32>,
    /// The height in pixels, or Excel's default.
    pub height: Option<u32>,
    /// Whether the comment is always shown: `setVisible(true)`.
    pub visible: bool,
    /// The background color, as `RRGGBB` hex.
    pub fill_color: Option<String>,
}

impl Comment {
    /// A comment with this text.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            ..Self::default()
        }
    }
}

/// One run of a rich text cell: text in one font. `PhpOffice\PhpSpreadsheet\RichText\Run`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct TextRun {
    /// The text.
    pub text: String,
    /// The run's font; an empty style for plain text.
    #[serde(default, skip_serializing_if = "Style::is_empty")]
    pub style: Style,
    /// Superscript.
    #[serde(default)]
    pub superscript: bool,
    /// Subscript.
    #[serde(default)]
    pub subscript: bool,
    /// Plain text outside any run (a `TextElement`), read back without a `<span>`.
    #[serde(default)]
    pub plain: bool,
}

/// A chart's type: PhpSpreadsheet's `DataSeries::TYPE_*`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ChartType {
    /// `TYPE_AREACHART`.
    Area,
    /// `TYPE_BARCHART` with horizontal bars.
    Bar,
    /// `TYPE_BARCHART` with vertical bars (`DIRECTION_COL`).
    Column,
    /// `TYPE_DOUGHNUTCHART`.
    Doughnut,
    /// `TYPE_LINECHART`.
    Line,
    /// `TYPE_PIECHART`.
    Pie,
    /// `TYPE_RADARCHART`.
    Radar,
    /// `TYPE_SCATTERCHART`.
    Scatter,
    /// `TYPE_STOCKCHART`.
    Stock,
}

/// One data series of a chart: `DataSeriesValues`. Ranges are such as `B2:B5` on the chart's
/// sheet, or `'Other sheet'!B2:B5`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ChartSeries {
    /// The series' name: a cell such as `B1`, or text.
    pub name: Option<String>,
    /// The categories (the X axis labels).
    pub categories: Option<String>,
    /// The values.
    pub values: String,
}

/// A chart placed over a range of cells: PhpSpreadsheet's `Chart`, for `WithCharts`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Chart {
    /// The chart's name.
    pub name: String,
    /// The type.
    pub kind: ChartType,
    /// The title.
    pub title: Option<String>,
    /// The series.
    pub series: Vec<ChartSeries>,
    /// The X axis title.
    pub x_axis_title: Option<String>,
    /// The Y axis title.
    pub y_axis_title: Option<String>,
    /// The legend's position: `r`, `l`, `t`, `b` or `tr`, or `None` for no legend.
    pub legend: Option<String>,
    /// The cell of the top left corner: `setTopLeftPosition()`.
    pub top_left: String,
    /// The cell of the bottom right corner: `setBottomRightPosition()`.
    pub bottom_right: String,
}

impl Chart {
    /// A chart of `kind` with a legend on the right, at `H7:P20` until placed elsewhere.
    pub fn new(name: impl Into<String>, kind: ChartType) -> Self {
        Self {
            name: name.into(),
            kind,
            title: None,
            series: Vec::new(),
            x_axis_title: None,
            y_axis_title: None,
            legend: Some("r".to_owned()),
            top_left: "H7".to_owned(),
            bottom_right: "P20".to_owned(),
        }
    }

    /// The title.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Adds a series.
    pub fn series(mut self, name: Option<&str>, categories: Option<&str>, values: &str) -> Self {
        self.series.push(ChartSeries {
            name: name.map(str::to_owned),
            categories: categories.map(str::to_owned),
            values: values.to_owned(),
        });
        self
    }

    /// The axis titles.
    pub fn axis_titles(mut self, x: Option<&str>, y: Option<&str>) -> Self {
        self.x_axis_title = x.map(str::to_owned);
        self.y_axis_title = y.map(str::to_owned);
        self
    }

    /// The legend's position (`r`, `l`, `t`, `b`, `tr`), or `None` to hide it.
    pub fn legend(mut self, position: Option<&str>) -> Self {
        self.legend = position.map(str::to_owned);
        self
    }

    /// The cells the chart covers: `setTopLeftPosition()` and `setBottomRightPosition()`.
    pub fn position(mut self, top_left: impl Into<String>, bottom_right: impl Into<String>) -> Self {
        self.top_left = top_left.into();
        self.bottom_right = bottom_right.into();
        self
    }
}

/// The auto filter of one column: `getAutoFilter()->getColumn()`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ColumnFilter {
    /// `filters` (a list of values) or `customFilters` (comparisons).
    pub filter_type: String,
    /// The rules, as `(operator, value)` pairs such as `("equal", "Yes")`.
    pub rules: Vec<(String, String)>,
}

/// An image placed on a sheet: `WithDrawings` returns these, like PhpSpreadsheet's `Drawing`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Drawing {
    /// The image file's path on the local filesystem.
    pub path: String,
    /// The cell the image's top left corner sits on, such as `B3`.
    pub coordinates: String,
    /// The name.
    pub name: Option<String>,
    /// The description, written as the image's alt text.
    pub description: Option<String>,
    /// The height in pixels, scaling the image proportionally.
    pub height: Option<u32>,
    /// The width in pixels, scaling the image proportionally; wins over `height`, as the later
    /// `setWidth()` does.
    #[serde(default)]
    pub width: Option<u32>,
    /// The image's bytes, instead of reading `path`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content: Option<Vec<u8>>,
    /// The horizontal offset in pixels.
    pub offset_x: u32,
    /// The vertical offset in pixels.
    pub offset_y: u32,
}

impl Drawing {
    /// An image from `path`, placed at `A1`.
    pub fn new(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            coordinates: "A1".to_owned(),
            name: None,
            description: None,
            height: None,
            width: None,
            content: None,
            offset_x: 0,
            offset_y: 0,
        }
    }

    /// The width in pixels, scaling the image proportionally: `setWidth()`.
    pub fn width(mut self, width: u32) -> Self {
        self.width = Some(width);
        self
    }

    /// The image's bytes, instead of a file.
    pub fn content(mut self, content: Vec<u8>) -> Self {
        self.content = Some(content);
        self
    }

    /// Places the image at a cell, such as `B3`: `setCoordinates()`.
    pub fn coordinates(mut self, coordinates: impl Into<String>) -> Self {
        self.coordinates = coordinates.into();
        self
    }

    /// The name: `setName()`.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// The description: `setDescription()`.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// The height in pixels: `setHeight()`.
    pub fn height(mut self, height: u32) -> Self {
        self.height = Some(height);
        self
    }

    /// The offsets from the cell's corner in pixels: `setOffsetX()` and `setOffsetY()`.
    pub fn offset(mut self, x: u32, y: u32) -> Self {
        self.offset_x = x;
        self.offset_y = y;
        self
    }
}

/// A sheet of a workbook: PhpSpreadsheet's `Worksheet`, the delegate of Laravel Excel's `Sheet`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Worksheet {
    title: String,
    cells: BTreeMap<u32, BTreeMap<u32, Cell>>,
    column_dimensions: BTreeMap<u32, ColumnDimension>,
    row_heights: BTreeMap<u32, f64>,
    column_styles: BTreeMap<u32, Style>,
    row_styles: BTreeMap<u32, Style>,
    merges: Vec<String>,
    freeze_pane: Option<String>,
    tab_color: Option<String>,
    protection: Option<Option<String>>,
    page_breaks: Vec<u32>,
    print_area: Option<String>,
    auto_filter: Option<String>,
    drawings: Vec<Drawing>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    hyperlinks: BTreeMap<String, Hyperlink>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    comments: BTreeMap<String, Comment>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    rich_texts: BTreeMap<String, Vec<TextRun>>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    column_filters: BTreeMap<u32, ColumnFilter>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    charts: Vec<Chart>,
}

impl Worksheet {
    /// An empty sheet.
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            ..Self::default()
        }
    }

    /// The sheet's title.
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Sets the title, as `setTitle()` does.
    pub fn set_title(&mut self, title: impl Into<String>) {
        self.title = title.into();
    }

    /// The value at a coordinate such as `B3`, or `Value::Null`.
    pub fn get(&self, coordinate: &str) -> Result<&Value, ExcelError> {
        let coordinate = Coordinate::parse(coordinate)?;
        Ok(self.value_at(coordinate))
    }

    /// The value at a coordinate.
    pub fn value_at(&self, coordinate: Coordinate) -> &Value {
        static NULL: Value = Value::Null;
        self.cells
            .get(&coordinate.row)
            .and_then(|row| row.get(&coordinate.column))
            .map_or(&NULL, |cell| &cell.value)
    }

    /// The cell at a coordinate, if it exists.
    pub fn cell(&self, coordinate: Coordinate) -> Option<&Cell> {
        self.cells
            .get(&coordinate.row)
            .and_then(|row| row.get(&coordinate.column))
    }

    /// Whether a cell exists at the coordinate: `cellExists()`.
    pub fn cell_exists(&self, coordinate: Coordinate) -> bool {
        self.cell(coordinate).is_some()
    }

    pub(crate) fn cell_mut(&mut self, coordinate: Coordinate) -> &mut Cell {
        self.cells
            .entry(coordinate.row)
            .or_default()
            .entry(coordinate.column)
            .or_default()
    }

    /// Sets the value of the cell at a coordinate such as `B3`, exactly as given, without the
    /// value binder: `setCellValueExplicit()`.
    pub fn set(&mut self, coordinate: &str, value: impl Into<Value>) -> Result<(), ExcelError> {
        let coordinate = Coordinate::parse(coordinate)?;
        self.set_value_at(coordinate, value.into());
        Ok(())
    }

    /// Keeps only the cells `keep` accepts.
    pub(crate) fn retain_cells(&mut self, mut keep: impl FnMut(Coordinate) -> bool) {
        for (row, cells) in &mut self.cells {
            cells.retain(|column, _| keep(Coordinate::new(*column, *row)));
        }
        self.cells.retain(|_, cells| !cells.is_empty());
    }

    /// Sets the value of the cell at a coordinate.
    pub fn set_value_at(&mut self, coordinate: Coordinate, value: Value) {
        self.cell_mut(coordinate).value = value;
    }

    /// The highest row with a cell: `getHighestRow()`, or 1 for an empty sheet.
    pub fn highest_row(&self) -> u32 {
        self.cells.keys().next_back().copied().unwrap_or(1)
    }

    /// The highest column with a cell, as an index: or 1 for an empty sheet.
    pub fn highest_column_index(&self) -> u32 {
        self.cells
            .values()
            .filter_map(|row| row.keys().next_back().copied())
            .max()
            .unwrap_or(1)
    }

    /// The highest column with a cell, as letters: `getHighestColumn()`.
    pub fn highest_column(&self) -> String {
        string_from_column_index(self.highest_column_index())
    }

    /// The highest column with a cell in `row`.
    pub fn highest_column_in_row(&self, row: u32) -> String {
        string_from_column_index(
            self.cells
                .get(&row)
                .and_then(|cells| cells.keys().next_back().copied())
                .unwrap_or(1),
        )
    }

    /// The highest row with a non-empty cell: `getHighestDataRow()`.
    pub fn highest_data_row(&self) -> u32 {
        self.cells
            .iter()
            .rev()
            .find(|(_, cells)| cells.values().any(|cell| !cell.value.is_null()))
            .map_or(1, |(row, _)| *row)
    }

    /// The highest column with a non-empty cell, as an index: `getHighestDataColumn()`.
    pub fn highest_data_column_index(&self) -> u32 {
        self.cells
            .values()
            .filter_map(|row| {
                row.iter()
                    .rev()
                    .find(|(_, cell)| !cell.value.is_null())
                    .map(|(column, _)| *column)
            })
            .max()
            .unwrap_or(1)
    }

    /// The rows from `start` to `end` (inclusive, or to the highest row), each as the values of
    /// columns `A` to `end_column` (or the sheet's highest column), filling gaps with `Null`.
    pub fn rows(&self, start: u32, end: Option<u32>, end_column: Option<u32>) -> Vec<(u32, Vec<Value>)> {
        let end = end.unwrap_or_else(|| self.highest_row());
        let last_column = end_column.unwrap_or_else(|| self.highest_column_index());
        (start..=end)
            .map(|row| {
                let values = (1..=last_column)
                    .map(|column| self.value_at(Coordinate::new(column, row)).clone())
                    .collect();
                (row, values)
            })
            .collect()
    }

    /// Writes rows of values from `start_cell` (or `A1`) down, like `fromArray()`. With
    /// `strict_null_comparison`, `null` values still create empty cells; without it they're
    /// skipped.
    pub fn from_array(&mut self, rows: Vec<Vec<Value>>, start_cell: Coordinate, strict_null_comparison: bool) {
        for (offset, values) in rows.into_iter().enumerate() {
            let row = start_cell.row + offset as u32;
            for (column_offset, value) in values.into_iter().enumerate() {
                if value.is_null() && !strict_null_comparison {
                    continue;
                }
                self.set_value_at(Coordinate::new(start_cell.column + column_offset as u32, row), value);
            }
        }
    }

    /// The style applied to a range such as `A1:C1`, `B2`, a column `B`, or a row `1`, on top of
    /// what's there: `getStyle($range)->applyFromArray()`.
    ///
    /// Whole columns and rows get a column or row style, as PhpSpreadsheet does; cell ranges
    /// style each cell in the range.
    pub fn apply_style(&mut self, range: &str, style: &Style) -> Result<(), ExcelError> {
        match CellRange::parse(range)? {
            CellRange::Columns(first, last) => {
                for column in first..=last {
                    self.column_styles.entry(column).or_default().apply(style);
                }
            }
            CellRange::Rows(first, last) => {
                for row in first..=last {
                    self.row_styles.entry(row).or_default().apply(style);
                }
            }
            CellRange::Cells(start, end) => {
                for row in start.row..=end.row {
                    for column in start.column..=end.column {
                        self.cell_mut(Coordinate::new(column, row)).style.apply(style);
                    }
                }
            }
        }
        Ok(())
    }

    /// Sets the number format of a range: `getStyle($range)->getNumberFormat()->setFormatCode()`.
    pub fn set_number_format(&mut self, range: &str, format: &str) -> Result<(), ExcelError> {
        self.apply_style(range, &Style::new().number_format(format))
    }

    /// The style of a cell: its column's, then its row's, then its own.
    pub fn effective_style(&self, coordinate: Coordinate) -> Style {
        let mut style = self.column_styles.get(&coordinate.column).cloned().unwrap_or_default();
        if let Some(row) = self.row_styles.get(&coordinate.row) {
            style.apply(row);
        }
        if let Some(cell) = self.cell(coordinate) {
            style.apply(&cell.style);
        }
        style
    }

    /// The column styles, by column index.
    pub fn column_styles(&self) -> &BTreeMap<u32, Style> {
        &self.column_styles
    }

    /// The row styles, by row number.
    pub fn row_styles(&self) -> &BTreeMap<u32, Style> {
        &self.row_styles
    }

    /// The cells, by row and then column.
    pub fn cells(&self) -> impl Iterator<Item = (Coordinate, &Cell)> {
        self.cells.iter().flat_map(|(row, cells)| {
            cells
                .iter()
                .map(move |(column, cell)| (Coordinate::new(*column, *row), cell))
        })
    }

    /// The dimension of a column such as `B`: `getColumnDimension()`.
    pub fn column_dimension(&mut self, column: &str) -> Result<&mut ColumnDimension, ExcelError> {
        let index = column_index_from_string(column)?;
        Ok(self.column_dimensions.entry(index).or_default())
    }

    /// The column dimensions, by column index.
    pub fn column_dimensions(&self) -> &BTreeMap<u32, ColumnDimension> {
        &self.column_dimensions
    }

    /// Sets a column's width, turning off its auto size.
    pub fn set_column_width(&mut self, column: &str, width: f64) -> Result<(), ExcelError> {
        let dimension = self.column_dimension(column)?;
        dimension.auto_size = false;
        dimension.width = Some(width);
        Ok(())
    }

    /// Sets a row's height in points: `getRowDimension()->setRowHeight()`.
    pub fn set_row_height(&mut self, row: u32, height: f64) {
        self.row_heights.insert(row, height);
    }

    /// The row heights, by row number.
    pub fn row_heights(&self) -> &BTreeMap<u32, f64> {
        &self.row_heights
    }

    /// Merges a range such as `A1:C1`: `mergeCells()`.
    pub fn merge_cells(&mut self, range: &str) -> Result<(), ExcelError> {
        CellRange::parse(range)?;
        self.merges.push(range.to_owned());
        Ok(())
    }

    /// The merged ranges.
    pub fn merges(&self) -> &[String] {
        &self.merges
    }

    /// Freezes the rows above and the columns left of a cell, such as `B2`: `freezePane()`.
    pub fn freeze_pane(&mut self, cell: &str) -> Result<(), ExcelError> {
        Coordinate::parse(cell)?;
        self.freeze_pane = Some(cell.to_owned());
        Ok(())
    }

    /// The frozen pane's top left cell.
    pub fn frozen_pane(&self) -> Option<&str> {
        self.freeze_pane.as_deref()
    }

    /// Sets the tab color, as `RRGGBB` hex: `getTabColor()->setRGB()`.
    pub fn set_tab_color(&mut self, color: impl Into<String>) {
        self.tab_color = Some(color.into());
    }

    /// The tab color.
    pub fn tab_color(&self) -> Option<&str> {
        self.tab_color.as_deref()
    }

    /// Protects the sheet, with an optional password: `getProtection()->setSheet(true)`.
    pub fn protect(&mut self, password: Option<String>) {
        self.protection = Some(password);
    }

    /// The sheet's protection: `None` when unprotected, `Some(password)` when protected.
    pub fn protection(&self) -> Option<Option<&str>> {
        self.protection.as_ref().map(Option::as_deref)
    }

    /// Adds a page break after `row`: `setBreak('A'.$row, BREAK_ROW)`.
    pub fn set_row_break(&mut self, row: u32) {
        if !self.page_breaks.contains(&row) {
            self.page_breaks.push(row);
        }
    }

    /// The rows with a page break after them.
    pub fn page_breaks(&self) -> &[u32] {
        &self.page_breaks
    }

    /// Sets the print area, such as `A1:D20`: `getPageSetup()->setPrintArea()`.
    pub fn set_print_area(&mut self, range: &str) -> Result<(), ExcelError> {
        CellRange::parse(range)?;
        self.print_area = Some(range.to_owned());
        Ok(())
    }

    /// The print area.
    pub fn print_area(&self) -> Option<&str> {
        self.print_area.as_deref()
    }

    /// Adds an auto filter to a range such as `A1:D20`: `setAutoFilter()`.
    pub fn set_auto_filter(&mut self, range: &str) -> Result<(), ExcelError> {
        CellRange::parse(range)?;
        self.auto_filter = Some(range.to_owned());
        Ok(())
    }

    /// The auto filter's range.
    pub fn auto_filter(&self) -> Option<&str> {
        self.auto_filter.as_deref()
    }

    /// Places an image on the sheet: `$drawing->setWorksheet($sheet)`.
    pub fn add_drawing(&mut self, drawing: Drawing) {
        self.drawings.push(drawing);
    }

    /// The images on the sheet.
    /// Sets a cell's link: `getCell()->getHyperlink()->setUrl()->setTooltip()`.
    pub fn set_hyperlink(&mut self, coordinate: Coordinate, hyperlink: Hyperlink) {
        self.hyperlinks.insert(coordinate.to_string(), hyperlink);
    }

    /// A cell's link.
    pub fn hyperlink(&self, coordinate: Coordinate) -> Option<&Hyperlink> {
        self.hyperlinks.get(&coordinate.to_string())
    }

    /// The links, by coordinate.
    pub fn hyperlinks(&self) -> &BTreeMap<String, Hyperlink> {
        &self.hyperlinks
    }

    /// A cell's comment, created when missing: `getComment($coordinate)`.
    pub fn comment_mut(&mut self, coordinate: Coordinate) -> &mut Comment {
        self.comments.entry(coordinate.to_string()).or_default()
    }

    /// A cell's comment.
    pub fn comment(&self, coordinate: Coordinate) -> Option<&Comment> {
        self.comments.get(&coordinate.to_string())
    }

    /// The comments, by coordinate.
    pub fn comments(&self) -> &BTreeMap<String, Comment> {
        &self.comments
    }

    /// Sets a cell to rich text: a `RichText` value. The cell's value becomes the plain text.
    pub fn set_rich_text(&mut self, coordinate: Coordinate, runs: Vec<TextRun>) {
        let text: String = runs.iter().map(|run| run.text.as_str()).collect();
        self.set_value_at(coordinate, Value::String(text));
        self.rich_texts.insert(coordinate.to_string(), runs);
    }

    /// A cell's rich text runs.
    pub fn rich_text(&self, coordinate: Coordinate) -> Option<&[TextRun]> {
        self.rich_texts.get(&coordinate.to_string()).map(Vec::as_slice)
    }

    /// The rich text cells, by coordinate.
    pub fn rich_texts(&self) -> &BTreeMap<String, Vec<TextRun>> {
        &self.rich_texts
    }

    /// The auto filter of a column such as `B`: `getAutoFilter()->getColumn()`.
    pub fn column_filter(&mut self, column: &str) -> Result<&mut ColumnFilter, ExcelError> {
        let index = column_index_from_string(column)?;
        Ok(self.column_filters.entry(index).or_default())
    }

    /// The column auto filters, by column index.
    pub fn column_filters(&self) -> &BTreeMap<u32, ColumnFilter> {
        &self.column_filters
    }

    /// Adds a chart: `addChart()`.
    pub fn add_chart(&mut self, chart: Chart) {
        self.charts.push(chart);
    }

    /// The charts.
    pub fn charts(&self) -> &[Chart] {
        &self.charts
    }

    /// The images.
    pub fn drawings(&self) -> &[Drawing] {
        &self.drawings
    }
}