1use chrono::{DateTime, NaiveDate, NaiveDateTime, TimeZone, Utc};
8use rust_decimal::Decimal;
9
10#[derive(Debug, Clone, Default, PartialEq, Eq)]
12pub struct CellImage {
13 pub bytes: Vec<u8>,
14 pub ext: String,
16 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
43pub 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#[derive(Debug, Clone, PartialEq, Default)]
58pub enum CellValue {
59 #[default]
61 Empty,
62 Text(String),
64 Number(f64),
66 Bool(bool),
68 Date(NaiveDate),
70 DateTime(NaiveDateTime),
72 Formula(String),
74 Error(String),
76 Image(CellImage),
78}
79
80impl CellValue {
81 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 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 CellValue::Image(img) => img.name.clone().unwrap_or_default(),
123 }
124 }
125
126 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 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#[derive(Debug, Clone, PartialEq)]
236pub struct Cell {
237 pub row: u32,
239 pub col: u16,
241 pub value: CellValue,
242 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}
264pub 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 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
283pub 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
308pub 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
334pub 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
361pub 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
385pub 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
398pub fn serial_to_datetime(serial: f64, date_1904: bool) -> Option<NaiveDateTime> {
405 if !serial.is_finite() || serial < 0.0 {
406 return None;
407 }
408 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
421pub 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
436pub 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
441pub trait FromCell: Sized {
445 fn from_cell(cell: &Cell) -> std::result::Result<Self, String>;
446
447 fn type_name() -> &'static str {
449 "值"
450 }
451
452 fn from_missing_column() -> std::result::Result<Self, String> {
454 Err("文件里缺少该列".to_string())
455 }
456}
457
458#[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 assert_eq!(
788 serial_to_datetime(1.0, false).unwrap().date(),
789 NaiveDate::from_ymd_opt(1900, 1, 1).unwrap()
790 );
791 }
792}