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
//! 流式 Excel 写出(`rust_xlsxwriter`,常量内存模式)
//!
//! - 打开 `constant_memory` 后,工作表数据边写边落临时文件,**内存与行数无关**,
//!   百万行导出的内存占用是一条行缓冲的量级;
//! - 代价:只能按行号递增写入(`rust_xlsxwriter` 会忽略对已 flush 行的写入),
//!   因此本模块用 `row_cursor` 强制顺序推进,避免"静默丢行"。

use std::collections::HashMap;
use std::path::Path;

use rust_xlsxwriter::{
    Color, ExcelDateTime, Format, FormatAlign, FormatBorder, Image, Workbook, Worksheet,
};

use crate::column::{ColumnDef, ColumnKind};
use crate::error::{ExcelError, Result};
use crate::model::ExcelRow;
use crate::value::{CellImage, CellValue};
use crate::write::{SheetOptions, WriteOptions, default_column_width};

/// Excel 写出器(可包含多个工作表)
pub struct ExcelWriter {
    workbook: Workbook,
    sheet_count: u32,
}

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

impl ExcelWriter {
    pub fn new() -> Self {
        Self {
            workbook: Workbook::new(),
            sheet_count: 0,
        }
    }

    pub fn sheet_count(&self) -> u32 {
        self.sheet_count
    }

    /// 新增一个工作表(列宽 / 表头 / 冻结窗格在写入前配置好)
    pub fn add_sheet(&mut self, options: &SheetOptions) -> Result<SheetWriter<'_>> {
        let name = if options.name.is_empty() {
            format!("Sheet{}", self.sheet_count + 1)
        } else {
            options.name.clone()
        };
        let ws = if options.write.constant_memory {
            self.workbook.add_worksheet_with_constant_memory()
        } else {
            self.workbook.add_worksheet()
        };
        self.sheet_count += 1;
        ws.set_name(&name)?;
        let mut writer = SheetWriter::new(ws, options.clone());
        writer.prepare()?;
        Ok(writer)
    }

    /// 保存到文件;返回文件字节数(大文件不会进内存)
    pub fn save<P: AsRef<Path>>(&mut self, path: P) -> Result<u64> {
        let path = path.as_ref();
        self.workbook.save(path)?;
        Ok(std::fs::metadata(path).map(|m| m.len()).unwrap_or(0))
    }

    /// 保存到内存缓冲(HTTP 响应直接下载;小数据量场景)
    pub fn save_to_buffer(&mut self) -> Result<Vec<u8>> {
        Ok(self.workbook.save_to_buffer()?)
    }

    /// 逃生口:需要合并单元格、批注、条件格式等高级能力时直接用底层工作簿
    pub fn workbook(&mut self) -> &mut Workbook {
        &mut self.workbook
    }
}

/// 单个工作表的写出句柄
pub struct SheetWriter<'a> {
    ws: &'a mut Worksheet,
    options: SheetOptions,
    /// 下一个可写行(0 基)
    row_cursor: u32,
    /// 已写入的最大列 / 行(autofilter 用)
    last_col: u16,
    /// 表头所在行(0 基);自动筛选从这里开始,避免把标题行框进去
    header_row: Option<u32>,
    /// 写入的列数(用于表头与筛选范围)
    col_count: u16,
    formats: HashMap<String, Format>,
}

impl<'a> SheetWriter<'a> {
    fn new(ws: &'a mut Worksheet, options: SheetOptions) -> Self {
        let col_count = options.effective_columns().len() as u16;
        Self {
            ws,
            options,
            row_cursor: 0,
            last_col: col_count.saturating_sub(1),
            header_row: None,
            col_count,
            formats: HashMap::new(),
        }
    }

    /// 列宽 + 冻结窗格
    fn prepare(&mut self) -> Result<()> {
        let columns = self.options.effective_columns();
        if !columns.is_empty() {
            for (i, col) in columns.iter().enumerate() {
                let width = col.width.unwrap_or_else(|| default_column_width(col));
                self.ws.set_column_width(i as u16, width)?;
            }
            if self.options.write.freeze_header {
                self.ws.set_freeze_panes(1, 0)?;
            }
        }
        Ok(())
    }

