From ce8f5fca22d3d2347a72e00635b210ee9d105216 Mon Sep 17 00:00:00 2001 From: neilcawse <8085959+neilcawse@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:10:21 -0400 Subject: [PATCH] PivotTables: a sort by value keeps its scope, and more refresh fidelity - Sort by the values in a column (autoSortScope references naming items of the other axis): read, written back and used by the engine, instead of sorting by the grand total. A scope GridCraft can't represent loads as a sort by label, with a warning. - Changing subtotals in Design replaces each field's own subtotal setting. - A numeric "For empty cells show" caption (Excel stores missingCaption="0") is written as a number in the value's format. - With field headers off there's no Values row, so firstDataRow matches. - A field that isn't auto-sorted keeps its order even when it is cache order (date groups only when reordered). Items tied in a sort by value still break ties by label in the sort direction: over 60 tie groups in the 11 Excel-saved reports no stored order (pivotField items, sharedItems, first appearance, reversed or not) explains more than 21, the same as the current rule. --- crates/engine/src/cmd/pivot.rs | 97 ++++++++++++++++++++ crates/engine/src/pivot.rs | 49 +++++++--- crates/model/src/features.rs | 4 + crates/xlsx/src/pivot.rs | 131 ++++++++++++++++++++++----- crates/xlsx/src/tests/pivot_tests.rs | 36 +++++++- 5 files changed, 278 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index 804eacea6..6122e4e4f 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -1189,6 +1189,7 @@ fn sort(s: &mut Session, p: &Json) -> Result { let f = axis_field(C, pt, &field)?; f.sort = order; f.sort_by = by; + f.sort_scope.clear(); Ok(json!({})) }) } @@ -1291,7 +1292,11 @@ fn layout(s: &mut Session, p: &Json) -> Result { } } if let Some((on, top)) = subtotals { + // Design › Subtotals applies to every field, replacing per-field settings. pt.subtotals = on; + for f in pt.rows.iter_mut().chain(pt.columns.iter_mut()) { + f.subtotal = None; + } if let Some(t) = top { pt.subtotals_top = t; } @@ -2490,4 +2495,96 @@ mod tests { // 64 Sub items under the collapsed "g" show as one column group: (1 + grand total) x 256 columns fit. s.execute("pivot.addField", json!({"field": "Sub", "area": "columns"})).unwrap(); } + + #[test] + fn design_subtotals_replace_field_settings() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap(); + // A file's field can override the table default (`defaultSubtotal`). + edit_pt(&mut s, |p| { + p.subtotals = false; + p.rows[0].subtotal = Some(true); + }); + assert!(find_row(&s, "East Total").is_some()); + // Design › Subtotals › Do Not Show Subtotals applies to every field. + s.execute("pivot.subtotals", json!({"mode": "none"})).unwrap(); + assert!(pt(&s).rows.iter().all(|f| f.subtotal.is_none())); + assert_eq!(find_row(&s, "East Total"), None); + edit_pt(&mut s, |p| p.rows[0].subtotal = Some(false)); + s.execute("pivot.subtotals", json!({"mode": "bottom"})).unwrap(); + assert!(find_row(&s, "East Total").is_some()); + } + + #[test] + fn numeric_empty_cell_caption_is_a_number() { + let mut s = sales(); + s.execute("range.setValues", json!({"range": "A14", "values": [["South", "Kiwis", "1/1/2026", 1, 10]]})).unwrap(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap(); + // South has no Apples: the cell shows the caption, a number as Excel stores it. + edit_pt(&mut s, |p| p.empty_caption = Some("0".into())); + let south = find_row(&s, "South").unwrap(); + let apples = CellRef::new(south, 1); + assert_eq!(text(&s, &CellRef::new(south - 3, 1).a1()), "Apples"); + assert_eq!(val(&s, &apples.a1()), Value::Number(0.0)); + edit_pt(&mut s, |p| p.empty_caption = Some("n/a".into())); + assert_eq!(val(&s, &apples.a1()), Value::text("n/a")); + } + + /// 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) { + 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(); + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for i in 0..z.len() { + let mut f = z.by_index(i).unwrap(); + let name = f.name().to_string(); + let mut b = Vec::new(); + f.read_to_end(&mut b).unwrap(); + if name == "xl/pivotTables/pivotTable1.xml" { + b = patch(&String::from_utf8(b).unwrap()).into_bytes(); + } + out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + out.write_all(&b).unwrap(); + } + let bytes = out.finish().unwrap().into_inner(); + crate::io::open_bytes("t.xlsx", &bytes).unwrap() + } + + #[test] + fn sort_by_value_in_a_column_keeps_its_scope() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap(); + // Excel's "sort by the values in the Apples column": the scope also names Product's + // item 0 (Apples). Apples: East 160, West 170, North 90; totals East 415, West 285. + let one = ""; + let values_ref = ""; + let two = format!("{values_ref}"); + let (wb, _) = reopen_patched(&s, |x| { + assert!(x.contains(one), "{x}"); + x.replace(one, &two) + }); + let si = wb.active_sheet; + let p = wb.sheet(si).unwrap().pivots.last().unwrap(); + assert_eq!(p.rows[0].sort_scope, vec![("Product".to_string(), "Apples".to_string())]); + let out = crate::pivot::compute(&wb, p, si).unwrap(); + let labels: Vec = out.grid.iter().filter_map(|r| r.first()).map(|c| c.value.display()).collect(); + let order: Vec<&str> = labels.iter().map(String::as_str).filter(|l| ["East", "West", "North"].contains(l)).collect(); + assert_eq!(order, ["West", "East", "North"]); + // Saving writes the scope back. + let again = crate::io::save_bytes(&wb, "t.xlsx").unwrap(); + let (back, _) = crate::io::open_bytes("t.xlsx", &again).unwrap(); + assert_eq!(back.sheet(si).unwrap().pivots.last().unwrap().rows[0].sort_scope, p.rows[0].sort_scope); + // A scope GridCraft can't represent (two Product items) loads as a sort by label, with + // a warning, instead of as a sort by the grand total. + let bad = + format!("{values_ref}"); + let (wb2, warnings) = reopen_patched(&s, |x| x.replace(one, &bad)); + let p2 = wb2.sheet(wb2.active_sheet).unwrap().pivots.last().unwrap(); + assert_eq!(p2.rows[0].sort_by, None); + assert!(p2.rows[0].sort_scope.is_empty()); + assert!(warnings.iter().any(|w| w.contains("scope")), "{warnings:?}"); + } } diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index 29dbb3f6f..947c7d3de 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -292,6 +292,12 @@ impl FieldItems { fn shown_label(&self, i: u32) -> String { self.get(i).map(|x| x.shown_label().to_string()).unwrap_or_default() } + /// The item a setting names by label (or, for a number item, its unformatted number text). + fn find(&self, label: &str) -> Option { + let l = label.to_lowercase(); + let i = self.items.iter().position(|it| it.text == l || (it.formatted && number_to_text(it.num).to_lowercase() == l))?; + u32::try_from(i).ok() + } /// Applies a field's renamed items and manual item order. Settings name items by label; a /// number item also matches its unformatted number text (how a file's cache names it). fn apply(&mut self, f: &PivotField) { @@ -451,11 +457,12 @@ struct Node { children: Vec, } -/// Sorting of an axis by value fields: the value field each axis field sorts by, and the value -/// of an axis path (a row path with the column total, or a column path with the row total). +/// Sorting of an axis by value fields: per axis field, the value field it sorts by and the path +/// on the other axis whose values it uses (empty = the total); and the value of an axis path at +/// an other-axis path. struct ByValue<'a> { - fields: Vec>, - value: &'a dyn Fn(&[u32], usize) -> Option, + fields: Vec)>>, + value: &'a dyn Fn(&[u32], &[u32], usize) -> Option, } fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems], by_value: &ByValue) -> Vec { @@ -471,12 +478,12 @@ fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[F g.push(p); } } - let vi = by_value.fields.get(depth).copied().flatten().filter(|_| field.sort != PivotSort::None); + let vi = by_value.fields.get(depth).and_then(Option::as_ref).filter(|_| field.sort != PivotSort::None); let mut nodes: Vec<(Option, Node)> = order .into_iter() .map(|it| { let ps = groups.remove(&it).unwrap_or_default(); - let key = vi.and_then(|vi| ps.first().and_then(|p| p.get(..=depth)).and_then(|p| (by_value.value)(p, vi))); + let key = vi.and_then(|(vi, other)| ps.first().and_then(|p| p.get(..=depth)).and_then(|p| (by_value.value)(p, other, *vi))); (key, Node { item: it, children: build_tree(&ps, depth + 1, fields, items, by_value) }) }) .collect(); @@ -1054,11 +1061,24 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result = cols.iter().map(|(_, f)| *f).collect(); let row_paths: Vec<&[u32]> = row_set.iter().map(Vec::as_slice).collect(); let col_paths: Vec<&[u32]> = col_set.iter().map(Vec::as_slice).collect(); - let value_index = |f: &&PivotField| f.sort_by.as_deref().and_then(|n| vals.iter().position(|(_, v)| v.name.eq_ignore_ascii_case(n))); - let row_value = |p: &[u32], vi: usize| get(p, &[], vi).as_ref().and_then(Value::as_f64); - let col_value = |p: &[u32], vi: usize| get(&[], p, vi).as_ref().and_then(Value::as_f64); - let row_by = ByValue { fields: row_fields.iter().map(value_index).collect(), value: &row_value }; - let col_by = ByValue { fields: col_fields.iter().map(value_index).collect(), value: &col_value }; + // The other-axis path a sort scope names: its items of the other axis's fields, outer first, + // up to the first field it doesn't name. An item that isn't there has no values. + let scope_path = |f: &PivotField, others: &[(usize, &PivotField)], other_items: &[FieldItems]| -> Vec { + let mut path = Vec::new(); + for ((_, o), oi) in others.iter().zip(other_items) { + let Some((_, label)) = f.sort_scope.iter().find(|(c, _)| c.eq_ignore_ascii_case(&o.source_col)) else { break }; + path.push(oi.find(label).unwrap_or(u32::MAX)); + } + path + }; + let sorting = |f: &PivotField, others: &[(usize, &PivotField)], other_items: &[FieldItems]| { + let vi = f.sort_by.as_deref().and_then(|n| vals.iter().position(|(_, v)| v.name.eq_ignore_ascii_case(n)))?; + Some((vi, scope_path(f, others, other_items))) + }; + let row_value = |p: &[u32], other: &[u32], vi: usize| get(p, other, vi).as_ref().and_then(Value::as_f64); + let col_value = |p: &[u32], other: &[u32], vi: usize| get(other, p, vi).as_ref().and_then(Value::as_f64); + let row_by = ByValue { fields: row_fields.iter().map(|f| sorting(f, &cols, &col_items)).collect(), value: &row_value }; + let col_by = ByValue { fields: col_fields.iter().map(|f| sorting(f, &rows, &row_items)).collect(), value: &col_value }; let row_tree = build_tree(&row_paths, 0, &row_fields, &row_items, &row_by); let col_tree = build_tree(&col_paths, 0, &col_fields, &col_items, &col_by); let mut siblings: HashMap, Vec> = HashMap::new(); @@ -1370,9 +1390,12 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result().ok().filter(|x| x.is_finite()).map(Value::number).unwrap_or_else(|| Value::text(c.as_str())); + let fmt = if matches!(v, Value::Number(_)) { data_fmt.get(*vi).cloned().flatten() } else { None }; + g.set(r, l + j, v, ck.1, 0, fmt); } continue; }; diff --git a/crates/model/src/features.rs b/crates/model/src/features.rs index 7c1b3588b..8238eea11 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -926,6 +926,10 @@ pub struct PivotField { /// Sort the items by this value field (its caption) instead of by their labels, in the /// `sort` direction (Sort > More Sort Options > by value). Ignored when `sort` is `None`. pub sort_by: Option, + /// Where `sort_by` takes its values: items of fields on the other axis (source column, + /// item label), outer field first, e.g. sort the rows by the "Apples" column. Empty = the + /// grand total. + pub sort_scope: Vec<(String, String)>, /// Manual item order (item labels), used when `sort` is `None`; unlisted items follow in /// source order. pub item_order: Vec, diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index 02deb3036..632ef9579 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -775,6 +775,20 @@ fn cache_xml(c: &Cache, records_rid: Option<&str>, sys: DateSystem) -> String { s } +/// A field's `` order (cache item indexes): its manual order when it isn't auto-sorted +/// (unlisted items after), else cache order. +fn written_order(labels: &[String], af: Option<&PivotField>) -> Vec { + let mut order: Vec = (0..labels.len()).collect(); + if let Some(af) = af.filter(|f| f.sort == PivotSort::None && !f.item_order.is_empty()) { + let mut rank: HashMap = HashMap::with_capacity(af.item_order.len()); + for (r, o) in af.item_order.iter().enumerate() { + rank.entry(o.to_lowercase()).or_insert(r); + } + order.sort_by_cached_key(|x| labels.get(*x).and_then(|l| rank.get(&l.to_lowercase()).copied()).unwrap_or(usize::MAX)); + } + order +} + fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn Fn(&str) -> Option) -> String { let nf = c.fields.len(); let find_db = |name: &str| c.fields.iter().position(|f| f.col.is_some() && same(&f.name, name)); @@ -865,7 +879,9 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn let row_values = (k > 1 && pt.values_on_rows).then(|| values_at(row_map, row_idx.len())); // In Columns Σ Values comes after the last field: the column layout doesn't place it elsewhere. let col_values = (k > 1 && !pt.values_on_rows).then_some(col_idx.len()); - let values_row = col_idx.is_empty() && !compact && ((col_values.is_some() && pt.show_values_row) || (k == 1 && pt.classic_layout)); + // The engine shows the Values row and the classic caption row only with field headers on. + let values_row = + col_idx.is_empty() && !compact && pt.show_headers && ((col_values.is_some() && pt.show_values_row) || (k == 1 && pt.classic_layout)); let first_data_row = if col_idx.is_empty() { 1 + usize::from(values_row) } else { 1 + col_idx.len() + usize::from(col_values.is_some()) }; let row_levels = row_idx.len() + usize::from(row_values.is_some()); let first_data_col = if row_levels == 0 && col_idx.is_empty() { @@ -950,14 +966,7 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn let collapsed: &[String] = af.map(|f| f.collapsed_items.as_slice()).unwrap_or(&[]); let captions: &[(String, String)] = af.map(|f| f.item_captions.as_slice()).unwrap_or(&[]); // Items in display order: the manual order (unlisted items after), else cache order. - let mut order: Vec = (0..labels.len()).collect(); - if let Some(af) = af.filter(|f| f.sort == PivotSort::None && !f.item_order.is_empty()) { - let mut rank: HashMap = HashMap::with_capacity(af.item_order.len()); - for (r, o) in af.item_order.iter().enumerate() { - rank.entry(o.to_lowercase()).or_insert(r); - } - order.sort_by_cached_key(|x| labels.get(*x).and_then(|l| rank.get(&l.to_lowercase()).copied()).unwrap_or(usize::MAX)); - } + let order = written_order(&labels, af); let count = labels.len() + usize::from(subtotals); let _ = write!(s, ">"); for x in order { @@ -979,16 +988,33 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn s.push_str(""); } s.push_str(""); - // Sort by a value field: the scope references the Values field's data item. + // Sort by a value field: the scope references the Values field's data item, then + // the other axis's items it takes the values from (index into their ``). if let Some(d) = af .filter(|f| f.sort != PivotSort::None) .and_then(|f| f.sort_by.as_deref()) .and_then(|n| vals.iter().position(|(_, v)| same(&v.name, n))) { - let _ = write!( - s, - "" - ); + let mut refs = vec![(VALUES_FIELD.to_string(), d)]; + if let Some(af) = af { + let on_rows = pt.rows.iter().any(|r| std::ptr::eq(r, af)); + let (others, base) = if on_rows { (&pt.columns, pt.rows.len()) } else { (&pt.rows, 0) }; + for (col, label) in &af.sort_scope { + let Some(q) = others.iter().position(|o| same(&o.source_col, col)) else { continue }; + let Some(j) = c.axis_map.get(base + q).copied().flatten() else { continue }; + let Some(cf) = c.fields.get(j) else { continue }; + let labels = cf.item_labels(); + let pos = written_order(&labels, others.get(q)).iter().position(|x| labels.get(*x).is_some_and(|l| same(l, label))); + if let Some(pos) = pos { + refs.push((j.to_string(), pos)); + } + } + } + let _ = write!(s, "", refs.len()); + for (field, x) in &refs { + let _ = write!(s, ""); + } + s.push_str(""); } if af.is_some_and(|f| f.repeat_labels) { let _ = @@ -1287,12 +1313,28 @@ fn x14_ext<'a>(e: &'a El, uri: &str) -> Option<&'a El> { ext.children.first() } -/// The data field (dataFields position) a pivot field's items are sorted by: its -/// `` references the Values field (`4294967294`) and one data item. -fn auto_sort_data_field(e: &El) -> Option { +/// A pivot field's sort by value, from its ``: the data field (dataFields +/// position) the scope's Values reference (`4294967294`) names, and the other references as +/// (cache field, index into that field's ``). `Err(())` for a scope GridCraft can't +/// represent (a reference naming no item or several). +type AutoSort = Result<(usize, Vec<(usize, usize)>), ()>; + +fn auto_sort_scope(e: &El) -> Option { let refs = e.path(&["autoSortScope", "pivotArea", "references"])?; let r = refs.kids("reference").find(|r| r.attr("field") == Some(VALUES_FIELD))?; - r.child("x").and_then(|x| x.attr_u32("v")).map(|v| v as usize) + let data = r.child("x").and_then(|x| x.attr_u32("v"))? as usize; + let mut scope = Vec::new(); + for r in refs.kids("reference").filter(|r| r.attr("field") != Some(VALUES_FIELD)) { + let xs: Vec<&El> = r.kids("x").collect(); + match (r.attr_u32("field"), xs.as_slice()) { + (Some(f), [x]) if !r.flag("byPosition", false) && !r.flag("relative", false) => match x.attr_u32("v") { + Some(v) => scope.push((f as usize, v as usize)), + None => return Some(Err(())), + }, + _ => return Some(Err(())), + } + } + Some(Ok((data, scope))) } /// (source column name, date grouping) of a cache field used on an axis. @@ -1380,8 +1422,9 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option = Vec::new(); - // Per axis field (in rows-then-columns order): the data field its items are sorted by. - let mut sort_by: Vec> = Vec::new(); + // Per axis field (in rows-then-columns order): its cache field and its sort by value. + let mut sort_by: Vec> = Vec::new(); + let mut axis_ix: Vec = Vec::new(); let table_subtotals = pt.subtotals; // (fields, position of Σ Values (`-2`) among them) let mut axis = |cx: &mut Ctx<'_>, list: &[i64], filters: &mut Vec| -> (Vec, Option) { @@ -1406,7 +1449,7 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option PivotSort::Desc, _ => PivotSort::None, }; - by = auto_sort_data_field(e); + by = auto_sort_scope(e); f.caption = e.attr("name").filter(|n| !n.is_empty()).map(str::to_string); let own = e.flag("defaultSubtotal", true); f.subtotal = (own != table_subtotals).then_some(own); @@ -1421,9 +1464,12 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option` list fixes the order, even when it happens to be + // cache order (new items follow it). Date groups are in date order anyway; they + // keep a list only when it was reordered. let xs: Vec = items.iter().filter_map(|it| it.attr_u32("x")).collect(); - if f.sort == PivotSort::None && xs.windows(2).any(|w| w[0] > w[1]) { + let reordered = xs.windows(2).any(|w| w[0] > w[1]); + if f.sort == PivotSort::None && (group == PivotDateGroup::None || reordered) { f.item_order = items.iter().filter_map(|it| lab(it)).collect(); } if items.iter().any(|it| it.flag("h", false)) { @@ -1434,6 +1480,7 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option, x: &El, cache: &CacheIn, id: u32) -> Option = pt.rows.iter().chain(pt.columns.iter()).map(|f| f.source_col.clone()).collect(); + let item_label = |j: usize, x: usize| -> Option { + let k = items_of(pf(j)?).get(x)?.attr_u32("x")?; + cache.fields.get(j)?.labels().get(k as usize).cloned() + }; + let mut sorts: Vec)>> = Vec::with_capacity(sort_by.len()); + for (p, by) in sort_by.into_iter().enumerate() { + let others = if p < n_rows { n_rows..names.len() } else { 0..n_rows }; + let resolved = by.map(|by| { + let (d, refs) = by?; + let scope = refs + .into_iter() + .map(|(j, x)| { + let k = others.clone().find(|k| axis_ix.get(*k) == Some(&j)).ok_or(())?; + Ok((names.get(k).cloned().ok_or(())?, item_label(j, x).ok_or(())?)) + }) + .collect::, ()>>()?; + Ok((d, scope)) + }); + if matches!(resolved, Some(Err(()))) { + cx.warn(format!( + "PivotTable \"{}\": a sort by value of \"{}\" has a scope that is not supported; it sorts by the label", + pt.name, + names.get(p).map(String::as_str).unwrap_or("") + )); + } + sorts.push(resolved.and_then(Result::ok)); + } let values = &pt.values; - for (f, by) in pt.rows.iter_mut().chain(pt.columns.iter_mut()).zip(sort_by) { - f.sort_by = by.and_then(|d| data_value.get(d).copied().flatten()).and_then(|v| values.get(v)).map(|v| v.name.clone()); + for (f, by) in pt.rows.iter_mut().chain(pt.columns.iter_mut()).zip(sorts) { + let Some((d, scope)) = by else { continue }; + f.sort_by = data_value.get(d).copied().flatten().and_then(|v| values.get(v)).map(|v| v.name.clone()); + if f.sort_by.is_some() { + f.sort_scope = scope; + } } // Calculated fields of the cache (each PivotTable on it can use them). diff --git a/crates/xlsx/src/tests/pivot_tests.rs b/crates/xlsx/src/tests/pivot_tests.rs index 7a47af6ed..8dd9277af 100644 --- a/crates/xlsx/src/tests/pivot_tests.rs +++ b/crates/xlsx/src/tests/pivot_tests.rs @@ -92,13 +92,14 @@ fn workbook() -> Workbook { collapsed_items: vec!["East".into()], caption: Some("Area".into()), sort_by: Some("Sum of Sales".into()), + sort_scope: vec![("Product".into(), "B".into())], item_captions: vec![("West".into(), "**West".into())], subtotal: Some(true), repeat_labels: true, number_format: Some("0.0".into()), ..PivotField::default() }], - columns: vec![PivotField { sort: PivotSort::None, ..field("Product") }], + columns: vec![PivotField { sort: PivotSort::None, item_order: vec!["C".into(), "A".into(), "B".into()], ..field("Product") }], values: vec![ PivotValue { source_col: "Sales".into(), @@ -364,6 +365,11 @@ fn pivot_xml_details() { "{t1}" ); assert!(t1.contains("")); + // Sort by the values in the "B" column: Product's item B sits third in its ``. + assert!( + t1.contains(""), + "{t1}" + ); assert!(t1.contains("subtotal=\"count\"")); assert!(t1.contains("numFmtId=\"4\"")); assert!(t1.contains("axis=\"axisPage\"")); @@ -612,3 +618,31 @@ fn data_on_rows_with_one_value_field_reads_without_warning() { let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); assert!(back.sheet(0).unwrap().pivots[0].values_on_rows); } + +#[test] +fn manual_order_in_cache_order_is_kept() { + // Not auto-sorted, items written in cache order: the order is still the file's, so a + // refresh over reordered source rows keeps it. + let mut wb = workbook(); + wb.sheet_mut(1).unwrap().pivots[0].columns[0].item_order.clear(); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + assert_eq!(back.sheet(1).unwrap().pivots[0].columns[0].item_order, ["A", "B", "C"]); +} + +#[test] +fn location_without_field_headers_has_no_values_row() { + let mut wb = workbook(); + { + let p = &mut wb.sheet_mut(1).unwrap().pivots[2]; + p.values.push(PivotValue { source_col: "Sales".into(), name: "Sum of Sales".into(), ..PivotValue::default() }); + p.layout = PivotLayout::Outline; + p.show_headers = false; + } + let parts = unzip(&write_xlsx(&wb).unwrap()); + let t3 = String::from_utf8(parts.get("xl/pivotTables/pivotTable3.xml").unwrap().clone()).unwrap(); + assert!(t3.contains("firstHeaderRow=\"1\" firstDataRow=\"1\""), "{t3}"); + wb.sheet_mut(1).unwrap().pivots[2].show_headers = true; + let parts = unzip(&write_xlsx(&wb).unwrap()); + let t3 = String::from_utf8(parts.get("xl/pivotTables/pivotTable3.xml").unwrap().clone()).unwrap(); + assert!(t3.contains("firstHeaderRow=\"1\" firstDataRow=\"2\""), "{t3}"); +}