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
//! 读侧:流式 xlsx 读取(动态表头 / 多 sheet / 单元格图片)
//!
//! ```no_run
//! use fast_excel::read::{ExcelReader, ReadOptions, SheetSelector};
//! # fn main() -> Result<(), fast_excel::ExcelError> {
//! let reader = ExcelReader::open("products.xlsx")?;
//! println!("工作表:{:?}", reader.sheet_names());
//! let options = ReadOptions::new().header_row(0).with_images();
//! let mut stream = reader.stream(SheetSelector::First, &[], options)?;
//! while let Some(row) = stream.next_row()? {
//!     println!("第 {} 行:{}", row.row_index, row.text_of("品名"));
//! }
//! # Ok(()) }
//! ```

pub mod csv;
pub mod images;
pub mod merges;
pub mod shared_strings;
pub mod sheet_meta;
pub mod source;
pub mod stream;
pub mod styles;
pub mod workbook;

use std::path::Path;
use std::sync::Arc;

use crate::column::ColumnDef;
use crate::error::{ExcelError, Result};
use crate::header::{HeaderAnalysis, HeaderMap, HeaderOptions};
use crate::model::{DynamicRow, ExcelRow, RowData};
use crate::value::CellValue;

pub use crate::value::CellImage;
pub use csv::CsvReader;
pub use images::{
    ExtractedImages, extract_all_images, extract_embedded_images, extract_images_of_sheet,
    extract_wps_cellimages, parse_dispimg_id,
};
pub use merges::MergeRange;
pub use sheet_meta::{CfRule, Comment, ConditionalFormat, DataValidation, Hyperlink};
pub use shared_strings::SharedStrings;
pub use source::{EntryReader, ZipSource};
pub use stream::SheetStream;
pub use styles::{CellStyle, Styles};
pub use workbook::SheetInfo;

/// 导入**计算列**:文件里没有该列时,也能从本行其它列算出值
///
/// 只要模型的字段表头与 `def.header` 一致,取值时会自动命中(无需文件里真有该列)。
#[derive(Clone)]
pub struct ComputedColumn {
    /// 列定义(`header` 必须与模型声明的表头一致)
    pub def: ColumnDef,
    expr: Arc<dyn for<'a> Fn(&RowData<'a>) -> CellValue + Send + Sync>,
}

impl ComputedColumn {
    pub fn new<F>(def: ColumnDef, expr: F) -> Self
    where
        F: for<'a> Fn(&RowData<'a>) -> CellValue + Send + Sync + 'static,
    {
        Self {
            def,
            expr: Arc::new(expr),
        }
    }

    /// 用本行原始数据求值
    pub fn eval<'a>(&self, row: &RowData<'a>) -> CellValue {
        (self.expr)(row)
    }

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

impl std::fmt::Debug for ComputedColumn {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ComputedColumn")
            .field("def", &self.def)
            .finish_non_exhaustive()
    }
}

/// 导入行过滤:返回 `true` 表示保留该行(用于跳过表尾"合计 / 备注"等脚注行)
#[derive(Clone)]
pub struct RowFilter(Arc<dyn for<'a> Fn(&RowData<'a>) -> bool + Send + Sync>);

impl RowFilter {
    pub fn new<F>(f: F) -> Self
    where
        F: for<'a> Fn(&RowData<'a>) -> bool + Send + Sync + 'static,
    {
        Self(Arc::new(f))
    }

    /// 是否保留该行
    pub fn keep<'a>(&self, row: &RowData<'a>) -> bool {
        (self.0)(row)
    }
}

impl std::fmt::Debug for RowFilter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("RowFilter")
    }
}

/// 工作表选择器
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SheetSelector {
    /// 第一个工作表
    First,
    /// 按下标(0 基)
    Index(u32),
    /// 按名称(精确)
    Name(String),
    /// 按名称集合(多 sheet 导入:逐个读,顺序与传入一致)
    Names(Vec<String>),
    /// 全部工作表(多 sheet 导入)
    All,
}

