From fa844ac0ed6f6bc0849ed1350dd7745075f9deae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingmar=20L=C3=BCbbe?= Date: Tue, 13 Oct 2026 09:14:53 +0200 Subject: [PATCH 01/13] PivotTables: two value fields without column fields open in Excel as GridCraft lays them out With two or more value fields and no column field, GridCraft lays out the value captions as the header row. Excel 365 does the same for its own PivotTables, because they turn "Show the Values row" off (x14:pivotTableDefinition hideValuesRow="1"). GridCraft's files didn't say so, so Excel added a "Values" caption row on refresh: the report moved down a row, and anything in the row below GridCraft's report left Excel showing only #SPILL! in its place. The writer now turns the Values row off as Excel does, and writes the location Excel writes for such a report (firstHeaderRow 0, firstDataRow 1). With headers off, the caption row above column fields is left out when it would be empty, as in Excel (firstHeaderRow 0). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj --- crates/engine/src/cmd/pivot.rs | 26 ++++++++++++++++++++++++++ crates/engine/src/pivot.rs | 25 +++++++++++++++++-------- crates/xlsx/src/pivot.rs | 24 ++++++++++++++++++++++-- crates/xlsx/src/tests/pivot_tests.rs | 27 ++++++++++++++++++++++++++- 4 files changed, 91 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index 8a441fa1b4..818d742077 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -1676,6 +1676,32 @@ mod tests { assert_eq!(val(&s, &CellRef::new(last.end.row, 7).a1()), Value::Number(TOTAL)); } + #[test] + fn two_values_without_column_fields_keep_one_header_row() { + // Excel 365 hides the Values row of its new PivotTables ("Show the Values row" off): with + // two value fields and no column field the value captions are the header row, in every + // layout. GridCraft lays it out that way and saves the setting (hideValuesRow). + let mut s = sales(); + s.execute("insert.pivotTable", json!({"values": ["Sales", {"field": "Units", "func": "average"}]})).unwrap(); + assert_eq!(text(&s, "A3"), "Sum of Sales"); + assert_eq!(text(&s, "B3"), "Average of Units"); + assert_eq!(val(&s, "A4"), Value::Number(TOTAL)); + assert_eq!(pt(&s).last_range.unwrap().a1(), "A3:B4"); + s.execute("pivot.addField", json!({"field": "Region", "area": "rows"})).unwrap(); + for layout in ["compact", "outline", "tabular"] { + s.execute("pivot.layout", json!({"layout": layout})).unwrap(); + assert_eq!(text(&s, "B3"), "Sum of Sales", "{layout}"); + assert_eq!(text(&s, "A4"), "East", "{layout}"); + assert_eq!(pt(&s).last_range.unwrap().a1(), "A3:C7", "{layout}"); + } + let wb = (*s.doc().unwrap().wb).clone(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(gridcraft_xlsx::write_xlsx(&wb).unwrap())).unwrap(); + let mut x = String::new(); + std::io::Read::read_to_string(&mut z.by_name("xl/pivotTables/pivotTable1.xml").unwrap(), &mut x).unwrap(); + assert!(x.contains("hideValuesRow=\"1\""), "{x}"); + assert!(x.contains(""), "{x}"); + } + #[test] fn date_grouping_by_quarter_and_month() { let mut s = sales(); diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index 6146bd4f91..2b2b239993 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -1081,6 +1081,9 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result 1 && !on_rows; if cols.is_empty() { let r = g.push_row(RowKind::Header)?; row_header(&mut g, r); @@ -1093,15 +1096,21 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result 0 && k == 1 { - g.set(cap, 0, Value::text(val_name(0)), CellKind::Header, 0, None); - } - if headers_on { - let caption = if compact { "Column Labels".to_string() } else { col_fields.first().map(|f| f.source_col.clone()).unwrap_or_default() }; - g.set(cap, l, Value::text(caption), CellKind::Header, 0, None); + // The caption row holds the value field's caption (one value field) and, with headers + // shown, the column caption. With headers off and nothing to show in it, Excel leaves it out. + let value_caption = l > 0 && k == 1; + if value_caption || headers_on { + let cap = g.push_row(RowKind::Header)?; + if value_caption { + g.set(cap, 0, Value::text(val_name(0)), CellKind::Header, 0, None); + } + if headers_on { + let caption = + if compact { "Column Labels".to_string() } else { col_fields.first().map(|f| f.source_col.clone()).unwrap_or_default() }; + g.set(cap, l, Value::text(caption), CellKind::Header, 0, None); + } } - let levels = cols.len() + usize::from(k > 1 && !on_rows); + let levels = cols.len() + usize::from(values_in_cols); let first_level = g.rows.len(); for _ in 0..levels { g.push_row(RowKind::Header)?; diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index 609ae530e1..ef887ac582 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -40,6 +40,8 @@ const MAX_ITEMS: usize = 1_048_576; const MAX_FIELDS: usize = 16_384; /// The `x14:dataField` extension (Excel 2010 show-values-as additions such as rank). const EXT_X14_DATA_FIELD: &str = "{E15A36E0-9728-4e99-A89B-3F7291B0FE68}"; +/// The `x14:pivotTableDefinition` extension ("Show the Values row": `hideValuesRow`). +const EXT_X14_TABLE: &str = "{962EF5D1-5CA2-4c93-8EF4-DBF5C05439D2}"; const NS_X14: &str = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"; const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; @@ -835,8 +837,18 @@ 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 first_data_row = if col_idx.is_empty() { 1 } else { 1 + col_idx.len() + usize::from(col_values.is_some()) }; let row_levels = row_idx.len() + usize::from(row_values.is_some()); + // Σ Values alone in Columns: its row is hidden (hideValuesRow, below), so the value captions are + // the header row, which Excel 365 counts as row 0. Column fields take a row each, Σ Values among + // them, below a caption row. The caption row holds the value's caption (one value field) and, + // with headers shown, the column caption; Excel leaves it out when it would be empty + // (firstHeaderRow 0). + let (first_header_row, first_data_row) = if col_idx.is_empty() { + (usize::from(col_values.is_none()), 1) + } else { + let caption_row = pt.show_headers || k == 1; + (usize::from(caption_row), usize::from(caption_row) + col_idx.len() + usize::from(col_values.is_some())) + }; let first_data_col = if row_levels == 0 && col_idx.is_empty() { 0 } else if compact { @@ -844,7 +856,11 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn } else { row_levels.max(1) }; - let _ = write!(s, ""); + // "Show the Values row" off, as in Excel 365's new PivotTables: without this, Excel adds a + // Values caption row above the value captions when Σ Values is the only column field, which the + // report as laid out doesn't have. + let _ = write!(s, ""); s.push_str(""); s } diff --git a/crates/xlsx/src/tests/pivot_tests.rs b/crates/xlsx/src/tests/pivot_tests.rs index 99a15d6e74..9aa2dfa3f4 100644 --- a/crates/xlsx/src/tests/pivot_tests.rs +++ b/crates/xlsx/src/tests/pivot_tests.rs @@ -338,7 +338,8 @@ fn pivot_xml_details() { let parts = unzip(&write_xlsx(&workbook()).unwrap()); let t1 = String::from_utf8(parts.get("xl/pivotTables/pivotTable1.xml").unwrap().clone()).unwrap(); assert!( - t1.contains(""), + // Headers off and two value fields: no caption row (Excel 365 writes firstHeaderRow 0). + t1.contains(""), "{t1}" ); assert!(t1.contains("")); @@ -569,6 +570,30 @@ fn values_on_rows_round_trip() { assert_eq!(back.sheet(1).unwrap().pivots[1].values_position, None); } +#[test] +fn two_values_without_column_fields_hide_the_values_row() { + // Σ Values alone in Columns: GridCraft lays out no Values row, so the file turns Excel's "Show + // the Values row" off (hideValuesRow), as Excel 365 does for its own new PivotTables, and the + // value captions are the header row (Excel writes firstHeaderRow="0" firstDataRow="1"). + let mut wb = workbook(); + { + let p = wb.sheet_mut(1).unwrap().pivots.get_mut(2).unwrap(); + p.values.push(PivotValue { source_col: "Sales".into(), func: PivotFunc::Sum, name: "Sum of Sales".into(), ..PivotValue::default() }); + p.last_range = Some(rr("AB1:AD6")); + } + let parts = unzip(&write_xlsx(&wb).unwrap()); + let t3 = String::from_utf8(parts.get("xl/pivotTables/pivotTable3.xml").unwrap().clone()).unwrap(); + assert!(t3.contains(""), "{t3}"); + // One value field: the header row is row 1, as before. + let t1 = String::from_utf8(unzip(&write_xlsx(&workbook()).unwrap()).get("xl/pivotTables/pivotTable3.xml").unwrap().clone()).unwrap(); + assert!(t1.contains("firstHeaderRow=\"1\" firstDataRow=\"1\" firstDataCol=\"1\""), "{t1}"); + // Read back unchanged. + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + assert_eq!(back.sheet(1).unwrap().pivots[2], wb.sheet(1).unwrap().pivots[2]); +} + #[test] fn values_ahead_of_column_fields_read_last() { let table = r#""#; From 6e27bb4e100212678cce127ceba2c22e8bfd915c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingmar=20L=C3=BCbbe?= Date: Tue, 13 Oct 2026 09:19:19 +0200 Subject: [PATCH 02/13] PivotTables: an item whose values are all blank shows empty cells, as in Excel When every value of an item is blank, Excel 365 leaves its value cells empty for every function. GridCraft showed 0 for Sum, Count, Max, Min and Product and #DIV/0! for Average, StdDev and Var, which reads as data that is 0 or as an error. Shown as a share of a total or as a running total, such an item still counts as 0, as Excel shows it (0 % and the carried running total). Calculated fields keep reading a blank sum as 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj --- crates/engine/src/cmd/pivot.rs | 31 +++++++++++++++++++++++++++++++ crates/engine/src/pivot.rs | 12 +++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index 818d742077..55556d4701 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -1702,6 +1702,37 @@ mod tests { assert!(x.contains(""), "{x}"); } + #[test] + fn items_with_only_blank_values_show_empty_cells() { + // Key A: 1 and 3; B: one blank value; C: 2. Excel 365 leaves B empty for every function. + let keyed = || { + let mut s = Session::new(); + s.new_workbook(); + let rows = json!([["Key", "Val"], ["A", 1], ["A", 3], ["B", null], ["C", 2]]); + s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap(); + s + }; + let funcs = ["sum", "average", "count", "max", "min", "product", "countNumbers", "stdDev", "stdDevP", "var", "varP"]; + let values: Vec = funcs.iter().map(|f| json!({"field": "Val", "func": f})).collect(); + let mut s = keyed(); + s.execute("insert.pivotTable", json!({"source": "Sheet1!$A$1:$B$5", "destination": "Sheet1!E3", "rows": ["Key"], "values": values})).unwrap(); + let b = find_row(&s, "B").unwrap(); + for (j, f) in funcs.iter().enumerate() { + assert_eq!(val(&s, &CellRef::new(b, 5 + j as u32).a1()), Value::Empty, "{f}"); + } + let a = find_row(&s, "A").unwrap(); + assert_eq!(val(&s, &CellRef::new(a, 5).a1()), Value::Number(4.0)); + // As a share of the grand total B is 0; as a running total it carries A forward. + for (show, want) in [("percentOfGrandTotal", 0.0), ("runningTotal", 4.0)] { + let mut s = keyed(); + s.execute("insert.pivotTable", json!({"source": "Sheet1!$A$1:$B$5", "destination": "Sheet1!E3", "rows": ["Key"], "values": ["Val"]})) + .unwrap(); + s.execute("pivot.valueSettings", json!({"field": "Val", "showAs": show})).unwrap(); + let b = find_row(&s, "B").unwrap(); + assert_eq!(val(&s, &CellRef::new(b, 5).a1()), Value::Number(want), "{show}"); + } + } + #[test] fn date_grouping_by_quarter_and_month() { let mut s = sales(); diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index 2b2b239993..9f0c5d761d 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -341,6 +341,10 @@ impl Acc { } } fn result(&self, f: PivotFunc) -> Value { + // An item whose values are all blank shows an empty cell, whatever the function (Excel 365). + if self.count == 0 { + return Value::Empty; + } let n = self.nums as f64; match f { PivotFunc::Count => return Value::number(self.count as f64), @@ -1169,7 +1173,7 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result Result raw, + (Value::Empty, _) => Value::Number(0.0), + _ => raw, + }; let shown = match vdef.show_as { PivotShowAs::Normal => raw, PivotShowAs::PercentOfGrandTotal => ratio(raw, get(&[], &[], *vi)), From fc99483b827995be7e8b8af0ee69133302eb464c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingmar=20L=C3=BCbbe?= Date: Tue, 13 Oct 2026 09:29:46 +0200 Subject: [PATCH 03/13] PivotTables: shares and running totals fill intersections without data, as in Excel Where a row item and a column item have no records together, Excel 365 shows 0 % for % of Grand Total, % of Column Total and % of Row Total, and carries the running total into the cell (0 when nothing came before). GridCraft left these cells empty, because the Show Values As rules ran only for intersections with an aggregate. For Running Total, Excel also leaves the Grand Total line empty; GridCraft filled it with the plain totals. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj --- crates/engine/src/cmd/pivot.rs | 39 ++++++++++++++++++++++++++++++++++ crates/engine/src/pivot.rs | 16 ++++++++------ 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index 55556d4701..54722a74c1 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -1733,6 +1733,45 @@ mod tests { } } + #[test] + fn shares_and_running_totals_fill_intersections_without_data() { + // Region × Product, Sum of Units, laid out at E3 (rows 5-6 East/West, row 7 Grand Total; + // columns F Apple, G Pear, H Grand Total). Values as Excel 365 shows them. + let report = |rows: Json, show: &str| { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap(); + let p = + json!({"source": "Sheet1!$A$1:$C$4", "destination": "Sheet1!E3", "rows": ["Region"], "columns": ["Product"], "values": ["Units"]}); + s.execute("insert.pivotTable", p).unwrap(); + s.execute("pivot.valueSettings", json!({"field": "Units", "showAs": show})).unwrap(); + s + }; + let west_no_pear = json!([["Region", "Product", "Units"], ["East", "Apple", 10], ["East", "Pear", 5], ["West", "Apple", 20]]); + for show in ["percentOfGrandTotal", "percentOfColumnTotal", "percentOfRowTotal"] { + let s = report(west_no_pear.clone(), show); + assert_eq!(text(&s, "E6"), "West"); + assert_eq!(val(&s, "G6"), Value::Number(0.0), "{show}"); + } + let s = report(west_no_pear.clone(), "runningTotal"); + assert_eq!(val(&s, "F6"), Value::Number(30.0)); + assert_eq!(val(&s, "G6"), Value::Number(5.0), "carried forward"); + assert_eq!(val(&s, "H6"), Value::Number(35.0)); + // The grand total line of a running total stays empty. + assert_eq!(text(&s, "E7"), "Grand Total"); + for c in ["F7", "G7", "H7"] { + assert_eq!(val(&s, c), Value::Empty, "{c}"); + } + // Nothing before an empty first item: 0. + let east_no_pear = json!([["Region", "Product", "Units"], ["East", "Apple", 10], ["West", "Apple", 20], ["West", "Pear", 5]]); + let s = report(east_no_pear, "runningTotal"); + assert_eq!(val(&s, "G5"), Value::Number(0.0)); + assert_eq!(val(&s, "G6"), Value::Number(5.0)); + // Shown normally, an empty intersection stays empty. + let s = report(west_no_pear, "normal"); + assert_eq!(val(&s, "G6"), Value::Empty); + } + #[test] fn date_grouping_by_quarter_and_month() { let mut s = sales(); diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index 9f0c5d761d..4421e4dd67 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -1270,18 +1270,22 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result raw, - (Value::Empty, _) => Value::Number(0.0), - _ => raw, + // Shown as a share or a running total, an intersection without records, or with only + // blank values, counts as 0 (Excel 365 shows 0 % and the carried running total there). + let counted = !matches!(vdef.show_as, PivotShowAs::Normal | PivotShowAs::Rank); + let raw = match get(rp, cp, *vi) { + Some(Value::Empty) if counted => Value::Number(0.0), + Some(v) => v, + None if counted => Value::Number(0.0), + None => continue, }; let shown = match vdef.show_as { PivotShowAs::Normal => raw, PivotShowAs::PercentOfGrandTotal => ratio(raw, get(&[], &[], *vi)), PivotShowAs::PercentOfColumnTotal => ratio(raw, get(&[], cp, *vi)), PivotShowAs::PercentOfRowTotal => ratio(raw, get(rp, &[], *vi)), + // Excel leaves a running total's grand total line empty. + PivotShowAs::RunningTotal if line.kind == LineKind::Grand => Value::Empty, PivotShowAs::RunningTotal => match (rp.first(), &raw) { (Some(first), Value::Number(_)) => { let mut acc = 0.0; From 86e2b7028831bc502ec932956db7d515c4247b53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingmar=20L=C3=BCbbe?= Date: Tue, 13 Oct 2026 09:34:13 +0200 Subject: [PATCH 04/13] PivotTables: date groups keep their date order in Excel Every row and column field was written with sortType="ascending", the default of a new field. For a field grouped by days, Excel 365 reads that as an A-to-Z sort of the item labels, so a GridCraft pivot opened and refreshed in Excel showed 01. Aug, 01. Feb, 01. Jan, 15. Jan. Excel's own date groups have no sortType and keep the items' date order. A date group sorted ascending is now written without sortType (its items are written in date order), and a date group without sortType reads back as ascending. Descending and the sort of other fields are written as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj --- crates/xlsx/src/pivot.rs | 11 +++++++++-- crates/xlsx/src/tests/pivot_tests.rs | 28 +++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index ef887ac582..b68fcc125c 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -913,6 +913,10 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn s.push_str(" showAll=\"0\""); if let Some(af) = axis_field(i) { match af.sort { + // A date group's items are written in date order. Excel sorts the labels of a + // sortType="ascending" day group as text ("1-Aug" before "1-Jan"), so ascending is + // left to that order, as Excel writes a date group it hasn't been asked to sort. + PivotSort::Asc if af.date_group != PivotDateGroup::None => {} PivotSort::Asc => s.push_str(" sortType=\"ascending\""), PivotSort::Desc => s.push_str(" sortType=\"descending\""), PivotSort::None => {} @@ -1307,12 +1311,15 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option PivotSort::Asc, Some("descending") => PivotSort::Desc, - _ => PivotSort::None, + _ => unsorted, }; let items = items_of(e); let lab = |it: &El| it.attr_u32("x").and_then(|k| labels.get(k as usize)).cloned(); diff --git a/crates/xlsx/src/tests/pivot_tests.rs b/crates/xlsx/src/tests/pivot_tests.rs index 9aa2dfa3f4..7abeac610d 100644 --- a/crates/xlsx/src/tests/pivot_tests.rs +++ b/crates/xlsx/src/tests/pivot_tests.rs @@ -125,7 +125,7 @@ fn workbook() -> Workbook { source: "SalesTbl".into(), anchor: at("K4"), rows: vec![ - PivotField { source_col: "Date".into(), date_group: PivotDateGroup::Years, sort: PivotSort::None, collapsed_items: vec!["2024".into()] }, + PivotField { source_col: "Date".into(), date_group: PivotDateGroup::Years, sort: PivotSort::Desc, collapsed_items: vec!["2024".into()] }, PivotField { source_col: "Date".into(), date_group: PivotDateGroup::Months, sort: PivotSort::Asc, collapsed_items: vec![] }, ], columns: vec![PivotField { sort: PivotSort::Desc, ..field("Product") }], @@ -594,6 +594,32 @@ fn two_values_without_column_fields_hide_the_values_row() { assert_eq!(back.sheet(1).unwrap().pivots[2], wb.sheet(1).unwrap().pivots[2]); } +#[test] +fn date_groups_sorted_ascending_are_written_without_sort_type() { + // Excel sorts the labels of a day group with sortType="ascending" as text (1-Aug before + // 1-Jan); without the attribute it keeps the items' date order. A date group sorted ascending + // is written without it and read back as ascending; descending is still written. + let mut wb = workbook(); + { + let p = wb.sheet_mut(1).unwrap().pivots.get_mut(1).unwrap(); + p.rows[0].sort = PivotSort::None; + p.rows[1].date_group = PivotDateGroup::Days; + } + let bytes = write_xlsx(&wb).unwrap(); + let t2 = String::from_utf8(unzip(&bytes).get("xl/pivotTables/pivotTable2.xml").unwrap().clone()).unwrap(); + assert!(!t2.contains("sortType=\"ascending\""), "{t2}"); + assert!(t2.contains("sortType=\"descending\""), "{t2}"); + let (back, _) = read_xlsx(&bytes).unwrap(); + let rows = &back.sheet(1).unwrap().pivots[1].rows; + assert_eq!(rows[1].date_group, PivotDateGroup::Days); + assert_eq!(rows[1].sort, PivotSort::Asc); + // A date group has no source order in the file: it reads back in date order. + assert_eq!(rows[0].sort, PivotSort::Asc); + // Other fields keep sortType="ascending". + let t1 = String::from_utf8(unzip(&bytes).get("xl/pivotTables/pivotTable1.xml").unwrap().clone()).unwrap(); + assert!(t1.contains("sortType=\"ascending\""), "{t1}"); +} + #[test] fn values_ahead_of_column_fields_read_last() { let table = r#""#; From cee9a27e7ab026c7ad8163e6d2d0e58a61d724d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingmar=20L=C3=BCbbe?= Date: Tue, 13 Oct 2026 09:39:43 +0200 Subject: [PATCH 05/13] PivotTables: PivotCharts stay PivotCharts in Excel A PivotChart names its PivotTable in . GridCraft wrote it as Sheet2!PivotTable1; Excel 365 binds the chart only when the name starts with a workbook in brackets ([Book.xlsx]Sheet2!PivotTable1), and otherwise opens it as an ordinary chart over fixed cells (Chart.PivotLayout is Nothing). The writer now puts the saved file's name in front (passed down from the save as write_xlsx_named), or a placeholder when there is none: Excel accepts any bracketed name. The reader drops the workbook part, so the model keeps Sheet2!PivotTable1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj --- crates/engine/src/cmd/pivot.rs | 13 +++++++++++++ crates/engine/src/io.rs | 6 +++++- crates/xlsx/src/chart.rs | 29 ++++++++++++++++++++++++----- crates/xlsx/src/lib.rs | 10 ++++++++-- crates/xlsx/src/sheet_write.rs | 2 +- crates/xlsx/src/write.rs | 5 ++++- 6 files changed, 55 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index 54722a74c1..def50e9adf 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -2118,6 +2118,19 @@ mod tests { let (back, _) = gridcraft_xlsx::read_xlsx(&gridcraft_xlsx::write_xlsx(&wb).unwrap()).unwrap(); let si = back.sheet_index("Sheet2").unwrap(); assert_eq!(back.sheet(si).unwrap().charts.first().and_then(|c| c.pivot.clone()).as_deref(), Some("Sheet2!PivotTable1")); + // Excel 365 binds the chart to its PivotTable only when the link names a workbook in + // brackets: the saved file's name, or a placeholder when there is none. + let chart_xml = |bytes: &[u8]| { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut f = z.by_name("xl/charts/chart1.xml").unwrap(); + let mut x = String::new(); + std::io::Read::read_to_string(&mut f, &mut x).unwrap(); + x + }; + let named = chart_xml(&crate::io::save_bytes(&wb, "Q1 Report.xlsx").unwrap()); + assert!(named.contains("[Q1 Report.xlsx]Sheet2!PivotTable1"), "{named}"); + let unnamed = chart_xml(&gridcraft_xlsx::write_xlsx(&wb).unwrap()); + assert!(unnamed.contains("[Workbook.xlsx]Sheet2!PivotTable1"), "{unnamed}"); // Renaming the sheet keeps the link; a refresh still rebinds. s.execute("sheet.rename", json!({"name": "Report"})).unwrap(); assert_eq!(pivot_chart(&s).pivot.as_deref(), Some("Report!PivotTable1")); diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 3e84036cbc..44d88d4698 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -200,7 +200,11 @@ pub fn save_bytes_as(wb: &Workbook, path: &str, kind: FileKind) -> Result gridcraft_xlsx::write_xlsx_as(wb, gridcraft_xlsx::XlsxKind::from_path(path)).map_err(|e| EngineError::Other(e.to_string())), + FileKind::Xlsx => { + // The file name is what a PivotChart's link names the workbook by. + let name = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or_default(); + gridcraft_xlsx::write_xlsx_named(wb, gridcraft_xlsx::XlsxKind::from_path(path), name).map_err(|e| EngineError::Other(e.to_string())) + } FileKind::Xls => { Err(EngineError::Other("Excel 97-2003 (.xls) is supported for import only. Save as .xlsx or another supported export format.".into())) } diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index dee33c83d4..2b9d871ecb 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -236,7 +236,8 @@ pub fn read_chart(root: &El) -> Option { y_title: y_ax.and_then(|a| a.child("title")).and_then(rich_title), source: None, by_rows: false, - pivot: root.path(&["pivotSource", "name"]).map(|n| n.text.trim().to_string()).filter(|n| !n.is_empty()), + // The link without its workbook, which only names the file the chart was saved in. + pivot: root.path(&["pivotSource", "name"]).map(|n| without_book(n.text.trim()).trim().to_string()).filter(|n| !n.is_empty()), }) } @@ -610,17 +611,35 @@ fn axis_xml(a: &Ax<'_>) -> String { s } -/// Chart part XML for a model chart on sheet `si`. -pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart) -> String { +/// A PivotChart link without its workbook: `[Book.xlsx]Sheet2!PivotTable1` → `Sheet2!PivotTable1`. +fn without_book(link: &str) -> &str { + match link.strip_prefix('[') { + Some(rest) => rest.split_once(']').map_or(rest, |(_, r)| r), + None => link, + } +} + +/// A PivotChart's `c:pivotSource` name: its link (`Sheet2!PivotTable1`) with the workbook in +/// brackets in front, replacing any there. Excel 365 binds the chart to its PivotTable only with a +/// bracketed workbook name; any name will do, so without the file's name a placeholder is used. +fn pivot_source_name(link: &str, book: Option<&str>) -> String { + let bare = without_book(link); + let book = book.map(str::trim).filter(|b| !b.is_empty() && !b.contains(['[', ']'])).unwrap_or("Workbook.xlsx"); + format!("[{book}]{bare}") +} + +/// Chart part XML for a model chart on sheet `si`. `book`: the file name of the workbook being +/// written, used in a PivotChart's link. +pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book: Option<&str>) -> String { let mut s = String::from( "\n", ); if (1..=48).contains(&ch.style) { let _ = write!(s, "", ch.style); } - // A PivotChart names its PivotTable (`Sheet2!PivotTable1`). + // A PivotChart names its PivotTable with the workbook (`[Book.xlsx]Sheet2!PivotTable1`). if let Some(link) = ch.pivot.as_deref().map(str::trim).filter(|l| !l.is_empty()) { - let _ = write!(s, "{}", esc(link)); + let _ = write!(s, "{}", esc(&pivot_source_name(link, book))); } s.push_str(""); match &ch.title { diff --git a/crates/xlsx/src/lib.rs b/crates/xlsx/src/lib.rs index 3300f97fe5..35c9bd932e 100644 --- a/crates/xlsx/src/lib.rs +++ b/crates/xlsx/src/lib.rs @@ -130,12 +130,18 @@ impl XlsxKind { /// Writes a workbook as an `.xlsx` package, or as an `.xlsm` one when it holds a VBA project. pub fn write_xlsx(wb: &Workbook) -> Result, IoError> { - write::write_xlsx(wb, if wb.vba_project.is_some() { XlsxKind::MacroWorkbook } else { XlsxKind::Workbook }) + write::write_xlsx(wb, if wb.vba_project.is_some() { XlsxKind::MacroWorkbook } else { XlsxKind::Workbook }, None) } /// Writes a workbook as the given member of the `.xlsx` family. pub fn write_xlsx_as(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { - write::write_xlsx(wb, kind) + write::write_xlsx(wb, kind, None) +} + +/// [`write_xlsx_as`] for a file named `file_name` (`Book.xlsx`): links that name the workbook +/// itself, such as a PivotChart's link to its PivotTable, use that name. +pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, file_name: &str) -> Result, IoError> { + write::write_xlsx(wb, kind, Some(file_name)) } /// CSV import options. diff --git a/crates/xlsx/src/sheet_write.rs b/crates/xlsx/src/sheet_write.rs index 78e1afaaef..f065d03a45 100644 --- a/crates/xlsx/src/sheet_write.rs +++ b/crates/xlsx/src/sheet_write.rs @@ -522,7 +522,7 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( drels.add_uri(crate::chartex::REL_CHARTEX, &format!("../charts/chartEx{n}.xml")) } else { let name = format!("xl/charts/chart{}.xml", out.charts); - out.part(&name, Some(CT_CHART), crate::chart::write_chart(wb, si, ch).into_bytes()); + out.part(&name, Some(CT_CHART), crate::chart::write_chart(wb, si, ch, out.book_name.as_deref()).into_bytes()); drels.add("chart", &format!("../charts/chart{}.xml", out.charts)) }; objs.push(Obj::Chart(ch, rid)); diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 06761f01d2..74ccbb4c34 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -126,6 +126,8 @@ pub struct Out { pub cell_pictures: crate::richdata::PicturesOut, /// Kept (pass-through) parts written so far. pub kept: crate::passthrough::KeptOut, + /// File name of the workbook being written, for links that name it (a PivotChart's PivotTable). + pub book_name: Option, } impl Out { @@ -185,7 +187,7 @@ fn check_sheet_names(wb: &Workbook) -> Result<(), IoError> { Ok(()) } -pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { +pub fn write_xlsx(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) -> Result, IoError> { if wb.sheets.is_empty() { return Err(IoError::Format("a workbook needs at least one sheet".into())); } @@ -211,6 +213,7 @@ pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { needs_calc: false, cell_pictures: Default::default(), kept: Default::default(), + book_name: book_name.map(str::to_string), }; out.default_type("rels", "application/vnd.openxmlformats-package.relationships+xml"); out.default_type("xml", "application/xml"); From 6c65d3dd8331fd64bf02b6462ac24edb0334e08e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingmar=20L=C3=BCbbe?= Date: Tue, 13 Oct 2026 13:59:27 +0200 Subject: [PATCH 06/13] PivotTables: caption cells of pivots without row fields, with values on rows, and in outline, as in Excel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Laid out as Excel 365 refreshes them: - Column fields and one value field, no row field: the value's caption labels the data line (A5), not the top-left cell (A3). - Column fields and two or more value fields, no row field: there is no label column; the report starts with the first column item (firstDataCol 0). - Σ Values on rows without a column field: the data column has no header. GridCraft wrote "Total" there; Excel leaves it empty after a refresh. - Outline and tabular: the caption row names every column field, Σ Values as "Values" (B3 Product, C3 Values); GridCraft named only the first. - With headers off, a caption row that would be empty is left out (columns only, one value). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj --- crates/engine/src/cmd/pivot.rs | 79 +++++++++++++++++++++++++++- crates/engine/src/pivot.rs | 40 +++++++++----- crates/xlsx/src/pivot.rs | 12 +++-- crates/xlsx/src/tests/pivot_tests.rs | 19 +++++++ 4 files changed, 130 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index def50e9adf..1f7d88fc01 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -1772,6 +1772,81 @@ mod tests { assert_eq!(val(&s, "G6"), Value::Empty); } + #[test] + fn captions_without_row_fields_and_with_values_on_rows() { + // Cell for cell what Excel 365 shows after a refresh, in all three layouts. + for layout in ["compact", "outline", "tabular"] { + // Column fields, one value field: the caption labels the data line (A5), not A3. + let mut s = sales(); + s.execute("insert.pivotTable", json!({"columns": ["Region"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.layout", json!({"layout": layout})).unwrap(); + assert_eq!(val(&s, "A3"), Value::Empty, "{layout}"); + assert_eq!(text(&s, "B4"), "East", "{layout}"); + assert_eq!(text(&s, "A5"), "Sum of Sales", "{layout}"); + assert_eq!(val(&s, "B5"), Value::Number(415.0), "{layout}"); + // Column fields, two value fields: no label column, the items start in A. + let mut s = sales(); + s.execute("insert.pivotTable", json!({"columns": ["Region"], "values": ["Sales", "Units"]})).unwrap(); + s.execute("pivot.layout", json!({"layout": layout})).unwrap(); + assert_eq!(text(&s, "A4"), "East", "{layout}"); + assert_eq!(text(&s, "A5"), "Sum of Sales", "{layout}"); + assert_eq!(text(&s, "B5"), "Sum of Units", "{layout}"); + assert_eq!(val(&s, "A6"), Value::Number(415.0), "{layout}"); + assert_eq!(pt(&s).last_range.unwrap().a1(), "A3:H6", "{layout}"); + // Σ Values on rows without a column field: the data column has no header. + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales", "Units"]})).unwrap(); + s.execute("pivot.moveField", json!({"field": "Σ Values", "from": "columns", "to": "rows"})).unwrap(); + s.execute("pivot.layout", json!({"layout": layout})).unwrap(); + let last = pt(&s).last_range.unwrap(); + assert_eq!(val(&s, &CellRef::new(last.start.row, last.end.col).a1()), Value::Empty, "{layout}"); + } + } + + #[test] + fn outline_caption_row_names_every_column_field() { + // Outline and tabular name each column field in the caption row, Σ Values as "Values" + // (Excel 365: B3 Region, C3 Product; with two values B3 Product, C3 Values). + let mut s = sales(); + s.execute("insert.pivotTable", json!({"columns": ["Region", "Product"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.layout", json!({"layout": "outline"})).unwrap(); + assert_eq!(text(&s, "B3"), "Region"); + assert_eq!(text(&s, "C3"), "Product"); + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales", "Units"]})).unwrap(); + s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap(); + assert_eq!(text(&s, "B3"), "Product"); + assert_eq!(text(&s, "C3"), "Values"); + // Compact keeps the one "Column Labels" caption. + s.execute("pivot.layout", json!({"layout": "compact"})).unwrap(); + assert_eq!(text(&s, "B3"), "Column Labels"); + assert_eq!(val(&s, "C3"), Value::Empty); + } + + #[test] + fn headers_off_leave_out_an_empty_caption_row() { + // With headers off, Excel 365 drops the caption row above the column items unless it holds + // the value's caption (one value field and row fields). + let mut s = sales(); + s.execute("insert.pivotTable", json!({"columns": ["Region"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.layout", json!({"showHeaders": false})).unwrap(); + assert_eq!(text(&s, "B3"), "East"); + assert_eq!(text(&s, "A4"), "Sum of Sales"); + assert_eq!(pt(&s).last_range.unwrap().a1(), "A3:E4"); + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales", "Units"]})).unwrap(); + s.execute("pivot.layout", json!({"showHeaders": false})).unwrap(); + assert_eq!(text(&s, "B3"), "Apples"); + assert_eq!(text(&s, "B4"), "Sum of Sales"); + assert_eq!(text(&s, "A5"), "East"); + // One value field with row fields: the caption row keeps the value's caption. + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.layout", json!({"showHeaders": false})).unwrap(); + assert_eq!(text(&s, "A3"), "Sum of Sales"); + assert_eq!(text(&s, "B4"), "Apples"); + } + #[test] fn date_grouping_by_quarter_and_month() { let mut s = sales(); @@ -1916,11 +1991,11 @@ mod tests { assert_eq!(val(&s, "B13"), Value::Number(TOTAL)); assert_eq!(text(&s, "A14"), "Total Sum of Units"); assert_eq!(val(&s, "B14"), Value::Number(72.0)); - // Tabular, no column field: "Total" heads the data column, as Excel saves it. + // Tabular, no column field: the data column has no header (Excel 365 refreshes it empty). s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap(); assert_eq!(text(&s, "A3"), "Region"); assert_eq!(text(&s, "B3"), "Values"); - assert_eq!(text(&s, "C3"), "Total"); + assert_eq!(val(&s, "C3"), Value::Empty); s.execute("pivot.layout", json!({"layout": "compact"})).unwrap(); // Σ Values before Region: the value fields are the outer items. s.execute("pivot.moveField", json!({"field": "Values", "from": "rows", "to": "rows", "position": 0})).unwrap(); diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index 4421e4dd67..5246b420cb 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -963,7 +963,12 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result = Vec::new(); if row_levels == 0 { - lines.push(Line { kind: LineKind::Item(false), leaf: true, path: vec![], values: true, labels: vec![], vi: None }); + // Column fields and one value field: Excel labels the data line with the value's caption. + let labels = match val_names.first() { + Some(name) if k == 1 && !cols.is_empty() => vec![(0, Value::text(name.as_str()), 0, None)], + _ => vec![], + }; + lines.push(Line { kind: LineKind::Item(false), leaf: true, path: vec![], values: true, labels, vi: None }); } else { if pt.layout == PivotLayout::Tabular { ctx.flatten_tabular(&row_tree, 0, None, &mut Vec::new(), &[], &mut lines); @@ -1016,7 +1021,10 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result 1) { 0 } else if compact { 1 @@ -1091,27 +1099,33 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result g.set(r, l + j, Value::text(val_name(*vi)), CellKind::Header, 0, None), - // Values on rows, no column field: the one data column is the grand total. - None if on_rows => g.set(r, l + j, Value::text("Total"), CellKind::Header, 0, None), - None => {} + if let Some(vi) = vi { + g.set(r, l + j, Value::text(val_name(*vi)), CellKind::Header, 0, None); } } } else { - // The caption row holds the value field's caption (one value field) and, with headers - // shown, the column caption. With headers off and nothing to show in it, Excel leaves it out. - let value_caption = l > 0 && k == 1; + // The caption row holds the value field's caption (one value field, with row fields; without + // them the caption labels the data line instead, see `lines`) and, with headers shown, the + // column caption. With headers off and nothing to show in it, Excel leaves it out. + let value_caption = l > 0 && k == 1 && row_levels > 0; if value_caption || headers_on { let cap = g.push_row(RowKind::Header)?; if value_caption { g.set(cap, 0, Value::text(val_name(0)), CellKind::Header, 0, None); } if headers_on { - let caption = - if compact { "Column Labels".to_string() } else { col_fields.first().map(|f| f.source_col.clone()).unwrap_or_default() }; - g.set(cap, l, Value::text(caption), CellKind::Header, 0, None); + // Compact: "Column Labels". Outline and tabular name each column field from the + // first data column on, Σ Values as "Values". + let names: Vec = if compact { + vec!["Column Labels".to_string()] + } else { + col_fields.iter().map(|f| f.source_col.clone()).chain(values_in_cols.then(|| "Values".to_string())).collect() + }; + for (i, name) in names.into_iter().enumerate() { + g.set(cap, l + i, Value::text(name), CellKind::Header, 0, None); + } } } let levels = cols.len() + usize::from(values_in_cols); diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index b68fcc125c..9e4e6b3b42 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -840,16 +840,18 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn let row_levels = row_idx.len() + usize::from(row_values.is_some()); // Σ Values alone in Columns: its row is hidden (hideValuesRow, below), so the value captions are // the header row, which Excel 365 counts as row 0. Column fields take a row each, Σ Values among - // them, below a caption row. The caption row holds the value's caption (one value field) and, - // with headers shown, the column caption; Excel leaves it out when it would be empty - // (firstHeaderRow 0). + // them, below a caption row. The caption row holds the value's caption (one value field and row + // fields) and, with headers shown, the column caption; Excel leaves it out when it would be + // empty (firstHeaderRow 0). let (first_header_row, first_data_row) = if col_idx.is_empty() { (usize::from(col_values.is_none()), 1) } else { - let caption_row = pt.show_headers || k == 1; + let caption_row = pt.show_headers || (k == 1 && row_levels > 0); (usize::from(caption_row), usize::from(caption_row) + col_idx.len() + usize::from(col_values.is_some())) }; - let first_data_col = if row_levels == 0 && col_idx.is_empty() { + // No row fields: no label column, unless column fields hold one value field (its caption + // labels the data line). + let first_data_col = if row_levels == 0 && (col_idx.is_empty() || col_values.is_some()) { 0 } else if compact { 1 diff --git a/crates/xlsx/src/tests/pivot_tests.rs b/crates/xlsx/src/tests/pivot_tests.rs index 7abeac610d..9520d49443 100644 --- a/crates/xlsx/src/tests/pivot_tests.rs +++ b/crates/xlsx/src/tests/pivot_tests.rs @@ -620,6 +620,25 @@ fn date_groups_sorted_ascending_are_written_without_sort_type() { assert!(t1.contains("sortType=\"ascending\""), "{t1}"); } +#[test] +fn column_fields_with_two_values_and_no_row_fields_have_no_label_column() { + // Excel 365 writes firstDataRow="3" firstDataCol="0" for Region in Columns with two values. + let mut wb = workbook(); + { + let p = wb.sheet_mut(1).unwrap().pivots.get_mut(2).unwrap(); + p.columns = std::mem::take(&mut p.rows); + p.values.push(PivotValue { source_col: "Sales".into(), func: PivotFunc::Sum, name: "Sum of Sales".into(), ..PivotValue::default() }); + } + 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=\"3\" firstDataCol=\"0\""), "{t3}"); + // With one value field its caption labels the data line in the first column. + wb.sheet_mut(1).unwrap().pivots[2].values.pop(); + 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\" firstDataCol=\"1\""), "{t3}"); +} + #[test] fn values_ahead_of_column_fields_read_last() { let table = r#""#; From ebe4742281fae0e842bd2ebd9f3ee62bf52f580e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingmar=20L=C3=BCbbe?= Date: Tue, 13 Oct 2026 09:52:34 +0200 Subject: [PATCH 07/13] PivotTables: Excel opens files whose pivot source has TRUE/FALSE or error values A pivot cache field's flags said containsString="0" for a column holding booleans or errors, and containsMixedTypes="1" for text mixed with booleans. Excel 365 counts booleans and errors as strings in these flags and can't open a file that contradicts its own items, not even with repair; any such column in the source was enough, used in the pivot or not. The flags are now written as Excel writes them: strings are text, booleans and errors; containsString="0" and containsSemiMixedTypes="0" only without them, and mixed types only for strings together with numbers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj --- crates/xlsx/src/pivot.rs | 16 ++++-- crates/xlsx/src/tests/pivot_tests.rs | 80 ++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 5 deletions(-) diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index 9e4e6b3b42..fc00d5a0e0 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -210,8 +210,13 @@ impl Stats { Value::Array(_) => self.add(&v.scalar()), } } + /// Text, booleans or errors: Excel counts all three as strings in a cache field's flags. + fn strings(&self) -> bool { + self.text || self.boolean || self.error + } + /// Kinds of values for `containsMixedTypes`: strings (text, booleans, errors) and numbers. fn kinds(&self) -> usize { - [self.text, self.number, self.boolean, self.error].iter().filter(|b| **b).count() + usize::from(self.strings()) + usize::from(self.number) } } @@ -572,7 +577,7 @@ fn build_cache(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Option, sys: DateSystem) -> String { } let _ = g; } else { - let semi = st.text || st.blank || st.boolean || st.error; - if !semi { + // Flags as Excel 365 writes them; it refuses a file whose flags deny the booleans + // or errors among the items (containsString="0" next to or ). + if !st.strings() && !st.blank { s.push_str(" containsSemiMixedTypes=\"0\""); } - if !st.text { + if !st.strings() { s.push_str(" containsString=\"0\""); } if st.blank { diff --git a/crates/xlsx/src/tests/pivot_tests.rs b/crates/xlsx/src/tests/pivot_tests.rs index 9520d49443..2642478e27 100644 --- a/crates/xlsx/src/tests/pivot_tests.rs +++ b/crates/xlsx/src/tests/pivot_tests.rs @@ -639,6 +639,86 @@ fn column_fields_with_two_values_and_no_row_fields_have_no_label_column() { assert!(t3.contains("firstHeaderRow=\"1\" firstDataRow=\"2\" firstDataCol=\"1\""), "{t3}"); } +#[test] +fn cache_flags_count_booleans_and_errors_as_strings() { + // The columns of an Excel 365 reference workbook, with the flags Excel writes for them. A + // file with containsString="0" next to or items can't be opened by Excel at all. + let mut wb = Workbook::new(); + let rows: [[Value; 7]; 5] = [ + ["Name", "BoolOnly", "NumBool", "ErrOnly", "NumErr", "TextBool", "BoolBlank"].map(Value::text), + [ + Value::text("a"), + Value::Bool(true), + Value::number(1.0), + Value::Error(gridcraft_core::CellError::Div0), + Value::number(1.0), + Value::text("x"), + Value::Bool(true), + ], + [ + Value::text("b"), + Value::Bool(false), + Value::Bool(true), + Value::Error(gridcraft_core::CellError::Div0), + Value::Error(gridcraft_core::CellError::NA), + Value::Bool(true), + Value::Empty, + ], + [ + Value::text("c"), + Value::Bool(true), + Value::number(2.5), + Value::Error(gridcraft_core::CellError::Div0), + Value::number(3.0), + Value::text("y"), + Value::Bool(false), + ], + [ + Value::text("d"), + Value::Bool(false), + Value::Bool(false), + Value::Error(gridcraft_core::CellError::Div0), + Value::Error(gridcraft_core::CellError::Div0), + Value::Bool(false), + Value::Bool(true), + ], + ]; + let data = wb.sheet_mut(0).unwrap(); + for (r, row) in rows.iter().enumerate() { + for (c, v) in row.iter().enumerate() { + if !v.is_empty() { + data.cells.set(CellRef::new(r as u32, c as u32), Cell::value(v.clone())); + } + } + } + data.pivots.push(PivotTable { + name: "Types".into(), + source: "Sheet1!$A$1:$G$5".into(), + anchor: at("J3"), + rows: vec![field("Name")], + values: vec![PivotValue { source_col: "Name".into(), func: PivotFunc::Count, name: "Count of Name".into(), ..PivotValue::default() }], + last_range: Some(rr("J3:K8")), + ..PivotTable::default() + }); + let parts = unzip(&write_xlsx(&wb).unwrap()); + let c = String::from_utf8(parts.get("xl/pivotCache/pivotCacheDefinition1.xml").unwrap().clone()).unwrap(); + let flags = |name: &str| -> String { + let at = c.find(&format!("').unwrap(); + c[si..end].split(" count=").next().unwrap().trim_end_matches('/').to_string() + }; + assert_eq!(flags("BoolOnly"), ""#; From 49a4f7221fc710be3c35c5335da9f32e438de758 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingmar=20L=C3=BCbbe?= Date: Tue, 13 Oct 2026 09:58:18 +0200 Subject: [PATCH 08/13] PivotTables: source headers keep their spaces, so fields don't vanish on refresh or save A source header with leading or trailing spaces ("Region ") names its field with the spaces in Excel, in the cache and in the layout. GridCraft trimmed headers when reading the source and when writing the cache, while the fields read from an Excel file kept the spaces, so the layout no longer found them: a refresh dropped the field, and even a plain open and save wrote the pivot without its row fields and value fields. Headers are now taken as they are, as Excel does. A name typed without the spaces (pivot.addField {"field": "Region"}) still finds the field when only one header matches that way, and is stored with the header's spelling. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj --- crates/engine/src/cmd/pivot.rs | 30 ++++++++++++++++++++++++++++++ crates/engine/src/pivot.rs | 16 +++++++++++++--- crates/xlsx/src/pivot.rs | 6 ++++-- 3 files changed, 47 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index 1f7d88fc01..d5fc031187 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -1847,6 +1847,36 @@ mod tests { assert_eq!(text(&s, "B4"), "Apples"); } + #[test] + fn headers_keep_their_spaces() { + // Excel names a field by its header exactly ("Region "), in the cache and in the layout. + let mut s = Session::new(); + s.new_workbook(); + let rows = json!([["Region ", " Sales ", "Qty"], ["East", 10, 1], ["West", 20, 2], ["East", 5, 3]]); + s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap(); + // Typed without the spaces, the fields are still found, and kept with them. + let p = json!({"source": "Sheet1!$A$1:$C$4", "destination": "Sheet1!E3", "rows": ["Region"], "values": ["Sales", "Qty"]}); + s.execute("insert.pivotTable", p).unwrap(); + let p = pt(&s); + assert_eq!(p.rows[0].source_col, "Region "); + assert_eq!(p.values[0].source_col, " Sales "); + let east = find_row(&s, "East").unwrap(); + assert_eq!(val(&s, &CellRef::new(east, 5).a1()), Value::Number(15.0)); + let f = s.execute("pivot.fields", json!({})).unwrap(); + assert!(f["fields"].as_array().unwrap().iter().any(|x| x["name"] == "Region "), "{f}"); + // Saved and reopened, the layout still finds its fields, and a refresh keeps them. + let wb = (*s.doc().unwrap().wb).clone(); + let (back, report) = gridcraft_xlsx::read_xlsx(&gridcraft_xlsx::write_xlsx(&wb).unwrap()).unwrap(); + assert!(report.warnings.iter().all(|w| !w.to_lowercase().contains("pivot")), "{:?}", report.warnings); + let rp = back.sheet(0).unwrap().pivots.first().unwrap().clone(); + assert_eq!((rp.rows.len(), rp.values.len()), (1, 2)); + assert_eq!(rp.rows[0].source_col, "Region "); + let mut back = back; + crate::pivot::refresh(&mut back, 0, 0, true).unwrap(); + let out = crate::pivot::compute(&back, back.sheet(0).unwrap().pivots.first().unwrap(), 0).unwrap(); + assert!(out.grid.iter().any(|row| row.first().is_some_and(|c| c.value == Value::text("East")))); + } + #[test] fn date_grouping_by_quarter_and_month() { let mut s = sales(); diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index 5246b420cb..b80191f00d 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -42,8 +42,17 @@ pub struct Source { } impl Source { + /// The column of a field. Headers keep their spaces, as in Excel (`Region `); a name typed + /// without them still finds the field when only one header matches that way. pub fn col(&self, name: &str) -> Option { - self.headers.iter().position(|h| h.eq_ignore_ascii_case(name)) + self.headers.iter().position(|h| h.eq_ignore_ascii_case(name)).or_else(|| { + let name = name.trim(); + let mut hits = self.headers.iter().enumerate().filter(|(_, h)| h.trim().eq_ignore_ascii_case(name)); + match (hits.next(), hits.next()) { + (Some((i, _)), None) => Some(i), + _ => None, + } + }) } } @@ -134,8 +143,9 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result = HashMap::new(); let mut formats = Vec::new(); for c in r.start.col..=r.end.col { - let h = crate::display::cell_text(wb, sh, CellRef::new(r.start.row, c)).trim().to_string(); - if h.is_empty() { + // A field is named by its header exactly, spaces included, as in Excel and in the cache. + let h = crate::display::cell_text(wb, sh, CellRef::new(r.start.row, c)); + if h.trim().is_empty() { return Err(FIELD_NAME_ERR.into()); } let key = h.to_ascii_lowercase(); diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index fc00d5a0e0..d70c4a8c3f 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -412,10 +412,12 @@ fn range_source_xml(sheet: &str, r: RangeRef) -> String { format!("", r.a1(), esc_attr(&name)) } +/// A source header as a cache field name: the text as it is, spaces included (as Excel names it, +/// and as the PivotTable's fields refer to it). fn header_text(v: &Value) -> String { match v { Value::Empty => String::new(), - v => label(v).trim().to_string(), + v => label(v), } } @@ -431,7 +433,7 @@ fn build_cache(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Option = HashMap::new(); for (k, c) in (r.start.col..=r.end.col).enumerate() { let mut h = header_text(&sh.value(CellRef::new(r.start.row, c)).scalar()); - if h.is_empty() { + if h.trim().is_empty() { h = format!("Column{}", k + 1); } let mut n = h.clone(); From 718e13bf497433a003f9597b8ce862375e307bab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingmar=20L=C3=BCbbe?= Date: Tue, 13 Oct 2026 10:01:42 +0200 Subject: [PATCH 09/13] PivotTables: a single-item report filter reads the item Excel selected pageField@item is an index into the pivot field's ; the item there names the shared item with its x. GridCraft took it as an index into the cache's shared items, so a filter on Qty = 3 read back as Qty = 2 whenever Excel's items weren't in shared-item order, and an open and save wrote that wrong item back, changing the report's values in Excel. The reader now goes through the field's items. The writer was right already: it writes the items in shared-item order, so its index and the shared item agree. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj --- crates/xlsx/src/pivot.rs | 9 ++++++++- crates/xlsx/src/tests/pivot_tests.rs | 10 ++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index d70c4a8c3f..5fddcb96c2 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -973,6 +973,7 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn && let Some(one) = sel.first() && let Some(x) = c.fields.get(*i).and_then(|cf| cf.item_labels().iter().position(|l| same(l, one))) { + // An index into the field's , which are written in shared-item order. let _ = write!(s, " item=\"{x}\""); } s.push_str(" hier=\"-1\"/>"); @@ -1351,7 +1352,13 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option; that item's `x` is the shared item. Only + // a field written without items falls back to the shared items' order. + let shared = match pf(i).and_then(|e| e.child("items")) { + Some(items) => items.kids("item").nth(k as usize).and_then(|it| it.attr_u32("x")), + None => Some(k), + }; + shared.and_then(|x| labels.get(x as usize)).map(|l| vec![l.clone()]) } else { pf(i).and_then(|e| { let items = items_of(e); diff --git a/crates/xlsx/src/tests/pivot_tests.rs b/crates/xlsx/src/tests/pivot_tests.rs index 2642478e27..3559917683 100644 --- a/crates/xlsx/src/tests/pivot_tests.rs +++ b/crates/xlsx/src/tests/pivot_tests.rs @@ -719,6 +719,16 @@ fn cache_flags_count_booleans_and_errors_as_strings() { assert_eq!(back.sheet(0).unwrap().pivots.len(), 1); } +#[test] +fn report_filter_item_indexes_the_fields_items() { + // pageField@item points into the pivot field's , whose x is the shared item. Excel + // writes items in its own order, so item="1" here is , the shared item "x". + let table = r#""#; + let (wb, _) = read_xlsx(&with_pivot(table, Some(GOOD_CACHE))).unwrap(); + let pt = &wb.sheet(0).unwrap().pivots[0]; + assert_eq!(pt.filters, vec![PivotFilter { source_col: "K".into(), selected: Some(vec!["x".into()]) }]); +} + #[test] fn values_ahead_of_column_fields_read_last() { let table = r#""#; From b46332a1c9bc15e0c2b20182b5e456be31e9f2a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingmar=20L=C3=BCbbe?= Date: Tue, 13 Oct 2026 10:03:58 +0200 Subject: [PATCH 10/13] PivotTables: date groups over a column with blank cells stay grouped in Excel The cache field of a date grouping was always written with containsSemiMixedTypes="0", also next to containsBlank="1". Excel 365 then dropped the grouping when it refreshed a GridCraft file whose date column had a blank cell: a pivot by months showed every single date instead. As Excel writes it, a date column with blanks is semi-mixed: containsSemiMixedTypes="0" is now written only when the column has no blank cells. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj --- crates/xlsx/src/pivot.rs | 7 ++++++- crates/xlsx/src/tests/pivot_tests.rs | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index 5fddcb96c2..9019044aea 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -709,7 +709,12 @@ fn cache_xml(c: &Cache, records_rid: Option<&str>, sys: DateSystem) -> String { if f.col.is_some() { s.push_str(" String { + let parts = unzip(&write_xlsx(wb).unwrap()); + let c = String::from_utf8(parts.get("xl/pivotCache/pivotCacheDefinition2.xml").unwrap().clone()).unwrap(); + let at = c.find(""#; From 6e4e13033b6b670ea1b4e29b76e95af750e9e70d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingmar=20L=C3=BCbbe?= Date: Tue, 13 Oct 2026 10:08:01 +0200 Subject: [PATCH 11/13] PivotTables: Rank Largest to Smallest gives tied values the same rank, as in Excel Excel 365 ranks densely: values 5, 4, 3, 3, 4 rank 1, 2, 3, 3, 2. GridCraft counted every larger sibling, so the same values ranked 1, 2, 4, 4, 2. A value's rank is now one more than the number of distinct larger values among its siblings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj --- crates/engine/src/cmd/pivot.rs | 16 ++++++++++++++++ crates/engine/src/pivot.rs | 10 ++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index d5fc031187..a9d7914e78 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -1877,6 +1877,22 @@ mod tests { assert!(out.grid.iter().any(|row| row.first().is_some_and(|c| c.value == Value::text("East")))); } + #[test] + fn rank_ties_share_a_rank_and_the_next_follows() { + // Excel 365, Rank Largest to Smallest: 5, 4, 3, 3, 4 rank 1, 2, 3, 3, 2 (dense). + let mut s = Session::new(); + s.new_workbook(); + let rows = json!([["Key", "Val"], ["A", 5], ["B", 4], ["C", 3], ["D", 3], ["E", 4]]); + s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap(); + s.execute("insert.pivotTable", json!({"source": "Sheet1!$A$1:$B$6", "destination": "Sheet1!E3", "rows": ["Key"], "values": ["Val"]})) + .unwrap(); + s.execute("pivot.valueSettings", json!({"field": "Val", "showAs": "rank"})).unwrap(); + for (key, rank) in [("A", 1.0), ("B", 2.0), ("C", 3.0), ("D", 3.0), ("E", 2.0)] { + let r = find_row(&s, key).unwrap(); + assert_eq!(val(&s, &CellRef::new(r, 5).a1()), Value::Number(rank), "{key}"); + } + } + #[test] fn date_grouping_by_quarter_and_month() { let mut s = sales(); diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index b80191f00d..a56be1be34 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -1329,16 +1329,18 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result match (rp.split_last(), raw.as_f64()) { (Some((_, parent)), Some(me)) => { + // Dense ranks, as Excel gives them: ties share a rank and the next value + // takes the next one (5, 4, 4, 3 rank 1, 2, 2, 3). let sibs = siblings.get(parent).cloned().unwrap_or_default(); - let mut rank = 1u64; + let mut greater: HashSet = HashSet::new(); for sib in sibs { let mut p = parent.to_vec(); p.push(sib); - if num(&get(&p, cp, *vi)).is_some_and(|x| x > me) { - rank += 1; + if let Some(x) = num(&get(&p, cp, *vi)).filter(|x| *x > me) { + greater.insert(if x == 0.0 { 0 } else { x.to_bits() }); } } - Value::number(rank as f64) + Value::number(greater.len() as f64 + 1.0) } (None, _) => Value::Empty, _ => raw, From 5f9581d64d43e0d78828aa4526ab03884826a454 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingmar=20L=C3=BCbbe?= Date: Tue, 13 Oct 2026 10:17:50 +0200 Subject: [PATCH 12/13] =?UTF-8?q?PivotTables:=20value=20captions=20come=20?= =?UTF-8?q?from=20one=20table=20and=20match=20Excel=20(Count=20Numbers=20?= =?UTF-8?q?=E2=86=92=20"Count=20of")?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The caption word and the names of the summary functions lived in three places: the engine's func_caption, the XLSX writer's func_caption/func_name/func_from, and the commands' func_param/ func_name. They had drifted: a new Count Numbers value field was captioned "Count Numbers of Units" by the engine, while Excel 365 (and the XLSX reader's fallback) say "Count of Units" (German Excel: "Anzahl von Units", the same as for Count). PivotFunc now holds them: caption() with Excel's words for all 11 functions, name() for commands and listings, file_name() for dataField@subtotal, and parse() for all of these plus the aliases the commands accepted. The engine and the XLSX reader and writer use them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj --- crates/engine/src/cmd/pivot.rs | 63 +++++++++------------- crates/engine/src/pivot.rs | 17 ------ crates/model/src/features.rs | 95 ++++++++++++++++++++++++++++++++++ crates/xlsx/src/pivot.rs | 57 ++------------------ 4 files changed, 124 insertions(+), 108 deletions(-) diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index a9d7914e78..7338563d78 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -245,39 +245,6 @@ fn area_param(cmd: &str, v: Option<&str>) -> Result<&'static str> { } } -fn func_param(v: Option<&str>) -> Option { - Some(match v?.to_ascii_lowercase().as_str() { - "sum" => PivotFunc::Sum, - "count" | "counta" => PivotFunc::Count, - "average" | "avg" | "mean" => PivotFunc::Average, - "max" => PivotFunc::Max, - "min" => PivotFunc::Min, - "product" => PivotFunc::Product, - "countnumbers" | "countnums" | "count numbers" => PivotFunc::CountNumbers, - "stddev" => PivotFunc::StdDev, - "stddevp" => PivotFunc::StdDevP, - "var" => PivotFunc::Var, - "varp" => PivotFunc::VarP, - _ => return None, - }) -} - -fn func_name(f: PivotFunc) -> &'static str { - match f { - PivotFunc::Sum => "sum", - PivotFunc::Count => "count", - PivotFunc::Average => "average", - PivotFunc::Max => "max", - PivotFunc::Min => "min", - PivotFunc::Product => "product", - PivotFunc::CountNumbers => "countNumbers", - PivotFunc::StdDev => "stdDev", - PivotFunc::StdDevP => "stdDevP", - PivotFunc::Var => "var", - PivotFunc::VarP => "varP", - } -} - fn show_as_param(v: &str) -> Option { Some(match v.to_ascii_lowercase().as_str() { "normal" | "none" => PivotShowAs::Normal, @@ -425,7 +392,7 @@ fn unique_value_name(pt: &PivotTable, base: &str, except: Option) -> Stri } fn auto_name(f: PivotFunc, field: &str) -> String { - format!("{} of {field}", pv::func_caption(f)) + format!("{} of {field}", f.caption()) } /// Adds `field` to an area (moving it out of the other axis areas). @@ -675,7 +642,16 @@ fn insert_pivot(s: &mut Session, p: &Json) -> Result { Json::String(n) => add_to_area("insert.pivotTable", pt, &src, n, area, None, None, None)?, Json::Object(_) => { let n = str_param(f, "field").ok_or_else(|| bad("insert.pivotTable", "a field object needs `field`"))?; - add_to_area("insert.pivotTable", pt, &src, n, area, func_param(str_param(f, "func")), str_param(f, "name"), None)?; + add_to_area( + "insert.pivotTable", + pt, + &src, + n, + area, + str_param(f, "func").and_then(PivotFunc::parse), + str_param(f, "name"), + None, + )?; let by = group_param(str_param(f, "group")); if let Some(by) = by.filter(|b| *b != PivotDateGroup::None) && matches!(area, "rows" | "columns") @@ -746,7 +722,7 @@ fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json { "source": pt.source, "rows": pt.rows.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::>(), "columns": pt.columns.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::>(), - "values": pt.values.iter().map(|v| json!({"field": v.source_col, "func": func_name(v.func), "name": v.name, "showAs": show_as_name(v.show_as), "numberFormat": v.number_format})).collect::>(), + "values": pt.values.iter().map(|v| json!({"field": v.source_col, "func": v.func.name(), "name": v.name, "showAs": show_as_name(v.show_as), "numberFormat": v.number_format})).collect::>(), "filters": pt.filters.iter().map(|f| json!({"field": f.source_col, "selected": f.selected, "report": !in_axes(pt, &f.source_col)})).collect::>(), "layout": layout_name(pt.layout), "grandTotalsRows": pt.grand_totals_rows, @@ -835,7 +811,7 @@ fn add_field(s: &mut Session, p: &Json) -> Result { let field = str_param(p, "field").ok_or_else(|| bad(C, "missing `field`"))?.to_string(); let area = area_param(C, str_param(p, "area"))?; let func = match str_param(p, "func") { - Some(f) => Some(func_param(Some(f)).ok_or_else(|| bad(C, format!("unknown function `{f}`")))?), + Some(f) => Some(PivotFunc::parse(f).ok_or_else(|| bad(C, format!("unknown function `{f}`")))?), None => None, }; let name = str_param(p, "name").map(str::to_string); @@ -1014,7 +990,7 @@ fn value_settings(s: &mut Session, p: &Json) -> Result { let field = str_param(p, "field").map(str::to_string); let index = u32_param(p, "index").map(|v| v as usize); let func = match str_param(p, "func") { - Some(f) => Some(func_param(Some(f)).ok_or_else(|| bad(C, format!("unknown function `{f}`")))?), + Some(f) => Some(PivotFunc::parse(f).ok_or_else(|| bad(C, format!("unknown function `{f}`")))?), None => None, }; let show = match str_param(p, "showAs") { @@ -1893,6 +1869,17 @@ mod tests { } } + #[test] + fn count_numbers_is_captioned_like_count() { + // Excel 365 captions a new Count Numbers value field "Count of Units", as it does Count. + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": [{"field": "Units", "func": "countNumbers"}]})).unwrap(); + assert_eq!(pt(&s).values[0].name, "Count of Units"); + assert_eq!(pt(&s).values[0].func, gridcraft_model::PivotFunc::CountNumbers); + let l = s.execute("pivot.list", json!({})).unwrap(); + assert_eq!(l[0]["values"][0]["func"], "countNumbers"); + } + #[test] fn date_grouping_by_quarter_and_month() { let mut s = sales(); diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index a56be1be34..befcd3a477 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -398,23 +398,6 @@ impl Acc { } } -/// Excel's caption verb for a function ("Sum of Sales"). -pub fn func_caption(f: PivotFunc) -> &'static str { - match f { - PivotFunc::Sum => "Sum", - PivotFunc::Count => "Count", - PivotFunc::Average => "Average", - PivotFunc::Max => "Max", - PivotFunc::Min => "Min", - PivotFunc::Product => "Product", - PivotFunc::CountNumbers => "Count Numbers", - PivotFunc::StdDev => "StdDev", - PivotFunc::StdDevP => "StdDevp", - PivotFunc::Var => "Var", - PivotFunc::VarP => "Varp", - } -} - // ---------------------------------------------------------------- trees #[derive(Clone, Debug)] diff --git a/crates/model/src/features.rs b/crates/model/src/features.rs index b51f7bc98a..e8246bce7d 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -939,6 +939,80 @@ pub enum PivotFunc { VarP, } +impl PivotFunc { + /// Every function, in the order of Excel's Value Field Settings list. + pub const ALL: [PivotFunc; 11] = [ + PivotFunc::Sum, + PivotFunc::Count, + PivotFunc::Average, + PivotFunc::Max, + PivotFunc::Min, + PivotFunc::Product, + PivotFunc::CountNumbers, + PivotFunc::StdDev, + PivotFunc::StdDevP, + PivotFunc::Var, + PivotFunc::VarP, + ]; + + /// The word Excel puts in front of a new value field's name ("Sum of Sales"). Count Numbers + /// is captioned "Count", as in Excel. + pub fn caption(self) -> &'static str { + match self { + PivotFunc::Sum => "Sum", + PivotFunc::Count | PivotFunc::CountNumbers => "Count", + PivotFunc::Average => "Average", + PivotFunc::Max => "Max", + PivotFunc::Min => "Min", + PivotFunc::Product => "Product", + PivotFunc::StdDev => "StdDev", + PivotFunc::StdDevP => "StdDevp", + PivotFunc::Var => "Var", + PivotFunc::VarP => "Varp", + } + } + + /// The name commands take and report (`countNumbers`, `stdDevP`). + pub fn name(self) -> &'static str { + match self { + PivotFunc::Sum => "sum", + PivotFunc::Count => "count", + PivotFunc::Average => "average", + PivotFunc::Max => "max", + PivotFunc::Min => "min", + PivotFunc::Product => "product", + PivotFunc::CountNumbers => "countNumbers", + PivotFunc::StdDev => "stdDev", + PivotFunc::StdDevP => "stdDevP", + PivotFunc::Var => "var", + PivotFunc::VarP => "varP", + } + } + + /// The name in an XLSX file (`dataField@subtotal`: `countNums`, `stdDevp`, `varp`). + pub fn file_name(self) -> &'static str { + match self { + PivotFunc::CountNumbers => "countNums", + PivotFunc::StdDevP => "stdDevp", + PivotFunc::VarP => "varp", + f => f.name(), + } + } + + /// A function from its name, case-insensitively: the command name, the file name or a + /// common alias (`avg`, `counta`, `count numbers`). + pub fn parse(s: &str) -> Option { + let s = s.trim().to_ascii_lowercase(); + let alias = match s.as_str() { + "counta" => Some(PivotFunc::Count), + "avg" | "mean" => Some(PivotFunc::Average), + "count numbers" => Some(PivotFunc::CountNumbers), + _ => None, + }; + alias.or_else(|| PivotFunc::ALL.into_iter().find(|f| f.name().eq_ignore_ascii_case(&s) || f.file_name().eq_ignore_ascii_case(&s))) + } +} + /// Show-values-as transform. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum PivotShowAs { @@ -1046,3 +1120,24 @@ impl Default for PivotTable { } } } + +#[cfg(test)] +mod pivot_func_tests { + use super::PivotFunc; + + #[test] + fn captions_and_names_round_trip() { + // Excel 365's captions; Count Numbers is captioned like Count ("Count of Units"). + let captions: Vec<&str> = PivotFunc::ALL.iter().map(|f| f.caption()).collect(); + assert_eq!(captions, ["Sum", "Count", "Average", "Max", "Min", "Product", "Count", "StdDev", "StdDevp", "Var", "Varp"]); + for f in PivotFunc::ALL { + assert_eq!(PivotFunc::parse(f.name()), Some(f)); + assert_eq!(PivotFunc::parse(f.file_name()), Some(f)); + assert_eq!(PivotFunc::parse(&f.name().to_uppercase()), Some(f)); + } + assert_eq!(PivotFunc::CountNumbers.file_name(), "countNums"); + assert_eq!(PivotFunc::parse("avg"), Some(PivotFunc::Average)); + assert_eq!(PivotFunc::parse("Count Numbers"), Some(PivotFunc::CountNumbers)); + assert_eq!(PivotFunc::parse("median"), None); + } +} diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index 9019044aea..bad12ec4b6 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -64,55 +64,6 @@ fn same(a: &str, b: &str) -> bool { a.to_lowercase() == b.to_lowercase() } -fn func_name(f: PivotFunc) -> &'static str { - match f { - PivotFunc::Sum => "sum", - PivotFunc::Count => "count", - PivotFunc::Average => "average", - PivotFunc::Max => "max", - PivotFunc::Min => "min", - PivotFunc::Product => "product", - PivotFunc::CountNumbers => "countNums", - PivotFunc::StdDev => "stdDev", - PivotFunc::StdDevP => "stdDevp", - PivotFunc::Var => "var", - PivotFunc::VarP => "varp", - } -} - -fn func_from(s: &str) -> Option { - Some(match s { - "sum" => PivotFunc::Sum, - "count" => PivotFunc::Count, - "average" => PivotFunc::Average, - "max" => PivotFunc::Max, - "min" => PivotFunc::Min, - "product" => PivotFunc::Product, - "countNums" => PivotFunc::CountNumbers, - "stdDev" => PivotFunc::StdDev, - "stdDevp" => PivotFunc::StdDevP, - "var" => PivotFunc::Var, - "varp" => PivotFunc::VarP, - _ => return None, - }) -} - -fn func_caption(f: PivotFunc) -> &'static str { - match f { - PivotFunc::Sum => "Sum", - PivotFunc::Count => "Count", - PivotFunc::Average => "Average", - PivotFunc::Max => "Max", - PivotFunc::Min => "Min", - PivotFunc::Product => "Product", - PivotFunc::CountNumbers => "Count", - PivotFunc::StdDev => "StdDev", - PivotFunc::StdDevP => "StdDevp", - PivotFunc::Var => "Var", - PivotFunc::VarP => "Varp", - } -} - fn group_by_name(g: PivotDateGroup) -> &'static str { match g { PivotDateGroup::Years => "years", @@ -990,7 +941,7 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn let mut used: Vec = Vec::new(); for (i, v) in &vals { let base = if v.name.trim().is_empty() { - format!("{} of {}", func_caption(v.func), c.fields.get(*i).map(|f| f.name.as_str()).unwrap_or("")) + format!("{} of {}", v.func.caption(), c.fields.get(*i).map(|f| f.name.as_str()).unwrap_or("")) } else { v.name.clone() }; @@ -1003,7 +954,7 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn used.push(n.clone()); let _ = write!(s, ", x: &El, cache: &CacheIn, id: u32) -> Option PivotFunc::Sum, - Some(s) => func_from(s).unwrap_or_else(|| { + Some(s) => PivotFunc::parse(s).unwrap_or_else(|| { cx.warn(format!("PivotTable function {s} is not supported; using Sum")); PivotFunc::Sum }), @@ -1430,7 +1381,7 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option Date: Tue, 13 Oct 2026 11:58:35 +0200 Subject: [PATCH 13/13] PivotTables: docs: GridCraft-made pivots checked in Excel 365 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit gaps.md §1 and §8 and the PivotTables row of target-app-parity.md said the PivotTable round trip was never checked in Excel. PivotTables made in GridCraft, one feature per file, have now been opened and refreshed in Excel 365; the differences that turned up are fixed in this branch. No score change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj --- docs/gaps.md | 12 +++++++----- docs/target-app-parity.md | 5 +++-- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index 03e8672c52..4c1ea6b40c 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and whole-row/column formatting) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (§1, §8: PivotTables made in GridCraft checked in Excel 365) · **Target:** Microsoft Excel (Microsoft 365) Every known shortfall against Excel, one entry each, ranked by user impact (what blocks someone using GridCraft for real work first). This is the work list: pick from the top, check the open @@ -19,9 +19,10 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- ### 1. XLSX output not proven in Excel or on real files (FF) - **Missing:** a run over a real-world XLSX corpus, and confirmation that Excel opens what we save with no repair prompt (PivotTables, charts, CF, validation, dynamic arrays, tables). -- **Evidence:** round-trip tests cover our own files only (`crates/xlsx/src/tests/`); PivotTable - round-trip noted as "unverified in real Excel" since 10-07; #64 (dynamic-array flag) shows the - class of bug. +- **Evidence:** round-trip tests cover our own files only (`crates/xlsx/src/tests/`); PivotTables + made in GridCraft were opened and refreshed in Excel 365 on 10-13 (one feature per file), which + found and fixed files Excel refused (TRUE/FALSE or errors in the source) and layouts Excel + changed on refresh; #64 (dynamic-array flag) shows the class of bug. - **Impact:** the main format; a repair prompt or silent loss destroys trust. - **Estimate:** 15–25 h, plus owner time in Excel. [file-format-parity.md](file-format-parity.md) @@ -77,7 +78,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- routine in business. - **Estimate:** 14–21 h (`.xls` styles and objects 10–15, encryption 4–6). [file-format-parity.md](file-format-parity.md) -### 8. PivotTables: no slicers, calculated items, PivotCharts; unverified in Excel (F) +### 8. PivotTables: no slicers, calculated items, PivotCharts (F) - **Evidence:** `parity-checklist.md` missing `insert.slicer`, `insert.timeline`, `insert.pivotChart`, `table.insertSlicer`; calculated items and GETPIVOTDATA missing (calculated fields and values on rows done). @@ -168,6 +169,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | §1, §8: PivotTables made in GridCraft checked in Excel 365; the layout, blank-value, Show Values As, date-group, cache-flag, report-filter and PivotChart differences it found are fixed | | 2026-10-12 | minor | rows auto-fit oversized fonts on open and whole-row/column formatting (#833) | | 2026-10-12 | minor | Page Layout view: dragging margins on the rulers (#792) removed from the §14 remainder | | 2026-10-12 | minor | §13: Forecast Sheet Forecast Start (hindcast) landed (#785) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b623124d9f..0f9e7291db 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: GridCraft vs Microsoft Excel -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and row formatting) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (PivotTables made in GridCraft checked in Excel 365) · **Target:** Microsoft Excel (Microsoft 365) This is the authoritative parity assessment. [`ROADMAP.md`](../ROADMAP.md) summarizes it, [`gaps.md`](gaps.md) lists every shortfall, and the area checklists hold the detail: @@ -84,7 +84,7 @@ performance 8, stability 8, localization 4, hardware 2, platforms 2, ecosystem 2 | Editing, navigation, clipboard, fill | 12 | ~90% | ~70% | 15–25 | Point mode, F4, AutoComplete, Paste Special, AutoFill, Flash Fill, Find/Replace, Go To Special. Bugs: rectangular drag-select (#28), monthly fill (#132), cut across sheets (#128), Insert Copied Cells missing (#21), key tips only on part of the Home tab (#43; #33, #49). [ui-parity.md](ui-parity.md) | | Cell formatting, styles, conditional formatting | 10 | ~95% | ~80% | 8–14 | Full number-format language, borders, 47 cell styles, 60 table styles, all CF rule kinds including data bars, colour scales and icon sets. Gaps: font weights beyond regular/bold (#168), system fonts list (#4), themes | | Sort, filter, tables, validation, outline | 8 | ~82% | ~70% | 10–16 | Multi-level sort, AutoFilter, Advanced Filter, tables with totals, validation, outline, subtotals, consolidate. Bugs: subtotal header (#131), validation edits (#129), table style panic caught (#130); no slicers on tables | -| PivotTables | 7 | ~65% | ~45% | 25–40 | Insert/Recommended, field list, three layouts, values on rows or columns, date grouping, show-values-as, refresh, calculated fields, XLSX round-trip. Missing: slicers, timelines, calculated items, PivotCharts, value/label filters, number grouping, GETPIVOTDATA, data-model pivots. Round-trip never checked in Excel | +| PivotTables | 7 | ~65% | ~45% | 25–40 | Insert/Recommended, field list, three layouts, values on rows or columns, date grouping, show-values-as, refresh, calculated fields, XLSX round-trip. Missing: slicers, timelines, calculated items, PivotCharts, value/label filters, number grouping, GETPIVOTDATA, data-model pivots. Round trip of GridCraft-made pivots checked in Excel 365 (one feature per file, 2026-10-13) | | Charts and sparklines | 8 | ~50% | ~30% | 40–60 | 25 chart kinds, all 2-D. The chart model holds title, legend position, a data-labels flag, gridlines flag and axis titles; no axis scaling, trendlines, error bars, per-point formatting, chart sheets, 3-D, surface, map, Pareto. Several kinds don't survive XLSX round trip (open PRs #158, #161). [chart-parity.md](chart-parity.md) | | Page layout, print, PDF | 5 | ~80% | ~55% | 12–20 | Page setup, print titles, breaks, Page Break Preview, headers/footers, PDF export and printing. No true Page Layout view; the PDF writer uses only the 14 standard fonts without embedding (no CJK or other non-Latin text in PDF); web print only exports (#141, #143) | | What-if and analysis | 4 | ~50% | ~40% | 22–35 | Goal Seek, Scenario Manager, data tables, Analysis ToolPak (13 of 19 tools, no charts), Solver (Simplex LP, a local nonlinear method and Evolutionary; Answer and Limits reports; no Sensitivity report or options dialog). Missing: Forecast Sheet, Analyze Data | @@ -332,6 +332,7 @@ The inventory carried over from the 2026-10-07 ROADMAP.md, updated for what land | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | PivotTables made in GridCraft checked in Excel 365 (opened without repair, refreshed to the same cells after the layout, blank-value, Show Values As, date-group, cache-flag, report-filter and PivotChart fixes); no score change | | 2026-10-12 | minor | Essentials AutoFit evidence: rows auto-fit oversized fonts on open and row formatting (#833) | | 2026-10-12 | minor | Sheet tabs: reveal the selected tab on navigation and resize while preserving manual scrolling (#681); no score change | | 2026-10-12 | minor | PivotTables: values on rows (Σ Values in Rows at any position, all three layouts; `pivot.moveField` and the field pane move it; `dataOnRows` round-trips) (no score change) |