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
//! CSV 导入:复用与 xlsx 同一套表头适配([`resolve_headers`])与模型映射([`ExcelRow::from_row`])
//!
//! 支持 RFC4180 的引号与转义(`""`)、跨行引号字段、CRLF / LF、UTF-8 BOM。
//! 列定义(表头 / 别名 / 必填 / 默认值)、导入计算列与行过滤与 xlsx 链路一致。
//!
//! 与 xlsx 的差异:CSV 没有合并单元格 / 内嵌图片 / 样式,这几项在 CSV 链路上为空。

use std::fs::File;
use std::io::{BufRead, BufReader, Cursor};
use std::path::Path;

use crate::error::{ExcelError, Result};
use crate::header::{HeaderMap, resolve_headers};
use crate::import::report::{ImportReport, RowError, SheetHeader};
use crate::model::{ExcelRow, RowData};
use crate::read::ReadOptions;
use crate::read::styles::Styles;
use crate::value::{Cell, CellValue};

/// CSV 读取器(流式逐条记录)
pub struct CsvReader<R: BufRead> {
    reader: R,
    /// 已读物理行数(1 基,用作行号)
    line_no: u32,
    eof: bool,
    /// 是否还在文件开头(用于剥离 BOM)
    first: bool,
}

impl CsvReader<BufReader<File>> {
    /// 打开磁盘文件
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let file = File::open(path)?;
        Ok(Self::new(BufReader::with_capacity(128 * 1024, file)))
    }
}

impl CsvReader<Cursor<Vec<u8>>> {
    /// 以内存字节打开(HTTP 上传场景)
    pub fn from_bytes(bytes: Vec<u8>) -> Self {
        Self::new(Cursor::new(bytes))
    }
}