    pub fn options(&self) -> &SheetOptions {
        &self.options
    }

    /// 当前待写行号(0 基)
    pub fn current_row(&self) -> u32 {
        self.row_cursor
    }

    /// 写表头(按列定义的 `header`)
    pub fn write_headers(&mut self) -> Result<()> {
        self.write_headers_with(&self.options.effective_columns())
    }

    /// 写表头(自定义列定义)
    pub fn write_headers_with(&mut self, columns: &[ColumnDef]) -> Result<()> {
        let row = self.row_cursor;
        let header_format = self.header_format();
        for (i, col) in columns.iter().enumerate() {
            if self.options.write.header_style {
                let fmt = header_format.clone();
                self.ws
                    .write_string_with_format(row, i as u16, &col.header, &fmt)?;
            } else {
                self.ws.write_string(row, i as u16, &col.header)?;
            }
        }
        if columns.len() as u16 > self.col_count {
            self.col_count = columns.len() as u16;
        }
        self.last_col = self.last_col.max(columns.len().saturating_sub(1) as u16);
        self.header_row = Some(row);
        self.row_cursor += 1;
        Ok(())
    }

    /// 写表头(必填列红字标出,导入模板场景)
    pub fn write_headers_marked(&mut self, columns: &[ColumnDef]) -> Result<()> {
        let row = self.row_cursor;
        let header_format = self.header_format();
        let required_format = self.required_header_format();
        for (i, col) in columns.iter().enumerate() {
            let fmt = if col.required {
                &required_format
            } else {
                &header_format
            };
            self.ws
                .write_string_with_format(row, i as u16, &col.header, fmt)?;
        }
        self.last_col = self.last_col.max(columns.len().saturating_sub(1) as u16);
        self.col_count = self.col_count.max(columns.len() as u16);
        self.header_row = Some(row);
        self.row_cursor += 1;
        Ok(())
    }

    /// 写一条**合并表头行**(多级表头):每段 `(标题, 跨列数)` 横向合并,写完推进一行
    pub fn write_merged_header_row(&mut self, groups: &[(String, u16)]) -> Result<()> {
        let row = self.row_cursor;
        let fmt = self.header_format();
        let mut col: u16 = 0;
        let mut max_col = self.col_count.saturating_sub(1);
        for (title, span) in groups {
            let span = (*span).max(1);
            let last = col.saturating_add(span - 1);
            if last > col {
                self.ws.merge_range(row, col, row, last, title, &fmt)?;
            } else {
                self.ws.write_string_with_format(row, col, title, &fmt)?;
            }
            max_col = max_col.max(last);
            col = last.saturating_add(1);
        }
        self.last_col = self.last_col.max(max_col);
        self.col_count = self.col_count.max(col);
        self.row_cursor += 1;
        Ok(())
    }

    fn required_header_format(&mut self) -> Format {
        let key = "header:required".to_string();
        if let Some(f) = self.formats.get(&key) {
            return f.clone();
        }
        let fmt = Format::new()
            .set_bold()
            .set_align(FormatAlign::Center)
            .set_border(FormatBorder::Thin)
            .set_background_color(Color::RGB(0xFD_E3_E3))
            .set_font_color(Color::Red);
        self.formats.insert(key, fmt.clone());
        fmt
    }