impl SheetSelector {
    pub fn name(name: impl Into<String>) -> Self {
        SheetSelector::Name(name.into())
    }

    pub fn names<I, S>(names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        SheetSelector::Names(names.into_iter().map(Into::into).collect())
    }
}

/// 读取选项
#[derive(Debug, Clone)]
pub struct ReadOptions {
    /// 表头定位与匹配策略
    pub header: HeaderOptions,
    /// 最多产出多少行(预览 / 抽样用)
    pub max_rows: Option<u64>,
    /// 跳过整行空白
    pub skip_empty_rows: bool,
    /// 是否读取单元格内嵌图片
    pub read_images: bool,
    /// 只读这些文件列(0 基)的图片;`None` = 按模型声明自动推导
    pub image_columns: Option<Vec<u16>>,
    /// 是否读取合并单元格信息(`<mergeCells>`)
    ///
    /// 开启后需要**额外扫描一遍工作表 XML**(`<mergeCells>` 在 `<data>` 之后,
    /// 流式读取无法边读边拿),因此默认关闭以保证百万行吞吐;需要时用
    /// [`ReadOptions::with_merges`] 打开。
    pub read_merges: bool,
    /// 是否把合并区域左上角的值回填到区域内每个单元格(依赖 `read_merges`)
    pub fill_merged: bool,
    /// 是否读取超链接(`<hyperlinks>`,需额外扫一遍工作表 XML)
    pub read_hyperlinks: bool,
    /// 是否读取批注(`comments*.xml`)
    pub read_comments: bool,
    /// 是否读取数据验证(下拉 / 数值区间)
    pub read_validations: bool,
    /// 是否读取条件格式
    pub read_conditional_formats: bool,
    /// 导入计算列(文件里没有该列也能按表达式算出来)
    pub computed: Vec<ComputedColumn>,
    /// 行过滤:返回 `false` 的行会被跳过(表尾汇总行 / 脚注行)
    pub row_filter: Option<RowFilter>,
    /// 文本是否 trim
    pub trim_text: bool,
}

impl Default for ReadOptions {
    fn default() -> Self {
        Self {
            header: HeaderOptions::default(),
            max_rows: None,
            skip_empty_rows: true,
            read_images: false,
            image_columns: None,
            read_merges: false,
            fill_merged: true,
            read_hyperlinks: false,
            read_comments: false,
            read_validations: false,
            read_conditional_formats: false,
            computed: Vec::new(),
            row_filter: None,
            trim_text: true,
        }
    }
}

impl ReadOptions {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn header_options(mut self, header: HeaderOptions) -> Self {
        self.header = header;
        self
    }

    pub fn header_row(mut self, row_index: u32) -> Self {
        self.header.row_index = row_index;
        self
    }

    pub fn header_span(mut self, span: u32) -> Self {
        self.header.row_span = span.max(1);
        self
    }

    pub fn max_rows(mut self, rows: u64) -> Self {
        self.max_rows = Some(rows);
        self
    }

    /// 打开图片读取(模型里声明了图片列时,只读这些列)
    pub fn with_images(mut self) -> Self {
        self.read_images = true;
        self
    }

    /// 显式指定要读图的文件列
    pub fn image_columns(mut self, cols: Vec<u16>) -> Self {
        self.image_columns = Some(cols);
        self
    }

    /// 打开合并单元格读取:解析 `<mergeCells>` 并把左上角值回填到整个区域
    ///
    /// 代价是多扫一遍工作表 XML(见字段说明);不需要合并信息时保持默认即可。
    pub fn with_merges(mut self) -> Self {
        self.read_merges = true;
        self.fill_merged = true;
        self
    }

    /// 关闭合并单元格读取
    pub fn without_merges(mut self) -> Self {
        self.read_merges = false;
        self
    }

