fast-excel 1.0.0

通用 Excel 导入导出工具:流式读写(百万级)、动态表头适配、多 sheet、单元格图片、批量落库(纯 Rust,对标 EasyExcel)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
//! 工作表行流:SAX 式逐行解析(百万行常量内存)
//!
//! 与 `calamine` 的 `worksheet_range`(一次性把整表读成二维数组)不同,这里
//! 直接用 `quick-xml` 事件流扫 `xl/worksheets/sheetN.xml`,每行解析完立刻交给
//! 调用方处理:内存占用与**列数**相关,与行数无关。

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

use chrono::NaiveTime;
use quick_xml::Reader;
use quick_xml::events::{BytesStart, Event};

use crate::column::ColumnDef;
use crate::error::{ExcelError, Result};
use crate::header::{HeaderAnalysis, HeaderMap, resolve_headers};
use crate::model::{RowData, RowImage};
use crate::read::ReadOptions;
use crate::read::images::{
    AnchorImage, AnchorIndex, load_media, load_sheet_anchors, load_wps_index, parse_dispimg_id,
};
use crate::read::merges::MergeRange;
use crate::read::sheet_meta::{
    Comment, ConditionalFormat, DataValidation, Hyperlink, MetaWants, load_comments,
    load_sheet_meta,
};
use crate::read::shared_strings::{SharedStrings, decode_text};
use crate::read::source::{EntryReader, ZipSource};
use crate::read::styles::Styles;
use crate::value::{Cell, CellValue, parse_datetime_text, serial_to_datetime};

/// 当前正在采集的文本目标
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Capture {
    None,
    Value,
    Formula,
    Inline,
}

/// `<c t="...">` 单元格类型(缺省 = 数字)
///
/// 用 `Copy` 枚举而不是 `Vec<u8>`:单元格是百万行场景的热路径,
/// 每格一次堆分配完全没有必要。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum CellType {
    /// 无 `t` 属性:数字 / 日期序列号
    #[default]
    Number,
    /// `t="s"`:共享字符串索引
    SharedString,
    /// `t="inlineStr"`:内联字符串
    InlineString,
    /// `t="str"`:公式结果字符串
    String,
    /// `t="b"`:布尔
    Bool,
    /// `t="e"`:错误值
    Error,
    /// `t="d"`:ISO 日期文本
    Date,
}

/// 行流内部:一个仍在生效的合并区域(含锚点值,供后续行回填)
#[derive(Debug, Clone)]
struct ActiveMerge {
    range: MergeRange,
    /// 左上角单元格的值(在锚点行抓取,之后的行复用它)
    value: Option<CellValue>,
}

/// 工作表行流
pub struct SheetStream {
    xml: Reader<BufReader<EntryReader>>,
    buf: Vec<u8>,
    source: ZipSource,
    sheet_name: String,
    date_1904: bool,
    shared: Arc<SharedStrings>,
    styles: Arc<Styles>,
    defs: Vec<ColumnDef>,
    options: ReadOptions,

    // 图片
    anchors_by_row: HashMap<u32, Vec<(u16, AnchorImage)>>,
    wps_index: Option<HashMap<String, String>>,
    pending_dispimg: Vec<(u16, String)>,

    // 合并单元格(仅当 options.read_merges)
    merges: Vec<MergeRange>,
    merge_cursor: usize,
    active_merges: Vec<ActiveMerge>,
    current_merges: Vec<MergeRange>,

    /// 列默认值兜底:`(文件列, 默认文本)`(见 `ColumnDef::default`)
    defaults_by_col: Vec<(u16, String)>,

    /// 超链接 / 批注(仅当对应开关打开)
    hyperlinks: Vec<Hyperlink>,
    comments: Vec<Comment>,
    validations: Vec<DataValidation>,
    conditional_formats: Vec<ConditionalFormat>,

    // 当前行
    current_row: u32,
    last_row: u32,
    cells: Vec<Cell>,
    images: Vec<RowImage>,
    cell_active: bool,
    cell_col: u16,
    cell_last_col: u16,
    cell_type: CellType,
    cell_style: u32,
    value_buf: String,
    formula_buf: String,
    inline_buf: String,
    capture: Capture,
    in_inline_str: bool,