    /// 给某一列挂下拉数据验证(模板场景:`dropdown` 列)
    pub fn add_dropdown(
        &mut self,
        col: u16,
        options: &[String],
        first_row: u32,
        last_row: u32,
        prompt: Option<&str>,
    ) -> Result<()> {
        if options.is_empty() {
            return Ok(());
        }
        let list: Vec<&str> = options.iter().map(|s| s.as_str()).collect();
        let mut dv = rust_xlsxwriter::DataValidation::new().allow_list_strings(&list)?;
        if let Some(p) = prompt {
            dv = dv.set_input_message(p)?;
        }
        self.ws
            .add_data_validation(first_row, col, last_row, col, &dv)?;
        Ok(())
    }
    /// 写一行原始值(顺序与列定义对齐)
    ///
    /// 行高在写单元格**之前**设置:带图行按 `image_row_height` 撑高,
    /// `insert_image_fit_to_cell_centered` 依赖行高计算缩放比例。
    pub fn write_row(&mut self, values: &[CellValue]) -> Result<()> {
        // 应用列表达式(改写 -> 追加计算列)
        let values = self.options.eval_row(values.to_vec());
        let row = self.row_cursor;
        let has_image = values
            .iter()
            .any(|v| matches!(v, CellValue::Image(img) if !img.bytes.is_empty()));
        if has_image {
            self.ws
                .set_row_height(row, self.options.write.image_row_height)?;
        } else if let Some(h) = self.options.write.default_row_height {
            self.ws.set_row_height(row, h)?;
        }
        let columns = self.options.effective_columns();
        for (i, value) in values.iter().enumerate() {
            let def = columns.get(i);
            self.write_value(row, i as u16, value, def)?;
        }
        self.row_cursor += 1;
        self.last_col = self.last_col.max(values.len().saturating_sub(1) as u16);
        Ok(())
    }

    /// 写业务模型一行
    pub fn write_model<T: ExcelRow>(&mut self, model: &T) -> Result<()> {
        self.write_row(&model.to_row())
    }

    /// 批量写业务模型(内部仍是逐行 => 常量内存)
    pub fn write_models<T: ExcelRow>(&mut self, models: &[T]) -> Result<()> {
        for m in models {
            self.write_model(m)?;
        }
        Ok(())
    }

