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
//! What an XLSX file holds beyond values, which `calamine` doesn't read: rich text runs, links
//! and images. PhpSpreadsheet loads these when the reader isn't in read-only mode, which Laravel
//! Excel asks for when a column needs them (`needsStyleInformation()`).

use std::collections::HashMap;
use std::io::{Cursor, Read};

use quick_xml::events::{BytesStart, Event};
use quick_xml::{Reader, XmlVersion};

use crate::coordinate::Coordinate;
use crate::spreadsheet::{Hyperlink, TextRun};
use crate::style::{BorderStyle, Horizontal, Style, Vertical};

/// An image read from a file: `Maatwebsite\Excel\ImageContent`.
#[derive(Debug, Clone, PartialEq)]
pub struct ImageContent {
    pub(crate) coordinates: String,
    pub(crate) content: Vec<u8>,
    pub(crate) filename: String,
    pub(crate) extension: String,
    pub(crate) name: Option<String>,
    pub(crate) description: Option<String>,
}

impl ImageContent {
    /// The cell the image sits on, such as `B3`.
    pub fn coordinates(&self) -> &str {
        &self.coordinates
    }

    /// The image's bytes: `content()`.
    pub fn content(&self) -> &[u8] {
        &self.content
    }

    /// The image's file name in the workbook, such as `image1.png`: `filename()`.
    pub fn filename(&self) -> &str {
        &self.filename
    }

    /// The file extension, such as `png`: `extension()`.
    pub fn extension(&self) -> &str {
        &self.extension
    }

    /// The drawing's name.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// The drawing's description (alt text).
    pub fn description(&self) -> Option<&str> {
        self.description.as_deref()
    }

    /// Stores the image on a disk, the default one without `disk`: `store($path, $disk)`.
    pub async fn store(&self, path: &str, disk: Option<&str>) -> laravel::Result<()> {
        let disk = match disk {
            Some(name) => laravel::storage::disk(name)?,
            None => laravel::storage::default_disk()?,
        };
        disk.put(path, self.content.clone()).await?;
        Ok(())
    }
}

/// One sheet's extras.
#[derive(Debug, Clone, Default)]
pub(crate) struct SheetExtras {
    pub rich_texts: Vec<(Coordinate, Vec<TextRun>)>,
    pub hyperlinks: Vec<(Coordinate, Hyperlink)>,
    pub images: Vec<ImageContent>,
    pub styles: Vec<(Coordinate, Style)>,
    /// `(first column, last column, width, hidden)`.
    pub columns: Vec<(u32, u32, Option<f64>, bool)>,
    pub row_heights: Vec<(u32, f64)>,
    pub merges: Vec<String>,
}

/// PhpSpreadsheet's built-in format codes, by `numFmtId`.
fn builtin_format(id: u32) -> Option<&'static str> {
    Some(match id {
        0 => "General",
        1 => "0",
        2 => "0.00",
        3 => "#,##0",
        4 => "#,##0.00",
        9 => "0%",
        10 => "0.00%",
        11 => "0.00E+00",
        12 => "# ?/?",
        13 => "# ??/??",
        14 => "m/d/yyyy",
        15 => "d-mmm-yy",
        16 => "d-mmm",
        17 => "mmm-yy",
        18 => "h:mm AM/PM",
        19 => "h:mm:ss AM/PM",
        20 => "h:mm",
        21 => "h:mm:ss",
        22 => "m/d/yyyy h:mm",
        37 => "#,##0_);(#,##0)",
        38 => "#,##0_);[Red](#,##0)",
        39 => "#,##0.00_);(#,##0.00)",
        40 => "#,##0.00_);[Red](#,##0.00)",
        44 => "_(\"$\"* #,##0.00_);_(\"$\"* \\(#,##0.00\\);_(\"$\"* \"-\"??_);_(@_)",
        45 => "mm:ss",
        46 => "[h]:mm:ss",
        47 => "mm:ss.0",
        48 => "##0.0E+0",
        49 => "@",
        _ => return None,
    })
}