impl<R: BufRead> CsvReader<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            line_no: 0,
            eof: false,
            first: true,
        }
    }

    /// 读下一条记录;返回 `(字段, 起始物理行号)`
    pub fn next_record(&mut self) -> Result<Option<(Vec<String>, u32)>> {
        if self.eof {
            return Ok(None);
        }
        let start_line = self.line_no + 1;
        let mut raw: Vec<u8> = Vec::new();
        loop {
            let mut line: Vec<u8> = Vec::new();
            let n = self.reader.read_until(b'\n', &mut line)?;
            if n == 0 {
                self.eof = true;
                if raw.is_empty() {
                    return Ok(None);
                }
                break;
            }
            self.line_no += 1;
            if self.first {
                self.first = false;
                // 剥离 UTF-8 BOM
                if line.starts_with(&[0xEF, 0xBB, 0xBF]) {
                    line.drain(0..3);
                }
            }
            raw.extend_from_slice(&line);
            if !has_unclosed_quote(&raw) {
                break;
            }
        }
        Ok(Some((split_fields(&raw), start_line)))
    }

    /// 按模型列定义逐行解析;`on_row` 返回 `Err` 视为该行错误
    ///
    /// 落库语义与 [`crate::ImportRunner::for_each_row`] 一致:逐行回调、不攒批。
    pub fn read_into<T, F>(&mut self, options: &ReadOptions, mut on_row: F) -> Result<ImportReport>
    where
        T: ExcelRow,
        F: FnMut(&RowData<'_>, T) -> std::result::Result<(), Vec<String>>,
    {
        let started = std::time::Instant::now();
        let styles = Styles::empty();
        let columns = T::columns();

        // ── 表头 ──
        let span = options.header.row_span.max(1) as usize;
        let header_start = options.header.row_index as usize;
        let mut idx = 0usize;
        let mut header_rows: Vec<Vec<String>> = Vec::new();
        while idx < header_start + span {
            match self.next_record()? {
                Some((rec, _)) => {
                    if idx >= header_start {
                        header_rows.push(rec);
                    }
                    idx += 1;
                }
                None => break,
            }
        }

        let mut report = ImportReport {
            sheets: vec!["CSV".to_string()],
            ..Default::default()
        };
        if header_rows.is_empty() {
            report.headers.push(SheetHeader {
                sheet: "CSV".to_string(),
                analysis: HeaderMap::dynamic(Vec::new()).analysis(),
            });
            return Ok(report);
        }

        let ncols = header_rows.iter().map(|r| r.len()).max().unwrap_or(0);
        let mut file_headers: Vec<String> = Vec::with_capacity(ncols);
        for c in 0..ncols {
            let parts: Vec<String> = header_rows
                .iter()
                .filter_map(|r| r.get(c))
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            file_headers.push(parts.join(" "));
        }
        // 导入计算列:补进"文件列"
        for cc in &options.computed {
            if !file_headers.iter().any(|h| h.as_str() == cc.header()) {
                file_headers.push(cc.header().to_string());
            }
        }

        let map = resolve_headers(&file_headers, &columns, &options.header);
        let missing = map.missing_required();
        if !missing.is_empty() {
            return Err(ExcelError::MissingColumns(missing));
        }
        report.headers.push(SheetHeader {
            sheet: "CSV".to_string(),
            analysis: map.analysis(),
        });

        let defaults: Vec<(u16, String)> = columns
            .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();

        // ── 数据行 ──
        while let Some((rec, line)) = self.next_record()? {
            report.total_rows += 1;
            let mut cells: Vec<Cell> = Vec::new();
            for (c, text) in rec.iter().enumerate() {
                if text.is_empty() {
                    continue;
                }
                let value = if options.trim_text {
                    CellValue::Text(text.trim().to_string())
                } else {
                    CellValue::Text(text.clone())
                };
                cells.push(Cell {
                    row: line,
                    col: c as u16,
                    value,
                    style: 0,
                });
            }

            // 默认值兜底
            for (col, text) in &defaults {
                let empty = cells
                    .iter()
                    .find(|c| c.col == *col)
                    .map(|c| c.value.is_empty())
                    .unwrap_or(true);
                if empty {
                    cells.push(Cell {
                        row: line,
                        col: *col,
                        value: CellValue::Text(text.clone()),
                        style: 0,
                    });
                }
            }

            // 计算列
            if !options.computed.is_empty() {
                let mut values: Vec<(u16, CellValue)> = Vec::new();
                {
                    let row = RowData {
                        row_index: line,
                        sheet: "CSV",
                        header: &map,
                        cells: &cells,
                        images: &[],
                        merges: &[],
                        styles: &styles,
                        hyperlinks: &[],
                        comments: &[],
                        validations: &[],
                        conditional_formats: &[],
                    };
                    for cc in &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)));
                    }
                }
                for (col, value) in values {
                    match cells.iter_mut().find(|c| c.col == col) {
                        Some(c) => c.value = value,
                        None => cells.push(Cell {
                            row: line,
                            col,
                            value,
                            style: 0,
                        }),
                    }
                }
            }
            cells.sort_by_key(|c| c.col);

            let row = RowData {
                row_index: line,
                sheet: "CSV",
                header: &map,
                cells: &cells,
                images: &[],
                merges: &[],
                styles: &styles,
                hyperlinks: &[],
                comments: &[],
                validations: &[],
                conditional_formats: &[],
            };

            // 行过滤
            if let Some(filter) = &options.row_filter {
                if !filter.keep(&row) {
                    report.skipped_rows += 1;
                    continue;
                }
            }
            // 空行
            if cells.iter().all(|c| c.value.is_empty()) && options.skip_empty_rows {
                report.skipped_rows += 1;
                continue;
            }

            match T::from_row(&row) {
                Ok(data) => {
                    let mut messages = data.validate().err().unwrap_or_default();
                    if messages.is_empty() {
                        if let Err(errs) = on_row(&row, data) {
                            messages = errs;
                        }
                    }
                    if messages.is_empty() {
                        report.success_rows += 1;
                    } else {
                        push_error(&mut report, line, messages);
                    }
                }
                Err(column_errors) => {
                    let messages: Vec<String> = column_errors
                        .iter()
                        .map(|e| {
                            if e.file_header.is_empty() {
                                format!("{}:{}", e.column, e.message)
                            } else {
                                format!("{}({}):{}", e.column, e.file_header, e.message)
                            }
                        })
                        .collect();
                    push_error(&mut report, line, messages);
                }
            }
        }

        report.elapsed_ms = started.elapsed().as_millis() as u64;
        Ok(report)
    }

    /// 解析为模型列表(小文件方便;错误直接返回第一条)
    pub fn parse_all<T: ExcelRow>(&mut self, options: &ReadOptions) -> Result<Vec<T>> {
        let mut out = Vec::new();
        let mut first_error: Option<ExcelError> = None;
        let report = self.read_into::<T, _>(options, |_row, data| {
            out.push(data);
            Ok(())
        })?;
        if !report.errors.is_empty() {
            let e = &report.errors[0];
            first_error = Some(ExcelError::InvalidRow {
                row: e.row,
                messages: e.messages.clone(),
            });
        }
        if let Some(e) = first_error {
            return Err(e);
        }
        Ok(out)
    }
}

