Skip to main content

fast_excel/
value.rs

1//! 单元格值模型 + 类型转换(读时 `from_cell` 解析、写时 `into_cell` 生成)
2//!
3//! 解析侧的宽容度是刻意设计的:Excel 里同一个"数字列"可能是文本、带千分位、
4//! 带货币符号或全角字符,[`CellValue::to_f64`] / [`CellValue::to_i64`] 统一兜底,
5//! 避免业务侧各写一套 `parse().unwrap_or_default()`。
6
7use chrono::{DateTime, NaiveDate, NaiveDateTime, TimeZone, Utc};
8use rust_decimal::Decimal;
9
10/// 单元格内嵌图片
11#[derive(Debug, Clone, Default, PartialEq, Eq)]
12pub struct CellImage {
13    pub bytes: Vec<u8>,
14    /// 扩展名(小写,不带点):png / jpg / gif / webp / bmp
15    pub ext: String,
16    /// 原始文件名或占位名(仅用于展示 / 落库时取名字)
17    pub name: Option<String>,
18}
19
20impl CellImage {
21    pub fn new(bytes: Vec<u8>, ext: impl Into<String>) -> Self {
22        Self {
23            bytes,
24            ext: ext.into(),
25            name: None,
26        }
27    }
28
29    pub fn named(mut self, name: impl Into<String>) -> Self {
30        self.name = Some(name.into());
31        self
32    }
33
34    pub fn is_empty(&self) -> bool {
35        self.bytes.is_empty()
36    }
37
38    pub fn mime(&self) -> &'static str {
39        mime_from_ext(&self.ext)
40    }
41}
42
43/// 扩展名 → mime
44pub fn mime_from_ext(ext: &str) -> &'static str {
45    match ext.to_ascii_lowercase().as_str() {
46        "png" => "image/png",
47        "gif" => "image/gif",
48        "webp" => "image/webp",
49        "bmp" => "image/bmp",
50        "emf" => "image/emf",
51        "wmf" => "image/wmf",
52        _ => "image/jpeg",
53    }
54}
55
56/// 单元格值
57#[derive(Debug, Clone, PartialEq, Default)]
58pub enum CellValue {
59    /// 空单元格
60    #[default]
61    Empty,
62    /// 文本
63    Text(String),
64    /// 数值
65    Number(f64),
66    /// 布尔
67    Bool(bool),
68    /// 日期
69    Date(NaiveDate),
70    /// 日期时间(无时区,Excel 语义)
71    DateTime(NaiveDateTime),
72    /// 公式(写出时按公式写;读入时保留原始公式文本)
73    Formula(String),
74    /// Excel 错误值(#DIV/0! 等)
75    Error(String),
76    /// 图片(写出时嵌入单元格;读入来自内嵌图片)
77    Image(CellImage),
78}
79
80impl CellValue {
81    /// 是否为空(空白文本视为空)
82    pub fn is_empty(&self) -> bool {
83        match self {
84            CellValue::Empty => true,
85            CellValue::Text(s) => s.trim().is_empty(),
86            _ => false,
87        }
88    }
89
90    pub fn type_name(&self) -> &'static str {
91        match self {
92            CellValue::Empty => "空",
93            CellValue::Text(_) => "文本",
94            CellValue::Number(_) => "数字",
95            CellValue::Bool(_) => "布尔",
96            CellValue::Date(_) => "日期",
97            CellValue::DateTime(_) => "日期时间",
98            CellValue::Formula(_) => "公式",
99            CellValue::Error(_) => "错误值",
100            CellValue::Image(_) => "图片",
101        }
102    }
103
104    /// 显示文本(导入预览 / 错误提示 / 导出兜底都用它)
105    pub fn to_text(&self) -> String {
106        match self {
107            CellValue::Empty => String::new(),
108            CellValue::Text(s) => s.clone(),
109            CellValue::Number(n) => fmt_number(*n),
110            CellValue::Bool(b) => {
111                if *b {
112                    "TRUE".to_string()
113                } else {
114                    "FALSE".to_string()
115                }
116            }
117            CellValue::Date(d) => d.format("%Y-%m-%d").to_string(),
118            CellValue::DateTime(dt) => dt.format("%Y-%m-%d %H:%M:%S").to_string(),
119            CellValue::Formula(f) => f.clone(),
120            CellValue::Error(e) => e.clone(),
121            // 图片没有文本表示:用占位名,便于预览展示"已识别到图片"
122            CellValue::Image(img) => img.name.clone().unwrap_or_default(),
123        }
124    }
125
126    /// 去空白后的显示文本
127    pub fn trimmed(&self) -> String {
128        self.to_text().trim().to_string()
129    }
130
131    pub fn to_f64(&self) -> Option<f64> {
132        match self {
133            CellValue::Number(n) => Some(*n),
134            CellValue::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
135            CellValue::Date(d) => Some(date_to_serial(*d, false)),
136            CellValue::DateTime(dt) => Some(datetime_to_serial(*dt, false)),
137            CellValue::Text(s) => parse_number(s),
138            CellValue::Formula(f) => parse_number(f),
139            _ => None,
140        }
141    }
142
143    pub fn to_i64(&self) -> Option<i64> {
144        match self {
145            CellValue::Text(s) => parse_number(s).map(round_to_i64),
146            CellValue::Formula(f) => parse_number(f).map(round_to_i64),
147            other => other.to_f64().map(round_to_i64),
148        }
149    }
150
151    pub fn to_bool(&self) -> Option<bool> {
152        match self {
153            CellValue::Bool(b) => Some(*b),
154            CellValue::Number(n) => Some(*n != 0.0),
155            CellValue::Text(s) => match normalize_text(s).to_ascii_lowercase().as_str() {
156                "true" | "yes" | "y" | "1" | "是" | "√" | "对" => Some(true),
157                "false" | "no" | "n" | "0" | "否" | "×" | "错" => Some(false),
158                _ => None,
159            },
160            _ => None,
161        }
162    }
163
164    pub fn to_decimal(&self) -> Option<Decimal> {
165        match self {
166            // 优先按"最短十进制表示"解析:Excel 里的 19.99 不该变成 19.98999999999999843680598132
167            CellValue::Number(n) => fmt_number(*n)
168                .parse::<Decimal>()
169                .ok()
170                .or_else(|| Decimal::from_f64_retain(*n)),
171            other => {
172                let t = normalize_number(other.to_text().as_str())?;
173                t.parse::<Decimal>().ok()
174            }
175        }
176    }
177
178    pub fn to_date(&self) -> Option<NaiveDate> {
179        match self {
180            CellValue::Date(d) => Some(*d),
181            CellValue::DateTime(dt) => Some(dt.date()),
182            CellValue::Number(n) => Some(serial_to_datetime(*n, false)?.date()),
183            other => parse_date_text(&other.to_text()),
184        }
185    }
186
187    pub fn to_datetime(&self) -> Option<NaiveDateTime> {
188        match self {
189            CellValue::DateTime(dt) => Some(*dt),
190            CellValue::Date(d) => d.and_hms_opt(0, 0, 0),
191            CellValue::Number(n) => serial_to_datetime(*n, false),
192            other => parse_datetime_text(&other.to_text()),
193        }
194    }
195}
196
197impl From<&str> for CellValue {
198    fn from(v: &str) -> Self {
199        CellValue::Text(v.to_string())
200    }
201}
202impl From<String> for CellValue {
203    fn from(v: String) -> Self {
204        CellValue::Text(v)
205    }
206}
207impl From<f64> for CellValue {
208    fn from(v: f64) -> Self {
209        CellValue::Number(v)
210    }
211}
212impl From<i64> for CellValue {
213    fn from(v: i64) -> Self {
214        CellValue::Number(v as f64)
215    }
216}
217impl From<i32> for CellValue {
218    fn from(v: i32) -> Self {
219        CellValue::Number(v as f64)
220    }
221}
222impl From<bool> for CellValue {
223    fn from(v: bool) -> Self {
224        CellValue::Bool(v)
225    }
226}
227
228impl From<CellValue> for String {
229    fn from(v: CellValue) -> Self {
230        v.to_text()
231    }
232}
233
234/// 单元格(含位置)
235#[derive(Debug, Clone, PartialEq)]
236pub struct Cell {
237    /// Excel 行号(1 基,与界面一致)
238    pub row: u32,
239    /// 列索引(0 基)
240    pub col: u16,
241    pub value: CellValue,
242    /// 原始样式索引(判断日期格式 / 自定义格式用)
243    pub style: u32,
244}
245
246impl Cell {
247    pub fn new(row: u32, col: u16, value: CellValue) -> Self {
248        Self {
249            row,
250            col,
251            value,
252            style: 0,
253        }
254    }
255
256    pub fn text(&self) -> String {
257        self.value.to_text()
258    }
259
260    pub fn is_empty(&self) -> bool {
261        self.value.is_empty()
262    }
263}
264// ─────────────────────────── 文本归一化 / 解析工具 ───────────────────────────
265
266/// 全角字符(含全角空格)转半角,去掉 BOM 与制表符
267pub fn normalize_text(s: &str) -> String {
268    let mut out = String::with_capacity(s.len());
269    for c in s.trim().trim_start_matches('\u{feff}').chars() {
270        match c {
271            '\u{3000}' => out.push(' '),
272            '\u{ff01}'..='\u{ff5e}' => {
273                // 全角 ASCII → 半角
274                out.push(char::from_u32(c as u32 - 0xfee0).unwrap_or(c))
275            }
276            '\u{feff}' => {}
277            c => out.push(c),
278        }
279    }
280    out
281}
282
283/// 数字文本归一化:去货币符号 / 千分位 / 空白;百分号换算成小数
284pub fn normalize_number(s: &str) -> Option<String> {
285    let t = normalize_text(s);
286    if t.is_empty() {
287        return None;
288    }
289    let (body, percent) = match t.strip_suffix('%') {
290        Some(rest) => (rest, true),
291        None => (t.as_str(), false),
292    };
293    let cleaned: String = body
294        .chars()
295        .filter(|c| !matches!(c, ',' | ' ' | '¥' | '¥' | '$' | '€' | '£' | '\'' | '_'))
296        .collect();
297    if cleaned.is_empty() {
298        return None;
299    }
300    if percent {
301        let v: f64 = cleaned.parse().ok()?;
302        Some(((v / 100.0).to_string()).parse().unwrap_or(cleaned))
303    } else {
304        Some(cleaned)
305    }
306}
307
308/// 宽松数字解析(文本 / 千分位 / 货币符号 / 百分号)
309pub fn parse_number(s: &str) -> Option<f64> {
310    let t = normalize_text(s);
311    if t.is_empty() {
312        return None;
313    }
314    let (body, percent) = match t.strip_suffix('%') {
315        Some(rest) => (rest, true),
316        None => (t.as_str(), false),
317    };
318    let cleaned: String = body
319        .chars()
320        .filter(|c| !matches!(c, ',' | ' ' | '¥' | '¥' | '$' | '€' | '£' | '\'' | '_'))
321        .collect();
322    let v: f64 = cleaned.parse().ok()?;
323    Some(if percent { v / 100.0 } else { v })
324}
325
326fn round_to_i64(v: f64) -> i64 {
327    if v.fract() == 0.0 {
328        v as i64
329    } else {
330        v.round() as i64
331    }
332}
333
334/// 日期文本解析(支持 `2024-01-02` / `2024/1/2` / `2024.1.2` / `2024年1月2日` / `20240102`)
335pub fn parse_date_text(s: &str) -> Option<NaiveDate> {
336    let t = normalize_text(s)
337        .replace(['年', '月'], "-")
338        .replace('日', "")
339        .replace(['.', '/'], "-");
340    let t = t.trim();
341    if t.is_empty() {
342        return None;
343    }
344    for f in [
345        "%Y-%m-%d",
346        "%Y-%m-%d %H:%M:%S",
347        "%Y-%m-%d %H:%M",
348        "%Y%m%d",
349        "%Y-%m",
350    ] {
351        if let Ok(d) = NaiveDate::parse_from_str(t, f) {
352            return Some(d);
353        }
354        if let Ok(dt) = NaiveDateTime::parse_from_str(t, f) {
355            return Some(dt.date());
356        }
357    }
358    None
359}
360
361/// 日期时间文本解析
362pub fn parse_datetime_text(s: &str) -> Option<NaiveDateTime> {
363    let t = normalize_text(s)
364        .replace(['年', '月'], "-")
365        .replace('日', "")
366        .replace(['.', '/', 'T'], "-");
367    let t = t.trim();
368    if t.is_empty() {
369        return None;
370    }
371    for f in [
372        "%Y-%m-%d %H:%M:%S",
373        "%Y-%m-%d %H:%M",
374        "%Y-%m-%d",
375        "%Y%m%d%H%M%S",
376        "%Y%m%d",
377    ] {
378        if let Ok(dt) = NaiveDateTime::parse_from_str(t, f) {
379            return Some(dt);
380        }
381    }
382    parse_date_text(t).and_then(|d| d.and_hms_opt(0, 0, 0))
383}
384
385/// 数字 → 显示文本(整数不带 `.0`,避免导出 1 显示成 1.0)
386pub fn fmt_number(v: f64) -> String {
387    if v.is_nan() {
388        return "NaN".to_string();
389    }
390    if v.fract() == 0.0 && v.abs() < 1e15 {
391        format!("{}", v as i64)
392    } else {
393        let s = format!("{v}");
394        s
395    }
396}
397
398// ─────────────────────────── Excel 日期序列号 ───────────────────────────
399
400/// Excel 序列号 → 日期时间
401///
402/// 1900 日期系统以 `1899-12-30` 为原点(自动跳过 Excel 的 1900 闰年 bug);
403/// 1904 日期系统(Mac 老文件)以 `1904-01-01` 为原点。
404pub fn serial_to_datetime(serial: f64, date_1904: bool) -> Option<NaiveDateTime> {
405    if !serial.is_finite() || serial < 0.0 {
406        return None;
407    }
408    // 1900 日期系统:序列号 < 61 时基点为 1899-12-31(Excel 把 1900 当闰年,
409    // 序列号 60 = 不存在的 1900-02-29),>= 61 时基点为 1899-12-30
410    let base = if date_1904 {
411        NaiveDate::from_ymd_opt(1904, 1, 1)?
412    } else if serial < 61.0 {
413        NaiveDate::from_ymd_opt(1899, 12, 31)?
414    } else {
415        NaiveDate::from_ymd_opt(1899, 12, 30)?
416    };
417    let ms = (serial * 86_400_000.0).round() as i64;
418    Some(base.and_hms_opt(0, 0, 0)? + chrono::Duration::milliseconds(ms))
419}
420
421/// 日期时间 → Excel 序列号
422pub fn datetime_to_serial(dt: NaiveDateTime, date_1904: bool) -> f64 {
423    let early = dt.date() < NaiveDate::from_ymd_opt(1900, 3, 1).unwrap();
424    let base = if date_1904 {
425        NaiveDate::from_ymd_opt(1904, 1, 1).unwrap()
426    } else if early {
427        NaiveDate::from_ymd_opt(1899, 12, 31).unwrap()
428    } else {
429        NaiveDate::from_ymd_opt(1899, 12, 30).unwrap()
430    };
431    let base = base.and_hms_opt(0, 0, 0).unwrap();
432    let dur = dt - base;
433    dur.num_milliseconds() as f64 / 86_400_000.0
434}
435
436/// 日期 → Excel 序列号
437pub fn date_to_serial(d: NaiveDate, date_1904: bool) -> f64 {
438    datetime_to_serial(d.and_hms_opt(0, 0, 0).unwrap(), date_1904)
439}
440
441// ─────────────────────────── 类型转换 trait ───────────────────────────
442
443/// 从单元格解析为业务类型(错误信息直接面向用户,中文)
444pub trait FromCell: Sized {
445    fn from_cell(cell: &Cell) -> std::result::Result<Self, String>;
446
447    /// 类型名(错误提示用)
448    fn type_name() -> &'static str {
449        "值"
450    }
451
452    /// 该列在文件里完全缺失时的取值:普通类型报错,`Option<T>` 返回 None
453    fn from_missing_column() -> std::result::Result<Self, String> {
454        Err("文件里缺少该列".to_string())
455    }
456}
457
458/// 业务类型 → 单元格值
459///
460/// 与 [`FromCell`] 构成 `from_cell` / `into_cell` 对称命名,因此 `&self` 接收者被 clippy 点名,
461/// 但改名会破坏公开 API,这里保持现状并压制该 lint。
462#[allow(clippy::wrong_self_convention)]
463pub trait IntoCell {
464    fn into_cell(&self) -> CellValue;
465}
466
467impl FromCell for CellValue {
468    fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
469        Ok(cell.value.clone())
470    }
471
472    fn type_name() -> &'static str {
473        "单元格值"
474    }
475}
476
477impl FromCell for Cell {
478    fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
479        Ok(cell.clone())
480    }
481
482    fn type_name() -> &'static str {
483        "单元格"
484    }
485}
486
487impl FromCell for CellImage {
488    fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
489        match &cell.value {
490            CellValue::Image(img) => Ok(img.clone()),
491            other => Err(format!("期望图片,实际是{}", other.type_name())),
492        }
493    }
494
495    fn type_name() -> &'static str {
496        "图片"
497    }
498}
499
500impl FromCell for String {
501    fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
502        Ok(cell.value.trimmed())
503    }
504
505    fn type_name() -> &'static str {
506        "文本"
507    }
508}
509
510impl<T: FromCell> FromCell for Option<T> {
511    fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
512        if cell.value.is_empty() {
513            Ok(None)
514        } else {
515            T::from_cell(cell).map(Some)
516        }
517    }
518
519    fn type_name() -> &'static str {
520        "可选值"
521    }
522
523    fn from_missing_column() -> std::result::Result<Self, String> {
524        Ok(None)
525    }
526}
527
528impl FromCell for bool {
529    fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
530        cell.value
531            .to_bool()
532            .ok_or_else(|| format!("期望布尔值,实际「{}」", cell.value.to_text()))
533    }
534
535    fn type_name() -> &'static str {
536        "布尔"
537    }
538}
539
540macro_rules! impl_from_cell_int {
541    ($($t:ty),* $(,)?) => {
542        $(
543            impl FromCell for $t {
544                fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
545                    let v = cell
546                        .value
547                        .to_i64()
548                        .ok_or_else(|| format!("期望整数,实际「{}」", cell.value.to_text()))?;
549                    <$t>::try_from(v)
550                        .map_err(|_| format!("整数「{v}」超出 {} 取值范围", stringify!($t)))
551                }
552
553                fn type_name() -> &'static str {
554                    "整数"
555                }
556            }
557        )*
558    };
559}
560
561impl_from_cell_int!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
562
563impl FromCell for f32 {
564    fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
565        cell.value
566            .to_f64()
567            .map(|v| v as f32)
568            .ok_or_else(|| format!("期望数字,实际「{}」", cell.value.to_text()))
569    }
570
571    fn type_name() -> &'static str {
572        "数字"
573    }
574}
575
576impl FromCell for f64 {
577    fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
578        cell.value
579            .to_f64()
580            .ok_or_else(|| format!("期望数字,实际「{}」", cell.value.to_text()))
581    }
582
583    fn type_name() -> &'static str {
584        "数字"
585    }
586}
587
588impl FromCell for Decimal {
589    fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
590        cell.value
591            .to_decimal()
592            .ok_or_else(|| format!("期望数字,实际「{}」", cell.value.to_text()))
593    }
594
595    fn type_name() -> &'static str {
596        "金额 / 小数"
597    }
598}
599
600impl FromCell for NaiveDate {
601    fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
602        cell.value
603            .to_date()
604            .ok_or_else(|| format!("期望日期,实际「{}」", cell.value.to_text()))
605    }
606
607    fn type_name() -> &'static str {
608        "日期"
609    }
610}
611
612impl FromCell for NaiveDateTime {
613    fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
614        cell.value
615            .to_datetime()
616            .ok_or_else(|| format!("期望日期时间,实际「{}」", cell.value.to_text()))
617    }
618
619    fn type_name() -> &'static str {
620        "日期时间"
621    }
622}
623
624impl FromCell for DateTime<Utc> {
625    fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
626        let dt = cell
627            .value
628            .to_datetime()
629            .ok_or_else(|| format!("期望日期时间,实际「{}」", cell.value.to_text()))?;
630        Ok(Utc.from_utc_datetime(&dt))
631    }
632
633    fn type_name() -> &'static str {
634        "日期时间(UTC)"
635    }
636}
637
638impl FromCell for serde_json::Value {
639    fn from_cell(cell: &Cell) -> std::result::Result<Self, String> {
640        Ok(match &cell.value {
641            CellValue::Empty => serde_json::Value::Null,
642            CellValue::Number(n) => serde_json::json!(n),
643            CellValue::Bool(b) => serde_json::json!(b),
644            other => serde_json::Value::String(other.to_text()),
645        })
646    }
647
648    fn type_name() -> &'static str {
649        "JSON 值"
650    }
651}
652
653impl IntoCell for CellValue {
654    fn into_cell(&self) -> CellValue {
655        self.clone()
656    }
657}
658
659impl IntoCell for Cell {
660    fn into_cell(&self) -> CellValue {
661        self.value.clone()
662    }
663}
664
665impl IntoCell for str {
666    fn into_cell(&self) -> CellValue {
667        CellValue::Text(self.to_string())
668    }
669}
670
671impl IntoCell for String {
672    fn into_cell(&self) -> CellValue {
673        CellValue::Text(self.clone())
674    }
675}
676
677impl IntoCell for &String {
678    fn into_cell(&self) -> CellValue {
679        CellValue::Text((*self).clone())
680    }
681}
682
683impl IntoCell for bool {
684    fn into_cell(&self) -> CellValue {
685        CellValue::Bool(*self)
686    }
687}
688
689impl IntoCell for f64 {
690    fn into_cell(&self) -> CellValue {
691        CellValue::Number(*self)
692    }
693}
694
695impl IntoCell for f32 {
696    fn into_cell(&self) -> CellValue {
697        CellValue::Number(*self as f64)
698    }
699}
700
701impl IntoCell for Decimal {
702    fn into_cell(&self) -> CellValue {
703        CellValue::Number(self.to_string().parse().unwrap_or_default())
704    }
705}
706
707impl IntoCell for NaiveDate {
708    fn into_cell(&self) -> CellValue {
709        CellValue::Date(*self)
710    }
711}
712
713impl IntoCell for NaiveDateTime {
714    fn into_cell(&self) -> CellValue {
715        CellValue::DateTime(*self)
716    }
717}
718
719impl IntoCell for DateTime<Utc> {
720    fn into_cell(&self) -> CellValue {
721        CellValue::DateTime(self.naive_utc())
722    }
723}
724
725impl IntoCell for CellImage {
726    fn into_cell(&self) -> CellValue {
727        CellValue::Image(self.clone())
728    }
729}
730
731macro_rules! impl_into_cell_num {
732    ($($t:ty),* $(,)?) => {
733        $(
734            impl IntoCell for $t {
735                fn into_cell(&self) -> CellValue {
736                    CellValue::Number(*self as f64)
737                }
738            }
739        )*
740    };
741}
742
743impl_into_cell_num!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
744
745impl<T: IntoCell> IntoCell for Option<T> {
746    fn into_cell(&self) -> CellValue {
747        match self {
748            Some(v) => v.into_cell(),
749            None => CellValue::Empty,
750        }
751    }
752}
753
754#[cfg(test)]
755mod tests {
756    use super::*;
757
758    #[test]
759    fn test_parse_number_variants() {
760        assert_eq!(parse_number("1,299.50"), Some(1299.5));
761        assert_eq!(parse_number("¥1 299"), Some(1299.0));
762        assert_eq!(parse_number("12"), Some(12.0));
763        assert_eq!(parse_number("50%"), Some(0.5));
764        assert_eq!(parse_number("abc"), None);
765    }
766
767    #[test]
768    fn test_parse_date_variants() {
769        let d = NaiveDate::from_ymd_opt(2024, 1, 2).unwrap();
770        assert_eq!(parse_date_text("2024-01-02"), Some(d));
771        assert_eq!(parse_date_text("2024/1/2"), Some(d));
772        assert_eq!(parse_date_text("2024.1.2"), Some(d));
773        assert_eq!(parse_date_text("2024年1月2日"), Some(d));
774        assert_eq!(parse_date_text("20240102"), Some(d));
775        assert_eq!(parse_date_text("not a date"), None);
776    }
777
778    #[test]
779    fn test_serial_roundtrip() {
780        let dt = NaiveDate::from_ymd_opt(2024, 1, 2)
781            .unwrap()
782            .and_hms_opt(12, 30, 0)
783            .unwrap();
784        let s = datetime_to_serial(dt, false);
785        assert_eq!(serial_to_datetime(s, false), Some(dt));
786        // Excel 著名的 1900 闰年 bug:序列号 1 = 1900-01-01
787        assert_eq!(
788            serial_to_datetime(1.0, false).unwrap().date(),
789            NaiveDate::from_ymd_opt(1900, 1, 1).unwrap()
790        );
791    }
792}