fn border_style(name: &str) -> Option<BorderStyle> {
    Some(match name {
        "thin" => BorderStyle::Thin,
        "medium" => BorderStyle::Medium,
        "thick" => BorderStyle::Thick,
        "dashed" => BorderStyle::Dashed,
        "dotted" => BorderStyle::Dotted,
        "double" => BorderStyle::Double,
        "hair" => BorderStyle::Hair,
        "mediumDashed" => BorderStyle::MediumDashed,
        "dashDot" => BorderStyle::DashDot,
        "mediumDashDot" => BorderStyle::MediumDashDot,
        "dashDotDot" => BorderStyle::DashDotDot,
        "mediumDashDotDot" => BorderStyle::MediumDashDotDot,
        "slantDashDot" => BorderStyle::SlantDashDot,
        _ => return None,
    })
}

fn rgb_of(element: &BytesStart<'_>) -> Option<String> {
    attr(element, "rgb").map(|rgb| if rgb.len() == 8 { rgb[2..].to_owned() } else { rgb })
}

/// The style of each cell style (`cellXfs`), by index: font, fill, borders, alignment and number
/// format (`None` for `General`), as PhpSpreadsheet's reader loads them out of read-only mode.
fn cell_styles(archive: &mut Archive, path: &str) -> Vec<Style> {
    let mut styles = Vec::new();
    let Some(bytes) = entry(archive, path) else {
        return styles;
    };
    let mut custom: HashMap<u32, String> = HashMap::new();
    let mut fonts: Vec<Style> = Vec::new();
    let mut fills: Vec<Option<String>> = Vec::new();
    let mut borders: Vec<crate::style::Borders> = Vec::new();
    let mut section = "";
    let mut border_side: Option<&'static str> = None;
    let mut fill_solid = false;
    let mut reader = Reader::from_reader(bytes.as_slice());
    let mut buffer = Vec::new();
    loop {
        let event = reader.read_event_into(&mut buffer);
        match event {
            Ok(Event::Start(ref element)) | Ok(Event::Empty(ref element)) => {
                let empty = matches!(event, Ok(Event::Empty(_)));
                match local_name(element.name().as_ref()) {
                    "numFmt" => {
                        if let (Some(id), Some(code)) = (
                            attr(element, "numFmtId").and_then(|id| id.parse().ok()),
                            attr(element, "formatCode"),
                        ) {
                            custom.insert(id, code);
                        }
                    }
                    name @ ("fonts" | "fills" | "borders" | "cellXfs" | "cellStyleXfs" | "dxfs") if !empty => {
                        section = match name {
                            "fonts" => "fonts",
                            "fills" => "fills",
                            "borders" => "borders",
                            "cellXfs" => "cellXfs",
                            _ => "other",
                        }
                    }
                    "font" if section == "fonts" => fonts.push(Style::new()),
                    "fill" if section == "fills" => {
                        fills.push(None);
                        fill_solid = false;
                    }
                    "patternFill" if section == "fills" => {
                        fill_solid = attr(element, "patternType").as_deref() == Some("solid")
                    }
                    "fgColor" if section == "fills" && fill_solid => {
                        if let (Some(last), Some(rgb)) = (fills.last_mut(), rgb_of(element)) {
                            *last = Some(rgb);
                        }
                    }
                    "border" if section == "borders" => borders.push(crate::style::Borders::default()),
                    side @ ("left" | "right" | "top" | "bottom") if section == "borders" => {
                        border_side = Some(match side {
                            "left" => "left",
                            "right" => "right",
                            "top" => "top",
                            _ => "bottom",
                        });
                        if let (Some(last), Some(style)) = (
                            borders.last_mut(),
                            attr(element, "style").as_deref().and_then(border_style),
                        ) {
                            let border = Some(crate::style::Border { style, color: None });
                            match side {
                                "left" => last.left = border,
                                "right" => last.right = border,
                                "top" => last.top = border,
                                _ => last.bottom = border,
                            }
                        }
                        if empty {
                            border_side = None;
                        }
                    }
                    "color" if section == "borders" => {
                        if let (Some(last), Some(side), Some(rgb)) = (borders.last_mut(), border_side, rgb_of(element))
                        {
                            let slot = match side {
                                "left" => &mut last.left,
                                "right" => &mut last.right,
                                "top" => &mut last.top,
                                _ => &mut last.bottom,
                            };
                            if let Some(border) = slot {
                                border.color = Some(rgb);
                            }
                        }
                    }
                    name if section == "fonts" => {
                        let Some(font) = fonts.last_mut() else { continue };
                        let value = attr(element, "val");
                        let on = value.as_deref().is_none_or(|value| value != "0" && value != "false");
                        let current = std::mem::take(font);
                        *font = match name {
                            "b" if on => current.bold(),
                            "i" if on => current.italic(),
                            "u" if value.as_deref() != Some("none") => current.underline(),
                            "strike" if on => current.strikethrough(),
                            "sz" => match value.and_then(|value| value.parse().ok()) {
                                Some(size) => current.font_size(size),
                                None => current,
                            },
                            "name" => match value {
                                Some(name) => current.font_name(name),
                                None => current,
                            },
                            "color" => match rgb_of(element) {
                                Some(rgb) => current.font_color(rgb),
                                None => current,
                            },
                            _ => current,
                        };
                    }
                    "xf" if section == "cellXfs" => {
                        let index = |name: &str| attr(element, name).and_then(|id| id.parse::<usize>().ok());
                        let mut style = index("fontId")
                            .and_then(|id| fonts.get(id).cloned())
                            .unwrap_or_default();
                        // The default font isn't a style of the cell.
                        if index("fontId") == Some(0) {
                            style = Style::new();
                        }
                        if let Some(fill) = index("fillId").and_then(|id| fills.get(id).cloned().flatten()) {
                            style = style.background(fill);
                        }
                        if let Some(borders) = index("borderId").and_then(|id| borders.get(id).cloned()) {
                            style.borders = borders;
                        }
                        let id = index("numFmtId").unwrap_or(0) as u32;
                        let code = custom
                            .get(&id)
                            .cloned()
                            .or_else(|| builtin_format(id).map(str::to_owned));
                        if let Some(code) = code.filter(|code| code != "General") {
                            style = style.number_format(code);
                        }
                        styles.push(style);
                    }
                    "alignment" if section == "cellXfs" => {
                        if let Some(style) = styles.last_mut() {
                            let current = std::mem::take(style);
                            let mut aligned = match attr(element, "horizontal").as_deref() {
                                Some("left") => current.horizontal(Horizontal::Left),
                                Some("right") => current.horizontal(Horizontal::Right),
                                Some("center") => current.horizontal(Horizontal::Center),
                                Some("centerContinuous") => current.horizontal(Horizontal::CenterContinuous),
                                Some("justify") => current.horizontal(Horizontal::Justify),
                                Some("fill") => current.horizontal(Horizontal::Fill),
                                Some("distributed") => current.horizontal(Horizontal::Distributed),
                                _ => current,
                            };
                            aligned = match attr(element, "vertical").as_deref() {
                                Some("top") => aligned.vertical(Vertical::Top),
                                Some("center") => aligned.vertical(Vertical::Center),
                                Some("justify") => aligned.vertical(Vertical::Justify),
                                Some("distributed") => aligned.vertical(Vertical::Distributed),
                                Some("bottom") => aligned.vertical(Vertical::Bottom),
                                _ => aligned,
                            };
                            if attr(element, "wrapText").as_deref() == Some("1") {
                                aligned = aligned.wrap_text();
                            }
                            if let Some(indent) = attr(element, "indent").and_then(|indent| indent.parse().ok()) {
                                aligned = aligned.indent(indent);
                            }
                            if let Some(rotation) =
                                attr(element, "textRotation").and_then(|rotation| rotation.parse().ok())
                            {
                                aligned = aligned.text_rotation(rotation);
                            }
                            *style = aligned;
                        }
                    }
                    _ => {}
                }
            }
            Ok(Event::End(ref element)) => match local_name(element.name().as_ref()) {
                "fonts" | "fills" | "borders" | "cellXfs" | "cellStyleXfs" | "dxfs" => section = "",
                "left" | "right" | "top" | "bottom" => border_side = None,
                _ => {}
            },
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
        buffer.clear();
    }
    styles
}

type Archive = zip::ZipArchive<Cursor<Vec<u8>>>;

fn entry(archive: &mut Archive, path: &str) -> Option<Vec<u8>> {
    let mut file = archive.by_name(path.trim_start_matches('/')).ok()?;
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes).ok()?;
    Some(bytes)
}

