Skip to main content

rust_excel_core/
cell.rs

1use calamine::Data as CalData;
2use umya_spreadsheet::Cell;
3
4use crate::types::CellValue;
5
6/// Extract a `CellValue` from an umya Cell.
7pub fn read_cell_value(cell: &Cell) -> CellValue {
8    // Check for formula first — get_formula() returns &str, empty if none
9    let formula = cell.get_formula();
10    if !formula.is_empty() {
11        return CellValue::Formula(formula.to_string());
12    }
13
14    let raw = cell.get_value();
15    if raw.is_empty() {
16        return CellValue::Empty;
17    }
18
19    let data_type = cell.get_data_type();
20    match data_type {
21        "b" => {
22            let b = raw.as_ref() == "1" || raw.eq_ignore_ascii_case("true");
23            CellValue::Boolean(b)
24        }
25        "n" => match raw.parse::<f64>() {
26            Ok(n) => CellValue::Number(n),
27            Err(_) => CellValue::String(raw.to_string()),
28        },
29        "s" | "str" | "inlineStr" => CellValue::String(raw.to_string()),
30        _ => {
31            // Try to parse as number, fall back to string
32            if let Ok(n) = raw.parse::<f64>() {
33                CellValue::Number(n)
34            } else {
35                CellValue::String(raw.to_string())
36            }
37        }
38    }
39}
40
41/// Convert a calamine `Data` value into our `CellValue`.
42pub fn from_calamine_data(data: &CalData) -> CellValue {
43    match data {
44        CalData::Int(i) => CellValue::Number(*i as f64),
45        CalData::Float(f) => CellValue::Number(*f),
46        CalData::String(s) => CellValue::String(s.clone()),
47        CalData::Bool(b) => CellValue::Boolean(*b),
48        CalData::Empty => CellValue::Empty,
49        CalData::DateTime(dt) => CellValue::Number(dt.as_f64()),
50        CalData::DateTimeIso(s) => CellValue::String(s.clone()),
51        CalData::DurationIso(s) => CellValue::String(s.clone()),
52        CalData::Error(e) => CellValue::String(format!("{:?}", e)),
53    }
54}
55
56/// Write a `CellValue` to an umya Cell.
57pub fn write_cell_value(cell: &mut Cell, value: &CellValue) {
58    match value {
59        CellValue::String(s) => {
60            cell.set_value_string(s);
61        }
62        CellValue::Number(n) => {
63            cell.set_value_number(*n);
64        }
65        CellValue::Boolean(b) => {
66            cell.set_value_bool(*b);
67        }
68        CellValue::Formula(f) => {
69            cell.set_formula(f);
70        }
71        CellValue::Empty => {
72            cell.set_value("");
73        }
74    }
75}