    // 表头
    header: Option<HeaderMap>,
    header_cells: Vec<Vec<String>>,
    header_done: bool,
    /// 实际需要读图的文件列(None = 全部;Some(空) = 不读)
    image_cols: Option<Vec<u16>>,

    // 统计
    pub rows_scanned: u64,
    pub rows_yielded: u64,
    /// 跳过的空行数
    pub skipped_rows: u64,
    /// 是否因 max_rows 提前停止(预览时判断还有更多行)
    limit_hit: bool,
    finished: bool,
}

impl SheetStream {
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        source: ZipSource,
        sheet_path: &str,
        sheet_name: &str,
        date_1904: bool,
        shared: Arc<SharedStrings>,
        styles: Arc<Styles>,
        defs: &[ColumnDef],
        options: ReadOptions,
    ) -> Result<Self> {
        let entry = source.entry_reader(sheet_path)?;
        let xml = Reader::from_reader(BufReader::with_capacity(256 * 1024, entry));

        // 图片锚点索引:只在需要读图时建立(索引很小;图片字节仍按需读)
        let mut anchors_by_row: HashMap<u32, Vec<(u16, AnchorImage)>> = HashMap::new();
        if options.read_images {
            let anchors: AnchorIndex = load_sheet_anchors(&source, sheet_path)?;
            for ((row, col), anchor) in anchors {
                anchors_by_row.entry(row).or_default().push((col, anchor));
            }
            for list in anchors_by_row.values_mut() {
                list.sort_by_key(|(c, _)| *c);
            }
        }

        // 合并区域 / 超链接 / 数据验证:都在 `<sheetData>` 之后,先独立扫一遍
        let meta = load_sheet_meta(
            &source,
            sheet_path,
            MetaWants {
                merges: options.read_merges,
                hyperlinks: options.read_hyperlinks,
                validations: options.read_validations,
                conditional_formats: options.read_conditional_formats,
            },
        )?;
        let merges = meta.merges;
        let comments = if options.read_comments {
            load_comments(&source, sheet_path)?
        } else {
            Vec::new()
        };

        Ok(Self {
            xml,
            buf: Vec::with_capacity(64 * 1024),
            source,
            sheet_name: sheet_name.to_string(),
            date_1904,
            shared,
            styles,
            defs: defs.to_vec(),
            options,
            anchors_by_row,
            wps_index: None,
            pending_dispimg: Vec::new(),
            merges,
            merge_cursor: 0,
            active_merges: Vec::new(),
            current_merges: Vec::new(),
            defaults_by_col: Vec::new(),
            hyperlinks: meta.hyperlinks,
            comments,
            validations: meta.validations,
            conditional_formats: meta.conditional_formats,
            current_row: 0,
            last_row: 0,
            cells: Vec::new(),
            images: Vec::new(),
            cell_active: false,
            cell_col: 0,
            cell_last_col: 0,
            cell_type: CellType::default(),
            cell_style: 0,
            value_buf: String::new(),
            formula_buf: String::new(),
            inline_buf: String::new(),
            capture: Capture::None,
            in_inline_str: false,
            header: None,
            header_cells: Vec::new(),
            header_done: false,
            image_cols: None,
            rows_scanned: 0,
            rows_yielded: 0,
            skipped_rows: 0,
            limit_hit: false,
            finished: false,
        })
    }

    // ───────────────────────────── 对外接口 ─────────────────────────────

    /// 表头解析结果(进入数据行后才有值)
    pub fn header(&self) -> Option<&HeaderMap> {
        self.header.as_ref()
    }

    /// 表头自适应报告(列匹配情况 / 缺失必填列 / 多出来的列)
    pub fn header_analysis(&self) -> Option<HeaderAnalysis> {
        self.header.as_ref().map(|h| h.analysis())
    }

    pub fn sheet_name(&self) -> &str {
        &self.sheet_name
    }

    pub fn is_finished(&self) -> bool {
        self.finished
    }

    /// 是否因 max_rows 提前停止(预览用)
    pub fn limit_hit(&self) -> bool {
        self.limit_hit
    }

    /// 本工作表的全部合并区域(仅当 [`ReadOptions::with_merges`] 开启时非空)
    pub fn merges(&self) -> &[MergeRange] {
        &self.merges
    }

    /// 本工作表的全部超链接(仅当 [`ReadOptions::with_hyperlinks`] 开启时非空)
    pub fn hyperlinks(&self) -> &[Hyperlink] {
        &self.hyperlinks
    }

    /// 某个单元格的超链接
    pub fn hyperlink_at(&self, row: u32, col: u16) -> Option<&Hyperlink> {
        self.hyperlinks.iter().find(|h| h.contains(row, col))
    }

    /// 本工作表的全部批注(仅当 [`ReadOptions::with_comments`] 开启时非空)
    pub fn comments(&self) -> &[Comment] {
        &self.comments
    }

    /// 本工作表的全部数据验证(下拉 / 数值区间;仅当 [`ReadOptions::with_validations`] 开启时非空)
    pub fn validations(&self) -> &[DataValidation] {
        &self.validations
    }

    /// 某个单元格命中的数据验证
    pub fn validation_at(&self, row: u32, col: u16) -> Option<&DataValidation> {
        self.validations.iter().find(|v| v.contains(row, col))
    }

    /// 本工作表的条件格式(仅当 [`ReadOptions::with_conditional_formats`] 开启时非空)
    pub fn conditional_formats(&self) -> &[ConditionalFormat] {
        &self.conditional_formats
    }

    /// 某个单元格命中的条件格式
    pub fn conditional_format_at(&self, row: u32, col: u16) -> Option<&ConditionalFormat> {
        self.conditional_formats.iter().find(|cf| cf.contains(row, col))
    }

    /// 某个单元格的批注文本
    pub fn comment_at(&self, row: u32, col: u16) -> Option<&Comment> {
        self.comments
            .iter()
            .find(|c| c.row == row && c.col == col)
    }

    /// 取下一行数据;`None` = 读完
    pub fn next_row(&mut self) -> Result<Option<RowData<'_>>> {
        if self.finished {
            return Ok(None);
        }
        if let Some(max) = self.options.max_rows {
            if self.rows_yielded >= max {
                self.limit_hit = true;
                self.finished = true;
                return Ok(None);
            }
        }

        loop {
            if !self.read_next_row_element()? {
                if !self.header_done {
                    self.build_header();
                }
                self.finished = true;
                return Ok(None);
            }

            self.rows_scanned += 1;
            let row_index = self.current_row;

            // 合并单元格回填(在表头采集 / 空行判断之前,保证合并不被读成空值)
            self.apply_merges(row_index);

            if !self.header_done {
                let start = self.options.header.row_index + 1;
                let end = start + self.options.header.row_span.max(1) - 1;
                if row_index < start {
                    continue;
                }
                if row_index <= end {
                    self.collect_header_row(row_index - start);
                    continue;
                }
                self.build_header();
            }

            // 列默认值兜底 → 导入计算列(计算列能看到兜底后的值)
            self.apply_defaults(row_index);
            self.apply_computed(row_index);
            self.collect_row_images(row_index)?;

            // 行过滤:业务自定义(跳过表尾"合计 / 备注"等脚注行)
            let keep = match (self.options.row_filter.as_ref(), self.header.as_ref()) {
                (Some(filter), Some(header)) => {
                    let row = RowData {
                        row_index,
                        sheet: &self.sheet_name,
                        header,
                        cells: &self.cells,
                        images: &self.images,
                        merges: &self.current_merges,
                        styles: self.styles.as_ref(),
                        hyperlinks: &self.hyperlinks,
                        comments: &self.comments,
                        validations: &self.validations,
                        conditional_formats: &self.conditional_formats,
                    };
                    filter.keep(&row)
                }
                _ => true,
            };
            if !keep {
                self.skipped_rows += 1;
                continue;
            }

            let empty = self.cells.iter().all(|c| c.value.is_empty());
            if empty && self.images.is_empty() && self.options.skip_empty_rows {
                self.skipped_rows += 1;
                continue;
            }
            self.rows_yielded += 1;
            let Some(header) = self.header.as_ref() else {
                // 不变量:产出首行前表头一定已构建;这里兜底返回错误而非 panic
                return Err(ExcelError::Other("工作表表头尚未构建".to_string()));
            };
            return Ok(Some(RowData {
                row_index,
                sheet: &self.sheet_name,
                header,
                cells: &self.cells,
                images: &self.images,
                merges: &self.current_merges,
                styles: self.styles.as_ref(),
                hyperlinks: &self.hyperlinks,
                comments: &self.comments,
                validations: &self.validations,
                conditional_formats: &self.conditional_formats,
            }));
        }
    }

    // ───────────────────────────── 合并单元格 ─────────────────────────────

    /// 把覆盖当前行的合并区域左上角的值回填到区域内单元格
    ///
    /// 行号单调递增,因此用游标增量激活合并区域,均摊 O(1):
    /// - 锚点行(`first_row`)只补右侧列;
    /// - 后续行补整段列(值来自锚点行抓取的缓存)。
    fn apply_merges(&mut self, row_index: u32) {
        if self.merges.is_empty() {
            return; // 未开启或本表没有合并
        }
        while self.merge_cursor < self.merges.len()
            && self.merges[self.merge_cursor].first_row <= row_index
        {
            let range = self.merges[self.merge_cursor];
            self.active_merges.push(ActiveMerge { range, value: None });
            self.merge_cursor += 1;
        }
        self.active_merges.retain(|m| m.range.last_row >= row_index);
        if self.active_merges.is_empty() {
            self.current_merges.clear();
            return;
        }

        let fill = self.options.fill_merged;
        let mut added = false;
        let mut active = std::mem::take(&mut self.active_merges);
        for m in active.iter_mut() {
            // 锚点行:抓取左上角的值(后续行复用它)
            if m.range.first_row == row_index && m.value.is_none() {
                if let Some(c) = self.cells.iter().find(|c| c.col == m.range.first_col) {
                    if !c.value.is_empty() {
                        m.value = Some(c.value.clone());
                    }
                }
            }
            if !fill {
                continue;
            }
            let Some(value) = m.value.clone() else { continue };
            if value.is_empty() {
                continue;
            }
            let start = if m.range.first_row == row_index {
                m.range.first_col.saturating_add(1)
            } else {
                m.range.first_col
            };
            for col in start..=m.range.last_col {
                // 合并区间内除锚点外的单元格通常是「空白格式单元格」(有 <c> 无 <v>),
                // 读到的是 CellValue::Empty —— 这类要覆盖成锚点值;已有真实值的保留。
                match self.cells.iter_mut().find(|c| c.col == col) {
                    Some(c) if c.value.is_empty() => {
                        c.value = value.clone();
                        added = true;
                    }
                    Some(_) => {}
                    None => {
                        self.cells.push(Cell {
                            row: row_index,
                            col,
                            value: value.clone(),
                            style: 0,
                        });
                        added = true;
                    }
                }
            }
        }
        self.active_merges = active;
        if added {
            self.cells.sort_by_key(|c| c.col);
        }
        self.current_merges.clear();
        self.current_merges
            .extend(self.active_merges.iter().map(|m| m.range));
    }

    // ───────────────────────────── 导入计算列 ─────────────────────────────

    /// 用本行原始数据求出计算列的值,注入为合成单元格(模型按同表头即可取到)
    fn apply_computed(&mut self, row_index: u32) {
        if self.options.computed.is_empty() {
            return;
        }
        let Some(header) = self.header.as_ref() else {
            return;
        };
        let mut values: Vec<(u16, CellValue)> = Vec::with_capacity(self.options.computed.len());
        {
            let row = RowData {
                row_index,
                sheet: &self.sheet_name,
                header,
                cells: &self.cells,
                images: &self.images,
                merges: &self.current_merges,
                styles: self.styles.as_ref(),
                hyperlinks: &self.hyperlinks,
                comments: &self.comments,
                validations: &self.validations,
                conditional_formats: &self.conditional_formats,
            };
            for cc in &self.options.computed {
                let Some(col) = row
                    .header
                    .file_headers
                    .iter()
                    .position(|h| h.as_str() == cc.header())
                else {
                    continue;
                };
                values.push((col as u16, cc.eval(&row)));
            }
        }
        if values.is_empty() {
            return;
        }
        self.inject_cells(row_index, values);
    }

    /// 列默认值兜底:本行为空且列配置了 `default` 时填入(`#[excel(default = "...")]`)
    fn apply_defaults(&mut self, row_index: u32) {
        if self.defaults_by_col.is_empty() {
            return;
        }
        let mut values: Vec<(u16, CellValue)> = Vec::new();
        for (col, text) in &self.defaults_by_col {
            let empty = self
                .cells
                .iter()
                .find(|c| c.col == *col)
                .map(|c| c.value.is_empty())
                .unwrap_or(true);
            if empty {
                values.push((*col, CellValue::Text(text.clone())));
            }
        }
        if values.is_empty() {
            return;
        }
        self.inject_cells(row_index, values);
    }

    /// 把合成单元格写入当前行(已存在则改写值),保持列序
    fn inject_cells(&mut self, row_index: u32, values: Vec<(u16, CellValue)>) {
        for (col, value) in values {
            match self.cells.iter_mut().find(|c| c.col == col) {
                Some(c) => c.value = value,
                None => self.cells.push(Cell {
                    row: row_index,
                    col,
                    value,
                    style: 0,
                }),
            }
        }
        self.cells.sort_by_key(|c| c.col);
    }

    // ───────────────────────────── 行解析 ─────────────────────────────

    /// 读到一行结束(`</row>`)为止
    fn read_next_row_element(&mut self) -> Result<bool> {
        self.cells.clear();
        self.images.clear();
        let mut row_seen = false;

        loop {
            self.buf.clear();
            let event = match self.xml.read_event_into(&mut self.buf) {
                Ok(Event::Eof) => return Ok(row_seen),
                Ok(ev) => ev,
                Err(e) => return Err(e.into()),
            };

            let mut begin: Option<(Option<u16>, CellType, u32)> = None;
            let mut cell_end = false;
            let mut row_end = false;

            match event {
                Event::Start(ref e) => match e.local_name().as_ref() {
                    b"row" => {
                        row_seen = true;
                        self.current_row = row_index_of(e).unwrap_or(self.last_row + 1);
                        self.last_row = self.current_row;
                        self.cell_last_col = 0;
                        self.cells.clear();
                    }
                    b"c" => begin = Some(parse_cell_attrs(e)),
                    b"v" => self.capture = Capture::Value,
                    b"f" => self.capture = Capture::Formula,
                    b"is" => self.in_inline_str = true,
                    b"t" if self.in_inline_str => self.capture = Capture::Inline,
                    _ => {}
                },
                Event::Empty(ref e) => match e.local_name().as_ref() {
                    b"row" => {
                        row_seen = true;
                        self.current_row = row_index_of(e).unwrap_or(self.last_row + 1);
                        self.last_row = self.current_row;
                        self.cell_last_col = 0;
                        row_end = true;
                    }
                    b"c" => {
                        begin = Some(parse_cell_attrs(e));
                        cell_end = true;
                    }
                    _ => {}
                },
                Event::End(ref e) => match e.local_name().as_ref() {
                    b"row" => row_end = true,
                    b"c" => cell_end = true,
                    b"v" | b"f" => self.capture = Capture::None,
                    b"is" => {
                        self.in_inline_str = false;
                        self.capture = Capture::None;
                    }
                    b"t" if self.in_inline_str => self.capture = Capture::None,
                    _ => {}
                },
                Event::Text(ref t) => match self.capture {
                    Capture::Value => self.value_buf.push_str(&decode_text(t)),
                    Capture::Formula => self.formula_buf.push_str(&decode_text(t)),
                    Capture::Inline => self.inline_buf.push_str(&decode_text(t)),
                    Capture::None => {}
                },
                Event::CData(ref t) => match self.capture {
                    Capture::Value => self
                        .value_buf
                        .push_str(&String::from_utf8_lossy(t.as_ref())),
                    Capture::Formula => self
                        .formula_buf
                        .push_str(&String::from_utf8_lossy(t.as_ref())),
                    Capture::Inline => self
                        .inline_buf
                        .push_str(&String::from_utf8_lossy(t.as_ref())),
                    Capture::None => {}
                },
                _ => {}
            }

            if let Some((col, cell_type, style)) = begin {
                self.begin_cell(col, cell_type, style);
            }
            if cell_end {
                self.finish_cell();
            }
            if row_end {
                return Ok(true);
            }
        }
    }

    fn begin_cell(&mut self, col: Option<u16>, cell_type: CellType, style: u32) {
        self.cell_active = true;
        self.cell_type = cell_type;
        self.cell_style = style;
        self.cell_col = col.unwrap_or_else(|| {
            if self.cells.is_empty() {
                0
            } else {
                self.cell_last_col + 1
            }
        });
        self.cell_last_col = self.cell_col;
        self.value_buf.clear();
        self.formula_buf.clear();
        self.inline_buf.clear();
        self.capture = Capture::None;
    }

    fn finish_cell(&mut self) {
        if !self.cell_active {
            return;
        }
        self.cell_active = false;

        let cell_type = self.cell_type;
        let style = self.cell_style;

        // 注意:只有真正需要"拥有"文本的分支才 `mem::take`(会丢掉 buffer 容量),
        // 其余分支保留内容,交给下一个 `begin_cell` 的 `clear()` 复用容量。
        // 这样数字 / 共享字符串这类最常见单元格不再每格重新分配。
        let mut value = match cell_type {
            CellType::SharedString => match self.value_buf.trim().parse::<usize>() {
                Ok(idx) => CellValue::Text(self.shared.get(idx).unwrap_or_default().to_string()),
                Err(_) => CellValue::Text(String::new()),
            },
            CellType::InlineString => CellValue::Text(std::mem::take(&mut self.inline_buf)),
            CellType::String => CellValue::Text(std::mem::take(&mut self.value_buf)),
            CellType::Bool => CellValue::Bool(matches!(self.value_buf.trim(), "1" | "true" | "TRUE")),
            CellType::Error => CellValue::Error(std::mem::take(&mut self.value_buf)),
            CellType::Date => match parse_datetime_text(self.value_buf.trim()) {
                Some(dt) => CellValue::DateTime(dt),
                None => CellValue::Text(std::mem::take(&mut self.value_buf)),
            },
            CellType::Number => {
                if self.value_buf.trim().is_empty() {
                    if self.formula_buf.is_empty() {
                        CellValue::Empty
                    } else {
                        CellValue::Formula(std::mem::take(&mut self.formula_buf))
                    }
                } else {
                    match self.value_buf.trim().parse::<f64>() {
                        Ok(n) => self.number_value(n, style),
                        Err(_) => CellValue::Text(std::mem::take(&mut self.value_buf)),
                    }
                }
            }
        };

        // WPS「单元格嵌入图片」:单元格是 DISPIMG 公式 → 记下 ID,按行 + 列取图
        if !self.formula_buf.is_empty() {
            if let Some(id) = parse_dispimg_id(&self.formula_buf) {
                self.pending_dispimg.push((self.cell_col, id));
                value = CellValue::Text(std::mem::take(&mut self.formula_buf));
            }
        }

        if let CellValue::Text(s) = &mut value {
            if self.options.trim_text {
                let trimmed = s.trim();
                if trimmed.len() != s.len() {
                    *s = trimmed.to_string();
                }
            }
        }

        self.cells.push(Cell {
            row: self.current_row,
            col: self.cell_col,
            value,
            style,
        });
    }

    /// 数字单元格:命中日期样式则转成日期/日期时间
    fn number_value(&self, n: f64, style: u32) -> CellValue {
        if self.styles.is_date(style) {
            if let Some(dt) = serial_to_datetime(n, self.date_1904) {
                let midnight = NaiveTime::from_hms_opt(0, 0, 0).unwrap();
                return if dt.time() == midnight {
                    CellValue::Date(dt.date())
                } else {
                    CellValue::DateTime(dt)
                };
            }
        }
        CellValue::Number(n)
    }

    // ───────────────────────────── 表头 ─────────────────────────────

    fn collect_header_row(&mut self, span_index: u32) {
        let span = self.options.header.row_span.max(1) as usize;
        let span_index = span_index as usize;
        let mut row_cells: Vec<(u16, String)> = self
            .cells
            .iter()
            .map(|c| (c.col, c.text()))
            .filter(|(_, t)| !t.is_empty())
            .collect();
        row_cells.sort_by_key(|(c, _)| *c);
        for (col, text) in row_cells {
            let col = col as usize;
            if self.header_cells.len() <= col {
                self.header_cells.resize(col + 1, vec![String::new(); span]);
            }
            if let Some(slot) = self.header_cells[col].get_mut(span_index) {
                *slot = text;
            }
        }
    }

    fn build_header(&mut self) {
        let span = self.options.header.row_span.max(1) as usize;
        let mut file_headers: Vec<String> = Vec::with_capacity(self.header_cells.len());
        for col in &self.header_cells {
            let parts: Vec<String> = (0..span)
                .filter_map(|i| col.get(i))
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            file_headers.push(parts.join(" "));
        }
        // 去掉尾部空表头(resize 出来的占位列)
        while matches!(file_headers.last(), Some(h) if h.trim().is_empty()) {
            file_headers.pop();
        }

        // 导入计算列:把表头补进「文件列」,模型按同表头即可命中;文件里已有则不重复
        for cc in &self.options.computed {
            if !file_headers.iter().any(|h| h.as_str() == cc.header()) {
                file_headers.push(cc.header().to_string());
            }
        }

        let map = if self.defs.is_empty() {
            HeaderMap::dynamic(file_headers)
        } else {
            resolve_headers(&file_headers, &self.defs, &self.options.header)
        };
        self.image_cols = match &self.options.image_columns {
            Some(cols) => Some(cols.clone()),
            None => {
                if self.defs.is_empty() {
                    // 动态模式:不知道哪些是图片列,全部按需读
                    None
                } else if self.defs.iter().any(|d| d.image) {
                    // 只读模型声明的图片列,避免把旁列图片也读进内存
                    Some(
                        self.defs
                            .iter()
                            .filter(|d| d.image)
                            .filter_map(|d| map.index_of(&d.header))
                            .collect(),
                    )
                } else {
                    Some(Vec::new())
                }
            }
        };

        // 列默认值兜底:导入时对空单元格填入 `ColumnDef::default`
        self.defaults_by_col = self
            .defs
            .iter()
            .filter(|d| d.is_importable())
            .filter_map(|d| d.default.as_ref().map(|v| (d, v)))
            .filter_map(|(d, v)| map.index_of(&d.header).map(|col| (col, v.clone())))
            .collect();

        self.header = Some(map);
        self.header_done = true;
    }

    // ───────────────────────────── 图片 ─────────────────────────────

    fn ensure_wps_index(&mut self) -> Result<()> {
        if self.wps_index.is_none() {
            let index = load_wps_index(&self.source)?;
            self.wps_index = Some(index);
        }
        Ok(())
    }

    fn collect_row_images(&mut self, row_index: u32) -> Result<()> {
        self.images.clear();
        if !self.options.read_images {
            self.pending_dispimg.clear();
            return Ok(());
        }

        // 1) 标准 drawing 锚点
        //    注意坐标口径:drawing 里的 row 是 0 基,行流的 row_index 是 1 基(与 Excel 界面一致)
        let anchor_row = row_index.saturating_sub(1);
        let mut found: Vec<(u16, String, Option<String>)> = Vec::new();
        if let Some(list) = self.anchors_by_row.get(&anchor_row) {
            for (col, anchor) in list {
                // 优先用写侧写入的 alt 文本(原文件名),其次退回媒体文件名
                let name = anchor
                    .name
                    .clone()
                    .or_else(|| anchor.media.rsplit('/').next().map(|s| s.to_string()));
                found.push((*col, anchor.media.clone(), name));
            }
        }
        // 2) WPS DISPIMG
        if !self.pending_dispimg.is_empty() {
            let pendings: Vec<(u16, String)> = self.pending_dispimg.drain(..).collect();
            if !pendings.is_empty() {
                self.ensure_wps_index()?;
            }
            if let Some(index) = self.wps_index.as_ref() {
                for (col, id) in pendings {
                    if found.iter().any(|(c, _, _)| *c == col) {
                        continue;
                    }
                    if let Some(media) = index.get(&id) {
                        found.push((col, media.clone(), Some(format!("DISPIMG:{id}"))));
                    }
                }
            }
        }

        // 3) 列过滤 + 按需读字节
        found.sort_by_key(|(c, _, _)| *c);
        let filter = self.image_cols.clone();
        for (col, media, name) in found {
            if let Some(cols) = &filter {
                if !cols.contains(&col) {
                    continue;
                }
            }
            match load_media(&self.source, &media) {
                Ok(img) => {
                    let header = self.header_name_of(col);
                    self.images.push(RowImage {
                        column: col,
                        header,
                        bytes: img.bytes,
                        ext: img.ext,
                        name,
                    });
                }
                Err(e) => log::warn!("读取内嵌图片失败({media}):{e}"),
            }
        }
        Ok(())
    }

    /// 文件列 → 表头名(优先用模型声明列,其次用文件表头)
    fn header_name_of(&self, col: u16) -> String {
        if let Some(header) = &self.header {
            if let Some(c) = header.columns.iter().find(|c| c.file_index == Some(col)) {
                return c.header.clone();
            }
            if let Some(h) = header.file_headers.get(col as usize) {
                if !h.is_empty() {
                    return h.clone();
                }
            }
        }
        format!("第{}列", crate::header::excel_column_name(col))
    }
}