fn local_name(name: &str) -> &str {
    match name.rfind(':') {
        Some(index) => &name[index + 1..],
        None => name,
    }
}

fn attr(element: &BytesStart<'_>, name: &str) -> Option<String> {
    element.attributes().flatten().find_map(|attribute| {
        let key: &str = attribute.key.as_ref();
        (key == name || local_name(key) == name && !name.contains(':'))
            .then(|| {
                attribute
                    .normalized_value(XmlVersion::Implicit1_0)
                    .ok()
                    .map(|value| value.into_owned())
            })
            .flatten()
    })
}

/// Resolves a relationship target against the part that holds it, such as `../media/image1.png`
/// from `xl/drawings/drawing1.xml`.
fn resolve(base: &str, target: &str) -> String {
    if let Some(absolute) = target.strip_prefix('/') {
        return absolute.to_owned();
    }
    let mut parts: Vec<&str> = base.split('/').collect();
    parts.pop();
    for segment in target.split('/') {
        match segment {
            ".." => {
                parts.pop();
            }
            "." | "" => {}
            other => parts.push(other),
        }
    }
    parts.join("/")
}

fn rels_path(part: &str) -> String {
    match part.rsplit_once('/') {
        Some((directory, file)) => format!("{directory}/_rels/{file}.rels"),
        None => format!("_rels/{part}.rels"),
    }
}