    /// 只暴露合并区域、不做值回填(会同时打开合并读取)
    pub fn merges_exposed_only(mut self) -> Self {
        self.read_merges = true;
        self.fill_merged = false;
        self
    }

    /// 打开超链接读取(`SheetStream::hyperlinks` / `ExcelReader::hyperlinks`)
    pub fn with_hyperlinks(mut self) -> Self {
        self.read_hyperlinks = true;
        self
    }

    /// 打开批注读取(`SheetStream::comments` / `ExcelReader::comments`)
    pub fn with_comments(mut self) -> Self {
        self.read_comments = true;
        self
    }

    /// 打开数据验证读取(下拉 / 数值区间)
    pub fn with_validations(mut self) -> Self {
        self.read_validations = true;
        self
    }

    /// 打开条件格式读取
    pub fn with_conditional_formats(mut self) -> Self {
        self.read_conditional_formats = true;
        self
    }

    /// 追加一个**导入计算列**:文件里没有该列时,也能从本行其它列算出值
    ///
    /// 模型只需按同一个表头声明字段即可取到:
    ///
    /// ```ignore
    /// use fast_excel::{CellValue, ColumnDef, ReadOptions};
    /// let options = ReadOptions::new().computed(ColumnDef::new("全名"), |row| {
    ///     let full = format!("{}{}", row.text_of("姓"), row.text_of("名"));
    ///     CellValue::Text(full)
    /// });
    /// ```
    pub fn computed<F>(mut self, def: ColumnDef, expr: F) -> Self
    where
        F: for<'a> Fn(&RowData<'a>) -> CellValue + Send + Sync + 'static,
    {
        self.computed.push(ComputedColumn::new(def, expr));
        self
    }

    /// 设置**行过滤**:返回 `false` 的行直接跳过(表尾"合计 / 备注"等脚注行)
    ///
    /// ```ignore
    /// use fast_excel::ReadOptions;
    /// let options = ReadOptions::new().row_filter(|row| {
    ///     // 丢弃第一列为「合计」的汇总行
    ///     row.text_of("品名") != "合计"
    /// });
    /// ```
    pub fn row_filter<F>(mut self, f: F) -> Self
    where
        F: for<'a> Fn(&RowData<'a>) -> bool + Send + Sync + 'static,
    {
        self.row_filter = Some(RowFilter::new(f));
        self
    }

    pub fn skip_empty_rows(mut self, skip: bool) -> Self {
        self.skip_empty_rows = skip;
        self
    }

    pub fn trim_text(mut self, trim: bool) -> Self {
        self.trim_text = trim;
        self
    }
}

/// xlsx 读取器(可同时解析多个工作表;每次 `stream` 都是独立的流式读取)
pub struct ExcelReader {
    source: ZipSource,
    sheets: Vec<SheetInfo>,
    date_1904: bool,
    shared: Arc<SharedStrings>,
    styles: Arc<Styles>,
}