    /// 写任意文本行(如"填报说明")
    pub fn write_text_row<I, S>(&mut self, texts: I) -> Result<()>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let row = self.row_cursor;
        for (i, t) in texts.into_iter().enumerate() {
            self.ws.write_string(row, i as u16, t.as_ref())?;
        }
        self.row_cursor += 1;
        Ok(())
    }

    /// 空一行
    pub fn skip_rows(&mut self, n: u32) {
        self.row_cursor += n;
    }

    /// 写一行,并在该行内做**横向合并**(内容合并 / 合计行 / 备注行)
    ///
    /// `merges` 为 `(起始列, 结束列)`(0 基,含两端),必须落在同一行;合并区间取
    /// `values` 里起始列的值作为锚点值(缺省为空)。区间外的列按普通单元格写出。
    ///
    /// ```ignore
    /// // 第 1 列普通、第 2~3 列合并为「合计」、第 4 列普通
    /// ws.write_row_with_merges(
    ///     &[CellValue::Text("小计".into()), CellValue::Text("合计 1,000".into()), CellValue::Empty, CellValue::Number(1000.0)],
    ///     &[(1, 2)],
    /// )?;
    /// ```
    pub fn write_row_with_merges(
        &mut self,
        values: &[CellValue],
        merges: &[(u16, u16)],
    ) -> Result<()> {
        let values = self.options.eval_row(values.to_vec());
        let row = self.row_cursor;
        let has_image = values
            .iter()
            .any(|v| matches!(v, CellValue::Image(img) if !img.bytes.is_empty()));
        if has_image {
            self.ws
                .set_row_height(row, self.options.write.image_row_height)?;
        } else if let Some(h) = self.options.write.default_row_height {
            self.ws.set_row_height(row, h)?;
        }

        let mut spans: Vec<(u16, u16)> = merges.iter().map(|(a, b)| (*a.min(b), *a.max(b))).collect();
        spans.sort_by_key(|(a, _)| *a);
        for (c1, c2) in &spans {
            if c1 == c2 {
                return Err(ExcelError::Other(
                    "横向合并区间至少需要 2 列".to_string(),
                ));
            }
        }

        let len = values.len() as u16;
        let max_col = spans
            .iter()
            .map(|(_, c2)| c2.saturating_add(1))
            .chain(std::iter::once(len))
            .max()
            .unwrap_or(len);

        let columns = self.options.effective_columns();
        let fmt = Format::new().set_align(FormatAlign::Center);
        let mut col = 0u16;
        while col < max_col {
            if let Some(&(_, c2)) = spans.iter().find(|(c1, _)| *c1 == col) {
                let text = values
                    .get(col as usize)
                    .map(|v| v.to_text())
                    .unwrap_or_default();
                self.ws.merge_range(row, col, row, c2, &text, &fmt)?;
                self.last_col = self.last_col.max(c2);
                col = c2.saturating_add(1);
            } else {
                if col < len {
                    let def = columns.get(col as usize);
                    self.write_value(row, col, &values[col as usize], def)?;
                }
                col += 1;
            }
        }

        self.row_cursor += 1;
        self.last_col = self.last_col.max(max_col.saturating_sub(1));
        self.col_count = self.col_count.max(max_col);
        Ok(())
    }

    /// 写一行,并把指定的列写成**超链接**
    ///
    /// `links` 为 `(列, URL, 显示文本)`(0 基);显示文本为 `None` 时显示 URL 本身。
    /// 其余列照常写 `values`(同样会先应用列表达式)。
    ///
    /// ```ignore
    /// ws.write_row_with_links(
    ///     &[CellValue::Text("官网".into()), CellValue::Empty],
    ///     &[(1, "https://example.com".to_string(), Some("打开".to_string()))],
    /// )?;
    /// ```
    pub fn write_row_with_links(
        &mut self,
        values: &[CellValue],
        links: &[(u16, String, Option<String>)],
    ) -> Result<()> {
        let values = self.options.eval_row(values.to_vec());
        let row = self.row_cursor;
        let has_image = values
            .iter()
            .any(|v| matches!(v, CellValue::Image(img) if !img.bytes.is_empty()));
        if has_image {
            self.ws
                .set_row_height(row, self.options.write.image_row_height)?;
        } else if let Some(h) = self.options.write.default_row_height {
            self.ws.set_row_height(row, h)?;
        }

        let len = values.len() as u16;
        let max_col = links
            .iter()
            .map(|(c, _, _)| c.saturating_add(1))
            .chain(std::iter::once(len))
            .max()
            .unwrap_or(len);

        let columns = self.options.effective_columns();
        for col in 0..max_col {
            match links.iter().find(|(c, _, _)| *c == col) {
                Some((_, url, text)) => match text {
                    Some(t) => {
                        self.ws.write_url_with_text(row, col, url.as_str(), t.as_str())?;
                    }
                    None => {
                        self.ws.write_url(row, col, url.as_str())?;
                    }
                },
                None => {
                    if col < len {
                        let def = columns.get(col as usize);
                        self.write_value(row, col, &values[col as usize], def)?;
                    }
                }
            }
        }

        self.row_cursor += 1;
        self.last_col = self.last_col.max(max_col.saturating_sub(1));
        self.col_count = self.col_count.max(max_col);
        Ok(())
    }

    /// 写一个合并单元格(普通样式:居中),左上角为 `text`
    ///
    /// 行 / 列均为 0 基,`(first_row, first_col)` 是左上角、`(last_row, last_col)` 是右下角。
    /// 常量内存模式下只能顺序写:`first_row` 不得早于当前行游标;本方法会把游标推进到
    /// `last_row + 1`。合并区域覆盖的行请不要再单独 `write_row`。
    ///
    /// 列表头类的大标题 / 多级表头请用 [`SheetWriter::merge_header`]。
    pub fn merge_range(
        &mut self,
        first_row: u32,
        first_col: u16,
        last_row: u32,
        last_col: u16,
        text: impl AsRef<str>,
    ) -> Result<()> {
        let fmt = Format::new().set_align(FormatAlign::Center);
        self.merge_range_with_format(
            first_row,
            first_col,
            last_row,
            last_col,
            text.as_ref(),
            &fmt,
        )
    }

    /// 写一个合并单元格(表头样式:加粗 + 底色 + 居中),用于大标题 / 多级表头
    pub fn merge_header(
        &mut self,
        first_row: u32,
        first_col: u16,
        last_row: u32,
        last_col: u16,
        text: impl AsRef<str>,
    ) -> Result<()> {
        let fmt = self.header_format();
        self.merge_range_with_format(
            first_row,
            first_col,
            last_row,
            last_col,
            text.as_ref(),
            &fmt,
        )
    }

    fn merge_range_with_format(
        &mut self,
        first_row: u32,
        first_col: u16,
        last_row: u32,
        last_col: u16,
        text: &str,
        format: &Format,
    ) -> Result<()> {
        if first_row > last_row || first_col > last_col {
            return Err(ExcelError::Other(format!(
                "合并区域行列顺序错误:({first_row},{first_col})-({last_row},{last_col})"
            )));
        }
        if first_row == last_row && first_col == last_col {
            return Err(ExcelError::Other(
                "合并区域至少需要 2 个单元格".to_string(),
            ));
        }
        if first_row < self.row_cursor {
            return Err(ExcelError::Other(format!(
                "常量内存模式只能顺序写:合并起始行 {first_row} 早于当前行游标 {}",
                self.row_cursor
            )));
        }
        self.ws
            .merge_range(first_row, first_col, last_row, last_col, text, format)?;
        self.row_cursor = self.row_cursor.max(last_row.saturating_add(1));
        self.last_col = self.last_col.max(last_col);
        self.col_count = self.col_count.max(last_col.saturating_add(1));
        Ok(())
    }

    /// 结束本表:应用自动筛选(必须写完数据后调用)
    pub fn finish(&mut self) -> Result<()> {
        // 从表头行开始筛选,避免把标题行 / 合并大标题框进来
        let start = self.header_row.unwrap_or(0);
        if self.options.write.auto_filter
            && self.options.write.header_style
            && self.row_cursor > start + 1
            && self.col_count > 0
        {
            self.ws
                .autofilter(start, 0, self.row_cursor - 1, self.last_col)?;
        }
        Ok(())
    }

    /// 逃生口:直接操作底层工作表(批注 / 合并 / 条件格式)
    pub fn worksheet(&mut self) -> &mut Worksheet {
        self.ws
    }

    // ─────────────────────────── 单元格写入 ───────────────────────────

    fn write_value(
        &mut self,
        row: u32,
        col: u16,
        value: &CellValue,
        def: Option<&ColumnDef>,
    ) -> Result<()> {
        match value {
            CellValue::Empty => {}
            CellValue::Text(s) => {
                if s.is_empty() {
                    return Ok(());
                }
                match self.cell_format_key(def, true) {
                    Some(key) => {
                        let fmt = self.format_of(&key, def, true);
                        self.ws.write_string_with_format(row, col, s, &fmt)?;
                    }
                    None => {
                        self.ws.write_string(row, col, s)?;
                    }
                }
            }
            CellValue::Number(n) => match self.cell_format_key(def, false) {
                Some(key) => {
                    let fmt = self.format_of(&key, def, false);
                    self.ws.write_number_with_format(row, col, *n, &fmt)?;
                }
                None => {
                    self.ws.write_number(row, col, *n)?;
                }
            },
            CellValue::Bool(b) => {
                self.ws.write_boolean(row, col, *b)?;
            }
            CellValue::Date(d) => {
                let fmt = self.date_format(def, false);
                let dt = ExcelDateTime::from_ymd(
                    chrono::Datelike::year(d) as u16,
                    chrono::Datelike::month(d) as u8,
                    chrono::Datelike::day(d) as u8,
                )?;
                self.ws.write_datetime_with_format(row, col, &dt, &fmt)?;
            }
            CellValue::DateTime(raw) => {
                let fmt = self.date_format(def, true);
                let dt = ExcelDateTime::from_ymd(
                    chrono::Datelike::year(raw) as u16,
                    chrono::Datelike::month(raw) as u8,
                    chrono::Datelike::day(raw) as u8,
                )?
                .and_hms(
                    chrono::Timelike::hour(raw) as u16,
                    chrono::Timelike::minute(raw) as u8,
                    chrono::Timelike::second(raw) as f64,
                )?;
                self.ws.write_datetime_with_format(row, col, &dt, &fmt)?;
            }
            CellValue::Formula(f) => {
                self.ws.write_formula(row, col, f.as_str())?;
            }
            CellValue::Error(e) => {
                self.ws.write_string(row, col, e)?;
            }
            CellValue::Image(img) => {
                self.write_image(row, col, img)?;
            }
        }
        Ok(())
    }

    fn write_image(&mut self, row: u32, col: u16, img: &CellImage) -> Result<()> {
        if img.bytes.is_empty() {
            return Ok(());
        }
        let mut image = Image::new_from_buffer(&img.bytes)?;
        if let Some(name) = &img.name {
            image = image.set_alt_text(name.clone());
        }
        if self.options.write.cell_image {
            // Excel「置于单元格内」图片:随单元格排序/筛选,但常量内存模式下
            // rust_xlsxwriter 0.99 会 panic(内部全局图片索引此时还没准备好)
            self.ws.embed_image(row, col, &image)?;
        } else {
            // 标准锚点图片:按行高自适应缩放 + 居中,常量内存模式下可用
            self.ws
                .insert_image_fit_to_cell_centered(row, col, &image)?;
        }
        Ok(())
    }

    // ─────────────────────────── 格式缓存 ───────────────────────────

    fn header_format(&mut self) -> Format {
        let key = "header".to_string();
        if let Some(f) = self.formats.get(&key) {
            return f.clone();
        }
        let fmt = Format::new()
            .set_bold()
            .set_align(FormatAlign::Center)
            .set_border(FormatBorder::Thin)
            .set_background_color(Color::RGB(0xD9_E1_F2))
            .set_font_color(Color::RGB(0x1F_23_29));
        self.formats.insert(key, fmt.clone());
        fmt
    }

    /// 该列是否需要显式格式;返回缓存 key
    fn cell_format_key(&self, def: Option<&ColumnDef>, text: bool) -> Option<String> {
        let def = def?;
        if text && def.text_format {
            return Some("text:@".to_string());
        }
        if !text {
            if let Some(f) = &def.format {
                return Some(format!("num:{f}"));
            }
            if def.text_format {
                return Some("text:@".to_string());
            }
        }
        None
    }

    fn format_of(&mut self, key: &str, def: Option<&ColumnDef>, text: bool) -> Format {
        if let Some(f) = self.formats.get(key) {
            return f.clone();
        }
        let code = match def.and_then(|d| d.format.clone()) {
            Some(code) => code,
            None => {
                if matches!(def.map(|d| d.kind), Some(ColumnKind::Integer)) {
                    "0".to_string()
                } else if matches!(
                    def.map(|d| d.kind),
                    Some(ColumnKind::Decimal) | Some(ColumnKind::Number)
                ) {
                    "0.00".to_string()
                } else if text {
                    "@".to_string()
                } else {
                    "General".to_string()
                }
            }
        };
        let fmt = Format::new().set_num_format(code);
        self.formats.insert(key.to_string(), fmt.clone());
        fmt
    }

    fn date_format(&mut self, def: Option<&ColumnDef>, with_time: bool) -> Format {
        let default = if with_time {
            self.options.write.datetime_format.clone()
        } else {
            self.options.write.date_format.clone()
        };
        let code = def.and_then(|d| d.format.clone()).unwrap_or(default);
        let key = format!("date:{code}");
        if let Some(f) = self.formats.get(&key) {
            return f.clone();
        }
        let fmt = Format::new().set_num_format(code);
        self.formats.insert(key, fmt.clone());
        fmt
    }
}

/// 便捷:一步导出单表(表头 + 行 + 收尾)
pub fn export_single_sheet<T: ExcelRow>(
    path: impl AsRef<Path>,
    sheet: &SheetOptions,
    rows: &[T],
) -> Result<u64> {
    let mut writer = ExcelWriter::new();
    {
        let mut ws = writer.add_sheet(sheet)?;
        ws.write_headers()?;
        ws.write_models(rows)?;
        ws.finish()?;
    }
    writer.save(path)
}

/// 便捷:把写出选项转成 rust_xlsxwriter 的通用行高(模板用)
pub fn default_write_options() -> WriteOptions {
    WriteOptions::default()
}