/// A part's relationships: id → (target, type, external).
fn relationships(archive: &mut Archive, part: &str) -> HashMap<String, (String, String, bool)> {
    let mut map = HashMap::new();
    let Some(bytes) = entry(archive, &rels_path(part)) else {
        return map;
    };
    let mut reader = Reader::from_reader(bytes.as_slice());
    let mut buffer = Vec::new();
    loop {
        match reader.read_event_into(&mut buffer) {
            Ok(Event::Empty(element) | Event::Start(element))
                if local_name(element.name().as_ref()) == "Relationship" =>
            {
                if let (Some(id), Some(target)) = (attr(&element, "Id"), attr(&element, "Target")) {
                    let kind = attr(&element, "Type").unwrap_or_default();
                    let external = attr(&element, "TargetMode").is_some_and(|mode| mode == "External");
                    map.insert(id, (target, kind, external));
                }
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
        buffer.clear();
    }
    map
}

/// Reads the `<r>` runs and bare `<t>` text of an `<si>` or `<is>` element, after its start.
fn read_runs(reader: &mut Reader<&[u8]>, end: &str) -> Vec<TextRun> {
    let mut runs = Vec::new();
    let mut buffer = Vec::new();
    let mut in_run = false;
    let mut in_properties = false;
    let mut in_text = false;
    let mut in_phonetic = false;
    let mut current = TextRun::default();
    loop {
        let event = reader.read_event_into(&mut buffer);
        match event {
            Ok(Event::Start(ref element)) | Ok(Event::Empty(ref element)) => {
                let empty = matches!(event, Ok(Event::Empty(_)));
                match local_name(element.name().as_ref()) {
                    "rPh" => in_phonetic = !empty,
                    "r" if !in_phonetic => {
                        in_run = true;
                        current = TextRun::default();
                    }
                    "rPr" => in_properties = !empty,
                    "t" if !in_phonetic => {
                        in_text = !empty;
                        if !in_run {
                            current = TextRun {
                                plain: true,
                                ..TextRun::default()
                            };
                        }
                    }
                    name if in_properties || (in_run && empty) => {
                        let value = attr(element, "val");
                        let on = value.as_deref().is_none_or(|value| value != "0" && value != "false");
                        let style = &mut current.style;
                        match name {
                            "b" if on => *style = std::mem::take(style).bold(),
                            "i" if on => *style = std::mem::take(style).italic(),
                            "u" if value.as_deref() != Some("none") => *style = std::mem::take(style).underline(),
                            "strike" if on => *style = std::mem::take(style).strikethrough(),
                            "sz" => {
                                if let Some(size) = value.and_then(|value| value.parse().ok()) {
                                    *style = std::mem::take(style).font_size(size);
                                }
                            }
                            "rFont" => {
                                if let Some(font) = value {
                                    *style = std::mem::take(style).font_name(font);
                                }
                            }
                            "color" => {
                                if let Some(rgb) = attr(element, "rgb") {
                                    let rgb = if rgb.len() == 8 { rgb[2..].to_owned() } else { rgb };
                                    *style = std::mem::take(style).font_color(rgb);
                                }
                            }
                            "vertAlign" => match value.as_deref() {
                                Some("superscript") => current.superscript = true,
                                Some("subscript") => current.subscript = true,
                                _ => {}
                            },
                            _ => {}
                        }
                    }
                    _ => {}
                }
            }
            Ok(Event::Text(text)) if in_text => {
                current.text.push_str(&text.xml_content(XmlVersion::Implicit1_0));
            }
            Ok(Event::GeneralRef(reference)) if in_text => {
                let name = reference.to_string();
                let decoded = crate::html::decode_entities(&format!("&{name};"));
                current.text.push_str(&decoded);
            }
            Ok(Event::CData(text)) if in_text => current.text.push_str(&text),
            Ok(Event::End(element)) => match local_name(element.name().as_ref()) {
                "rPh" => in_phonetic = false,
                "rPr" => in_properties = false,
                "t" if !in_phonetic => {
                    in_text = false;
                    if !in_run {
                        runs.push(std::mem::take(&mut current));
                    }
                }
                "r" if !in_phonetic => {
                    in_run = false;
                    runs.push(std::mem::take(&mut current));
                }
                name if name == end => break,
                _ => {}
            },
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
        buffer.clear();
    }
    runs
}

/// The shared strings that hold runs, by index.
fn shared_strings(archive: &mut Archive, path: &str) -> Vec<Option<Vec<TextRun>>> {
    let mut strings = Vec::new();
    let Some(bytes) = entry(archive, path) else {
        return strings;
    };
    let mut reader = Reader::from_reader(bytes.as_slice());
    let mut buffer = Vec::new();
    loop {
        match reader.read_event_into(&mut buffer) {
            Ok(Event::Start(element)) if local_name(element.name().as_ref()) == "si" => {
                let runs = read_runs(&mut reader, "si");
                strings.push(runs.iter().any(|run| !run.plain).then_some(runs));
            }
            Ok(Event::Empty(element)) if local_name(element.name().as_ref()) == "si" => strings.push(None),
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
        buffer.clear();
    }
    strings
}

fn sheet_extras(archive: &mut Archive, part: &str, strings: &[Option<Vec<TextRun>>], formats: &[Style]) -> SheetExtras {
    let mut extras = SheetExtras::default();
    let Some(bytes) = entry(archive, part) else {
        return extras;
    };
    let rels = relationships(archive, part);
    let mut reader = Reader::from_reader(bytes.as_slice());
    let mut buffer = Vec::new();
    let mut cell: Option<(Coordinate, String)> = None;
    let mut in_value = false;
    let mut drawing_ids = Vec::new();
    loop {
        match reader.read_event_into(&mut buffer) {
            Ok(Event::Start(element)) => match local_name(element.name().as_ref()) {
                "row" => {
                    if attr(&element, "customHeight").is_some_and(|custom| custom == "1" || custom == "true")
                        && let (Some(row), Some(height)) = (
                            attr(&element, "r").and_then(|row| row.parse::<u32>().ok()),
                            attr(&element, "ht").and_then(|height| height.parse::<f64>().ok()),
                        )
                    {
                        extras.row_heights.push((row, height));
                    }
                }
                "c" => {
                    cell = attr(&element, "r")
                        .and_then(|r| Coordinate::parse(&r).ok())
                        .map(|coordinate| (coordinate, attr(&element, "t").unwrap_or_default()));
                    if let Some((coordinate, _)) = &cell
                        && let Some(style) = attr(&element, "s")
                            .and_then(|index| index.parse::<usize>().ok())
                            .and_then(|index| formats.get(index))
                        && !style.is_empty()
                    {
                        extras.styles.push((*coordinate, style.clone()));
                    }
                }
                "v" => in_value = true,
                "is" => {
                    let runs = read_runs(&mut reader, "is");
                    if let Some((coordinate, _)) = &cell
                        && runs.iter().any(|run| !run.plain)
                    {
                        extras.rich_texts.push((*coordinate, runs));
                    }
                }
                _ => {}
            },
            Ok(Event::Text(text)) if in_value => {
                if let Some((coordinate, kind)) = &cell
                    && kind == "s"
                    && let Ok(index) = text.xml_content(XmlVersion::Implicit1_0).trim().parse::<usize>()
                    && let Some(Some(runs)) = strings.get(index)
                {
                    extras.rich_texts.push((*coordinate, runs.clone()));
                }
            }
            Ok(Event::End(element)) => match local_name(element.name().as_ref()) {
                "v" => in_value = false,
                "c" => cell = None,
                _ => {}
            },
            Ok(Event::Empty(element)) => match local_name(element.name().as_ref()) {
                "c" => {
                    if let Some(coordinate) = attr(&element, "r").and_then(|r| Coordinate::parse(&r).ok())
                        && let Some(style) = attr(&element, "s")
                            .and_then(|index| index.parse::<usize>().ok())
                            .and_then(|index| formats.get(index))
                        && !style.is_empty()
                    {
                        extras.styles.push((coordinate, style.clone()));
                    }
                }
                "col" => {
                    let number = |name: &str| attr(&element, name).and_then(|value| value.parse::<u32>().ok());
                    if let (Some(min), Some(max)) = (number("min"), number("max")) {
                        let width = attr(&element, "customWidth")
                            .filter(|custom| custom == "1" || custom == "true")
                            .and(attr(&element, "width"))
                            .and_then(|width| width.parse().ok());
                        let hidden = attr(&element, "hidden").is_some_and(|hidden| hidden == "1" || hidden == "true");
                        if width.is_some() || hidden {
                            extras.columns.push((min, max.min(min + 1000), width, hidden));
                        }
                    }
                }
                "mergeCell" => {
                    if let Some(reference) = attr(&element, "ref") {
                        extras.merges.push(reference);
                    }
                }
                "hyperlink" => {
                    let Some(reference) = attr(&element, "ref") else {
                        continue;
                    };
                    let first = reference.split(':').next().unwrap_or_default();
                    let Ok(coordinate) = Coordinate::parse(first) else {
                        continue;
                    };
                    let url = match attr(&element, "r:id").and_then(|id| rels.get(&id).cloned()) {
                        Some((target, _, _)) => target,
                        None => attr(&element, "location")
                            .map(|location| format!("sheet://{location}"))
                            .unwrap_or_default(),
                    };
                    extras.hyperlinks.push((
                        coordinate,
                        Hyperlink {
                            url,
                            tooltip: attr(&element, "tooltip"),
                        },
                    ));
                }
                "drawing" => {
                    if let Some(id) = attr(&element, "r:id") {
                        drawing_ids.push(id);
                    }
                }
                _ => {}
            },
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
        buffer.clear();
    }
    for id in drawing_ids {
        if let Some((target, _, false)) = rels.get(&id).cloned() {
            let drawing = resolve(part, &target);
            extras.images.extend(images(archive, &drawing));
        }
    }
    extras
}

/// The pictures of a drawing part, at their anchors' top left cells.
fn images(archive: &mut Archive, part: &str) -> Vec<ImageContent> {
    let mut images = Vec::new();
    let Some(bytes) = entry(archive, part) else {
        return images;
    };
    let rels = relationships(archive, part);
    let mut reader = Reader::from_reader(bytes.as_slice());
    let mut buffer = Vec::new();
    let mut in_from = false;
    let mut field: Option<&'static str> = None;
    let mut column = 0u32;
    let mut row = 0u32;
    let mut name = None;
    let mut description = None;
    loop {
        let event = reader.read_event_into(&mut buffer);
        match event {
            Ok(Event::Start(ref element)) | Ok(Event::Empty(ref element)) => {
                match local_name(element.name().as_ref()) {
                    "twoCellAnchor" | "oneCellAnchor" => {
                        name = None;
                        description = None;
                    }
                    "from" => in_from = true,
                    "col" if in_from => field = Some("col"),
                    "row" if in_from => field = Some("row"),
                    "cNvPr" => {
                        name = attr(element, "name");
                        description = attr(element, "descr");
                    }
                    "blip" => {
                        if let Some((target, _, false)) = attr(element, "r:embed").and_then(|id| rels.get(&id).cloned())
                        {
                            let path = resolve(part, &target);
                            if let Some(content) = entry(archive, &path) {
                                let filename = path.rsplit('/').next().unwrap_or_default().to_owned();
                                let extension = filename
                                    .rsplit_once('.')
                                    .map(|(_, ext)| ext.to_ascii_lowercase())
                                    .unwrap_or_default();
                                images.push(ImageContent {
                                    coordinates: Coordinate::new(column + 1, row + 1).to_string(),
                                    content,
                                    filename,
                                    extension,
                                    name: name.clone(),
                                    description: description.clone().filter(|text: &String| !text.is_empty()),
                                });
                            }
                        }
                    }
                    _ => {}
                }
            }
            Ok(Event::Text(text)) => {
                let value = text.xml_content(XmlVersion::Implicit1_0).trim().parse().unwrap_or(0);
                match field {
                    Some("col") => column = value,
                    Some("row") => row = value,
                    _ => {}
                }
            }
            Ok(Event::End(element)) => match local_name(element.name().as_ref()) {
                "from" => in_from = false,
                "col" | "row" => field = None,
                _ => {}
            },
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
        buffer.clear();
    }
    images
}

/// Reads every sheet's extras, by sheet name.
pub(crate) fn read(bytes: &[u8]) -> HashMap<String, SheetExtras> {
    let mut result = HashMap::new();
    let Ok(mut archive) = zip::ZipArchive::new(Cursor::new(bytes.to_vec())) else {
        return result;
    };
    let workbook = "xl/workbook.xml";
    let rels = relationships(&mut archive, workbook);
    let shared = rels
        .values()
        .find(|(_, kind, _)| kind.ends_with("/sharedStrings"))
        .map(|(target, _, _)| resolve(workbook, target))
        .unwrap_or_else(|| "xl/sharedStrings.xml".to_owned());
    let strings = shared_strings(&mut archive, &shared);
    let styles = rels
        .values()
        .find(|(_, kind, _)| kind.ends_with("/styles"))
        .map(|(target, _, _)| resolve(workbook, target))
        .unwrap_or_else(|| "xl/styles.xml".to_owned());
    let formats = cell_styles(&mut archive, &styles);
    let Some(bytes) = entry(&mut archive, workbook) else {
        return result;
    };
    let mut sheets = Vec::new();
    let mut reader = Reader::from_reader(bytes.as_slice());
    let mut buffer = Vec::new();
    loop {
        match reader.read_event_into(&mut buffer) {
            Ok(Event::Empty(element) | Event::Start(element)) if local_name(element.name().as_ref()) == "sheet" => {
                if let (Some(name), Some(id)) = (attr(&element, "name"), attr(&element, "r:id")) {
                    sheets.push((name, id));
                }
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
        buffer.clear();
    }
    for (name, id) in sheets {
        if let Some((target, _, _)) = rels.get(&id) {
            let part = resolve(workbook, target);
            result.insert(name, sheet_extras(&mut archive, &part, &strings, &formats));
        }
    }
    result
}