fn push_error(report: &mut ImportReport, line: u32, messages: Vec<String>) {
    report.error_rows += 1;
    if report.errors.len() < 1000 {
        report.errors.push(RowError {
            row: line,
            sheet: "CSV".to_string(),
            messages,
        });
    } else {
        report.errors_truncated = true;
    }
}

/// 是否还有未闭合的引号(用于判断跨行字段)
fn has_unclosed_quote(data: &[u8]) -> bool {
    let mut in_quotes = false;
    let mut field_started = false;
    let mut i = 0;
    while i < data.len() {
        let b = data[i];
        if in_quotes {
            if b == b'"' {
                if i + 1 < data.len() && data[i + 1] == b'"' {
                    i += 2;
                    continue;
                }
                in_quotes = false;
            }
            i += 1;
        } else {
            match b {
                b'"' if !field_started => {
                    in_quotes = true;
                    field_started = true;
                }
                b',' => field_started = false,
                _ => field_started = true,
            }
            i += 1;
        }
    }
    in_quotes
}

/// 把一条记录切成字段(去尾部换行,处理引号与 `""` 转义)
fn split_fields(raw: &[u8]) -> Vec<String> {
    let mut end = raw.len();
    if end > 0 && raw[end - 1] == b'\n' {
        end -= 1;
    }
    if end > 0 && raw[end - 1] == b'\r' {
        end -= 1;
    }
    let data = &raw[..end];

    let mut fields: Vec<String> = Vec::new();
    let mut cur: Vec<u8> = Vec::new();
    let mut in_quotes = false;
    let mut field_started = false;
    let mut i = 0;
    while i < data.len() {
        let b = data[i];
        if in_quotes {
            if b == b'"' {
                if i + 1 < data.len() && data[i + 1] == b'"' {
                    cur.push(b'"');
                    i += 2;
                    continue;
                }
                in_quotes = false;
                i += 1;
                continue;
            }
            cur.push(b);
            i += 1;
            continue;
        }
        match b {
            b'"' if !field_started => {
                in_quotes = true;
                field_started = true;
                i += 1;
            }
            b',' => {
                fields.push(String::from_utf8_lossy(&cur).into_owned());
                cur.clear();
                field_started = false;
                i += 1;
            }
            _ => {
                cur.push(b);
                field_started = true;
                i += 1;
            }
        }
    }
    fields.push(String::from_utf8_lossy(&cur).into_owned());
    fields
}

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

    #[test]
    fn test_split_fields() {
        assert_eq!(split_fields(b"a,b,c\n"), vec!["a", "b", "c"]);
        assert_eq!(split_fields(b"a,\"b,c\",d"), vec!["a", "b,c", "d"]);
        assert_eq!(split_fields(b"\"he said \"\"hi\"\"\",x"), vec!["he said \"hi\"", "x"]);
        assert_eq!(split_fields(b"a,b\r\n"), vec!["a", "b"]);
        assert_eq!(split_fields(b"only"), vec!["only"]);
    }

    #[test]
    fn test_unclosed_quote() {
        assert!(!has_unclosed_quote(b"a,\"b\",c"));
        assert!(has_unclosed_quote(b"a,\"b"));
        assert!(!has_unclosed_quote(b"a,\"b\"\"c\""));
    }
}