/// 解析 `<c r="B12" t="s" s="3">` 的属性 → (列索引, 类型, 样式)
fn parse_cell_attrs(e: &BytesStart<'_>) -> (Option<u16>, CellType, u32) {
    let mut col: Option<u16> = None;
    let mut cell_type = CellType::default();
    let mut style: u32 = 0;
    for a in e.attributes().flatten() {
        match a.key.as_ref() {
            b"r" => col = col_from_ref(&String::from_utf8_lossy(&a.value)),
            b"t" => {
                cell_type = match a.value.as_ref() {
                    b"s" => CellType::SharedString,
                    b"inlineStr" => CellType::InlineString,
                    b"str" => CellType::String,
                    b"b" => CellType::Bool,
                    b"e" => CellType::Error,
                    b"d" => CellType::Date,
                    _ => CellType::Number,
                }
            }
            b"s" => {
                style = String::from_utf8_lossy(&a.value)
                    .trim()
                    .parse()
                    .unwrap_or(0)
            }
            _ => {}
        }
    }
    (col, cell_type, style)
}

/// `<row r="12">` → 12
fn row_index_of(e: &BytesStart<'_>) -> Option<u32> {
    for a in e.attributes().flatten() {
        if a.key.as_ref() == b"r" {
            return String::from_utf8_lossy(&a.value).trim().parse().ok();
        }
    }
    None
}
/// `B12` → 列索引(B → 1)
pub(crate) fn col_from_ref(r: &str) -> Option<u16> {
    let mut n: u32 = 0;
    let mut has = false;
    for c in r.chars() {
        if c.is_ascii_alphabetic() {
            has = true;
            n = n * 26 + (c.to_ascii_uppercase() as u32 - 'A' as u32 + 1);
        } else {
            break;
        }
    }
    if has && n > 0 {
        Some((n - 1) as u16)
    } else {
        None
    }
}

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

    #[test]
    fn test_col_from_ref() {
        assert_eq!(col_from_ref("A1"), Some(0));
        assert_eq!(col_from_ref("B12"), Some(1));
        assert_eq!(col_from_ref("Z1"), Some(25));
        assert_eq!(col_from_ref("AA1"), Some(26));
        assert_eq!(col_from_ref("AB100"), Some(27));
        assert_eq!(col_from_ref("1"), None);
    }
}