DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
fix(import): show XLSX numbers as Excel's General format does
storybored3795e22a3dbeef4
diff --git a/crates/textimport/src/xlsx.rs b/crates/textimport/src/xlsx.rsindex 99d4db0a1..d07956998 100644--- a/crates/textimport/src/xlsx.rs+++ b/crates/textimport/src/xlsx.rs@@ -51,16 +51,34 @@ fn value(c: &El, shared: &[String]) -> String {}_ => {let raw = v();- // Whole numbers without the trailing ".0" Excel never shows.match raw.trim().parse::<f64>() {- Ok(f) if f.fract() == 0.0 && f.abs() < 1e15 => format!("{}", f as i64),- Ok(f) => f.to_string(),- Err(_) => raw,+ Ok(f) if f.is_finite() => general(f),+ _ => raw,}}}}+/// A number as Excel's General format shows it: at most 15 significant digits (Excel stores+/// doubles with 17, so `=0.1+0.2` is cached as 0.30000000000000004 and shown as 0.3), whole+/// numbers without ".0", and an exponent for very large or very small values.+fn general(f: f64) -> String {+ let r = format!("{f:.14e}").parse::<f64>().unwrap_or(f);+ let a = r.abs();+ if r == 0.0 {+ "0".into()+ } else if (1e-9..1e15).contains(&a) {+ // Shortest text that reads back as the rounded value; whole numbers drop the ".0".+ r.to_string()+ } else {+ let s = format!("{r:E}");+ match s.split_once('E') {+ Some((m, e)) if !e.starts_with('-') => format!("{m}E+{e}"),+ _ => s,+ }+ }+}+/// One worksheet as a grid of cached cell text, empty cells kept, for data merge./// The first used row is the header. Later rows that are entirely empty are left out./// Cells past the header are kept so the caller can warn. Over 200 columns or 100,000@@ -345,7 +363,7 @@ mod tests {#[test]fn numeric_values_keep_their_precision_in_tables_and_records() {- for text in ["1e-12", "-0.0000000000123", "1.23456789012345", "1e300", "12.0"] {+ for text in ["1e-12", "-0.0000000000123", "1.23456789012345", "1e300", "12.0", "-2.5e-300"] {let book = one_value(&format!(r#"<c r="A2"><v>{text}</v></c>"#));let placed = crate::import("values.xlsx", &book).unwrap();let table = placed.story.tables.values().next().unwrap();@@ -356,6 +374,27 @@ mod tests {}}+ #[test]+ fn numeric_values_show_as_excel_general_format() {+ for (text, shown) in [+ ("0.30000000000000004", "0.3"),+ ("2.0000000000000004", "2"),+ ("12.0", "12"),+ ("-0.5", "-0.5"),+ ("0", "0"),+ ("123456789012345", "123456789012345"),+ ("1e15", "1E+15"),+ ("1e300", "1E+300"),+ ("1e-12", "1E-12"),+ ("-1.5e-10", "-1.5E-10"),+ ("inf", "inf"),+ ] {+ let book = one_value(&format!(r#"<c r="A2"><v>{text}</v></c>"#));+ let rows = crate::xlsx_records(&book, None).unwrap();+ assert_eq!(rows[1][0], shown, "cell {text}");+ }+ }+#[test]fn cached_string_values_are_not_reformatted_as_numbers() {for text in ["00123", "1e3", "12.0", " 42 "] {