impl ExcelReader {
    /// 打开磁盘文件(推荐:不把整个文件读进内存)
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::from_source(ZipSource::open(path)?)
    }

    /// 以内存字节打开(HTTP 上传的 multipart 场景)
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
        Self::from_source(ZipSource::from_bytes(bytes))
    }

    /// 复用已有数据源
    pub fn from_source(source: ZipSource) -> Result<Self> {
        let (sheets, date_1904) = workbook::load_sheets(&source)?;
        // 共享字符串与样式表体积小、且需要随机访问,策略是整体加载一次
        let shared = match source.entry_reader("xl/sharedStrings.xml") {
            Ok(reader) => SharedStrings::parse(std::io::BufReader::new(reader))?,
            Err(_) => SharedStrings::empty(),
        };
        let styles = match source.entry_reader("xl/styles.xml") {
            Ok(reader) => Styles::parse(std::io::BufReader::new(reader))?,
            Err(_) => Styles::empty(),
        };
        Ok(Self {
            source,
            sheets,
            date_1904,
            shared: Arc::new(shared),
            styles: Arc::new(styles),
        })
    }

    pub fn source(&self) -> &ZipSource {
        &self.source
    }

    pub fn sheets(&self) -> &[SheetInfo] {
        &self.sheets
    }

    pub fn sheet_names(&self) -> Vec<String> {
        self.sheets.iter().map(|s| s.name.clone()).collect()
    }

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

    pub fn shared_strings(&self) -> &SharedStrings {
        &self.shared
    }

    /// 单元格样式表(字体颜色 / 底色 / 加粗 / 斜体)
    pub fn styles(&self) -> &Styles {
        &self.styles
    }

    /// 解析选择器 → 工作表列表
    pub fn select(&self, selector: &SheetSelector) -> Result<Vec<&SheetInfo>> {
        let found: Vec<&SheetInfo> = match selector {
            SheetSelector::First => self.sheets.first().into_iter().collect(),
            SheetSelector::Index(i) => self.sheets.iter().filter(|s| s.index == *i).collect(),
            SheetSelector::Name(name) => self.sheets.iter().filter(|s| &s.name == name).collect(),
            SheetSelector::Names(names) => names
                .iter()
                .map(|n| {
                    self.sheets
                        .iter()
                        .find(|s| &s.name == n)
                        .ok_or_else(|| ExcelError::SheetNotFound(n.clone()))
                })
                .collect::<Result<Vec<_>>>()?,
            SheetSelector::All => self.sheets.iter().collect(),
        };
        if found.is_empty() {
            return Err(ExcelError::SheetNotFound(match selector {
                SheetSelector::First => "第一个工作表".to_string(),
                SheetSelector::Index(i) => format!("下标 {i}"),
                SheetSelector::Name(n) => n.clone(),
                SheetSelector::Names(n) => n.join("、"),
                SheetSelector::All => "任意工作表".to_string(),
            }));
        }
        Ok(found)
    }

    /// 打开一个工作表的行流(单个 sheet)
    pub fn stream(
        &self,
        selector: SheetSelector,
        defs: &[ColumnDef],
        options: ReadOptions,
    ) -> Result<SheetStream> {
        let sheets = self.select(&selector)?;
        let sheet = sheets[0];
        self.stream_sheet(sheet, defs, options)
    }

    /// 打开指定工作表的行流
    pub fn stream_sheet(
        &self,
        sheet: &SheetInfo,
        defs: &[ColumnDef],
        options: ReadOptions,
    ) -> Result<SheetStream> {
        SheetStream::new(
            self.source.clone(),
            &sheet.path,
            &sheet.name,
            self.date_1904,
            self.shared.clone(),
            self.styles.clone(),
            defs,
            options,
        )
    }

    /// 只做表头自适应分析(不消费数据,供"导入预检"接口使用)
    pub fn analyze_header(
        &self,
        selector: &SheetSelector,
        defs: &[ColumnDef],
        options: ReadOptions,
    ) -> Result<HeaderAnalysis> {
        let sheets = self.select(selector)?;
        let mut stream = self.stream_sheet(sheets[0], defs, options)?;
        // 触发一次解析即可确保表头已构建(空文件也会在 EOF 处构建)
        let _ = stream.next_row()?;
        Ok(stream
            .header_analysis()
            .unwrap_or_else(|| HeaderMap::dynamic(Vec::new()).analysis()))
    }

    /// 读取所有工作表的表头分析(多 sheet 预检)
    pub fn analyze_all_headers(
        &self,
        defs: &[ColumnDef],
        options: ReadOptions,
    ) -> Result<Vec<(String, HeaderAnalysis)>> {
        let mut out = Vec::with_capacity(self.sheets.len());
        for sheet in &self.sheets {
            let mut stream = self.stream_sheet(sheet, defs, options.clone())?;
            let _ = stream.next_row()?;
            let analysis = stream
                .header_analysis()
                .unwrap_or_else(|| HeaderMap::dynamic(Vec::new()).analysis());
            out.push((sheet.name.clone(), analysis));
        }
        Ok(out)
    }

    /// 读取指定(可多个)工作表的合并区域(只查询,不做值回填)
    ///
    /// 需要值回填时改用 [`ReadOptions::with_merges`] 走 [`ExcelReader::stream`]。
    pub fn merge_ranges(&self, selector: &SheetSelector) -> Result<Vec<MergeRange>> {
        let mut out = Vec::new();
        for sheet in self.select(selector)? {
            let wants = sheet_meta::MetaWants {
                merges: true,
                ..Default::default()
            };
            out.extend(sheet_meta::load_sheet_meta(&self.source, &sheet.path, wants)?.merges);
        }
        Ok(out)
    }

    /// 读取指定(可多个)工作表的超链接
    pub fn hyperlinks(&self, selector: &SheetSelector) -> Result<Vec<Hyperlink>> {
        let mut out = Vec::new();
        for sheet in self.select(selector)? {
            let wants = sheet_meta::MetaWants {
                hyperlinks: true,
                ..Default::default()
            };
            out.extend(sheet_meta::load_sheet_meta(&self.source, &sheet.path, wants)?.hyperlinks);
        }
        Ok(out)
    }

    /// 读取指定(可多个)工作表的数据验证(下拉 / 数值区间)
    pub fn validations(&self, selector: &SheetSelector) -> Result<Vec<sheet_meta::DataValidation>> {
        let mut out = Vec::new();
        for sheet in self.select(selector)? {
            let wants = sheet_meta::MetaWants {
                validations: true,
                ..Default::default()
            };
            out.extend(sheet_meta::load_sheet_meta(&self.source, &sheet.path, wants)?.validations);
        }
        Ok(out)
    }

    /// 读取指定(可多个)工作表的条件格式
    pub fn conditional_formats(
        &self,
        selector: &SheetSelector,
    ) -> Result<Vec<sheet_meta::ConditionalFormat>> {
        let mut out = Vec::new();
        for sheet in self.select(selector)? {
            let wants = sheet_meta::MetaWants {
                conditional_formats: true,
                ..Default::default()
            };
            out.extend(
                sheet_meta::load_sheet_meta(&self.source, &sheet.path, wants)?
                    .conditional_formats,
            );
        }
        Ok(out)
    }

    /// 动态读取整表(**无实体**):返回 `(表头, 每行 表头→值)`
    ///
    /// 等价于 `stream(selector, &[], options)` + [`DynamicRow::from_row`],
    /// 用于「没有实体、前端直接拿表头与内容」的场景。
    pub fn read_dynamic(
        &self,
        selector: &SheetSelector,
        options: ReadOptions,
    ) -> Result<(Vec<String>, Vec<DynamicRow>)> {
        let sheets = self.select(selector)?;
        let mut stream = self.stream_sheet(sheets[0], &[], options)?;
        let mut rows = Vec::new();
        while let Some(row) = stream.next_row()? {
            let dynamic = DynamicRow::from_row(&row)
                .map_err(|e| ExcelError::Other(format!("动态行解析失败:{}", e.len())))?;
            rows.push(dynamic);
        }
        let headers = stream
            .header()
            .map(|h| h.file_headers.clone())
            .unwrap_or_default();
        Ok((headers, rows))
    }

    /// 读取指定(可多个)工作表的批注(经典批注 `comments*.xml` + 线程批注 `threadedComments`)
    ///
    /// 线程批注只收根批注(带 `ref` 的条目),回复暂不展开。
    pub fn comments(&self, selector: &SheetSelector) -> Result<Vec<Comment>> {
        let mut out = Vec::new();
        for sheet in self.select(selector)? {
            out.extend(sheet_meta::load_comments(&self.source, &sheet.path)?);
        }
        Ok(out)
    }
}