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.
This commit is contained in:
Local contributor
2026-10-14 09:11:28 -04:00
parent fadcec3683
commit b60d37e4e9
2 changed files with 67 additions and 6 deletions
+62 -1
View File
@@ -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<String> = (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<String>) {
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<String>) {
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 `<d v="1899-12-30T08:00:00"/>`: 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<String> {
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 = "<d v=\"1899-12-30T08:00:00\"/><d v=\"1899-12-30T09:30:00\"/><m/>";
let (back, _) = reopen_patched_part(&s, "xl/pivotCache/pivotCacheDefinition1.xml", |x| {
let ours = "<n v=\"0.3333333333333333\"/><n v=\"0.3958333333333333\"/><m/>";
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);
}
}
+5 -5
View File
@@ -221,8 +221,8 @@ struct FieldItems {
index: HashMap<String, u32>,
}
/// 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),
}
}