From b60d37e4e9b2ce2e345a79956c30a48f3079b00b Mon Sep 17 00:00:00 2001 From: Local contributor Date: Wed, 14 Oct 2026 09:11:28 -0400 Subject: [PATCH] PivotTables: date items sort after logicals and errors The ascending item order put dates between text and TRUE/FALSE. Excel's item lists put numbers, text, logicals, errors, dates and then blanks: in the one Excel-saved cache in the test corpus whose fields mix dates with logicals or errors (ClosedXML VariousDataTypesInTableColumns), the Mixed Types field lists 10, 14.5, ABC, TRUE, #DIV/0!, 16:30, 8/10/2020, (blank), and the DateTime with num field puts its numbers before its dates. The sort classes follow that order. Also adds the regression test for the time items read from an Excel cache. --- crates/engine/src/cmd/pivot.rs | 63 +++++++++++++++++++++++++++++++++- crates/engine/src/pivot.rs | 10 +++--- 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index ed1dadb6e..8c1400544 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -2169,6 +2169,25 @@ mod tests { assert_eq!(text(&s, "A5"), "NA"); } + #[test] + fn dates_sort_after_logicals_and_errors() { + // Excel's ascending item order: numbers, text, logicals, errors, dates, blanks. + let mut s = sales(); + s.execute("cell.set", json!({"cell": "C11", "input": "TRUE"})).unwrap(); + s.execute("cell.set", json!({"cell": "C12", "input": "=1/0"})).unwrap(); + s.execute("cell.set", json!({"cell": "C13", "input": "NA"})).unwrap(); + s.execute("insert.pivotTable", json!({"rows": ["Date"], "values": ["Sales"]})).unwrap(); + edit_pt(&mut s, |p| { + p.rows[0].number_format = None; + p.rows[0].sort = PivotSort::Asc; + }); + let p = pt(&s); + let r = p.last_range.unwrap(); + let labels: Vec = (r.start.row + 1..=r.end.row).map(|row| text(&s, &CellRef::new(row, r.start.col).a1())).collect(); + // 46037 is 1/15/2026, the first date. + assert_eq!(labels[..4], ["NA", "TRUE", "#DIV/0!", "46037"]); + } + fn pivot_chart(s: &Session) -> gridcraft_model::Chart { s.doc().unwrap().wb.active().unwrap().charts.last().unwrap().clone() } @@ -2533,6 +2552,10 @@ mod tests { /// Saves the active workbook, applies `patch` to the first PivotTable part and reopens it. fn reopen_patched(s: &Session, patch: impl Fn(&str) -> String) -> (gridcraft_model::Workbook, Vec) { + reopen_patched_part(s, "xl/pivotTables/pivotTable1.xml", patch) + } + /// Saves the active workbook, applies `patch` to `part` and reopens it. + fn reopen_patched_part(s: &Session, part: &str, patch: impl Fn(&str) -> String) -> (gridcraft_model::Workbook, Vec) { use std::io::{Read, Write}; let bytes = crate::io::save_bytes(&s.doc().unwrap().wb, "t.xlsx").unwrap(); let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); @@ -2542,7 +2565,7 @@ mod tests { let name = f.name().to_string(); let mut b = Vec::new(); f.read_to_end(&mut b).unwrap(); - if name == "xl/pivotTables/pivotTable1.xml" { + if name == part { b = patch(&String::from_utf8(b).unwrap()).into_bytes(); } out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); @@ -2732,4 +2755,42 @@ mod tests { assert_eq!(first_col(&wb, &quarters), ["Qtr3", "Qtr1", "Qtr2", "Qtr4"]); assert_eq!(first_col(&reopen(&wb), &quarters), ["Qtr3", "Qtr1", "Qtr2", "Qtr4"]); } + + #[test] + fn manual_order_of_time_items_from_an_excel_cache() { + // Excel caches times as ``: those items must name the + // report's 8:00 and 9:30, or a refresh puts the blank ahead of them. + let mut s = Session::new(); + s.new_workbook(); + for (cell, input) in [("A1", "Shift"), ("B1", "Sales"), ("A2", "8:00"), ("B2", "10"), ("A3", "9:30"), ("B3", "20"), ("B4", "5")] { + s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap(); + } + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + s.execute("insert.pivotTable", json!({"rows": ["Shift"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.sort", json!({"field": "Shift", "order": "none"})).unwrap(); + // The report's first column: times as minutes, and the blank item. + let shifts = |wb: &gridcraft_model::Workbook| -> Vec { + let si = wb.active_sheet; + let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap(); + out.grid + .iter() + .filter_map(|r| match &r.first()?.value { + Value::Number(n) => Some(format!("{}", (n * 1440.0).round())), + v if v.display() == "(blank)" => Some(v.display()), + _ => None, + }) + .collect() + }; + let order = ["480", "570", "(blank)"]; + assert_eq!(shifts(&s.doc().unwrap().wb), order); + let excel_items = ""; + let (back, _) = reopen_patched_part(&s, "xl/pivotCache/pivotCacheDefinition1.xml", |x| { + let ours = ""; + assert!(x.contains(ours), "{x}"); + x.replace(ours, excel_items) + }); + assert_eq!(shifts(&back), order); + // Saving writes that order back. + assert_eq!(shifts(&reopen(&back)), order); + } } diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index 22fcb5c1a..a35f8cdba 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -221,8 +221,8 @@ struct FieldItems { index: HashMap, } -/// Sort classes: numbers, text, dates (a number shown with a date format; Excel sorts these -/// after text), logicals, errors, blanks. +/// Sort classes: numbers, text, logicals, errors, dates (a number shown with a date format; +/// Excel sorts these after errors), blanks. fn cmp_items(a: &Item, b: &Item) -> Ordering { a.class.cmp(&b.class).then(a.num.total_cmp(&b.num)).then_with(|| a.text.cmp(&b.text)) } @@ -259,15 +259,15 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: return (format!("g{key}"), it(Value::text(label.as_str()), label, 0, key, false)); } let shown = crate::display::format(v, fmt, wb); - let class = if crate::display::number_format(fmt).is_date() { 2 } else { 0 }; + let class = if crate::display::number_format(fmt).is_date() { 4 } else { 0 }; (format!("n{}", n.to_bits()), it(v.clone(), shown.text, class, *n, true)) } Value::Text(t) => (format!("t{}", t.to_lowercase()), it(v.clone(), t.to_string(), 1, 0.0, false)), Value::Bool(b) => { let l = if *b { "TRUE" } else { "FALSE" }; - (format!("l{l}"), it(Value::Bool(*b), l.into(), 3, *b as u8 as f64, false)) + (format!("l{l}"), it(Value::Bool(*b), l.into(), 2, *b as u8 as f64, false)) } - Value::Error(e) => (format!("e{}", e.as_str()), it(v.clone(), e.as_str().into(), 4, 0.0, false)), + Value::Error(e) => (format!("e{}", e.as_str()), it(v.clone(), e.as_str().into(), 3, 0.0, false)), Value::Array(_) => make_item(wb, &v.scalar(), group, fmt, first), } }