Merge pull request #722 from neilcawse/fix/pivot-refresh-fidelity

PivotTables: refresh keeps sort by value, captions, item order and layout settings
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 22:46:19 +01:00
commit 90ec7db3b5
19 files changed
+1576 -226

No files matched your search

+65
View File
@@ -162,6 +162,43 @@ pub fn serial_from_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Opti
Some(serial as f64)
}
/// The calendar date a pivot cache's ISO 8601 date items (`<d>`, `minDate`, `startDate`…) give
/// a date of a date system's calendar, as [`datetime_from_serial`] returns it. Those dates count
/// real days: from 1899-12-30 in the 1900 system and from 1904-01-01 in the 1904 system. Up to
/// February 1900 the 1900 system's own calendar, with its day 1900-01-00 and the fictitious
/// 1900-02-29, runs one day ahead of that: serial 0 (the date part of a time) is 1899-12-30,
/// serial 1 is 1899-12-31 and serial 60 is 1900-02-28. Excel writes its caches that way.
pub fn iso_ymd(sys: DateSystem, year: i32, month: u32, day: u32) -> (i32, u32, u32) {
if sys == DateSystem::D1900 && year == 1900 && month <= 2 {
let serial = if month <= 1 { day } else { 31 + day };
return civil_from_days(i64::from(serial) + UNIX_1899_12_30);
}
(year, month, day)
}
/// Serial for an ISO 8601 calendar date, the inverse of [`iso_ymd`]. Unlike [`serial_from_ymd`]
/// (`DATE()`), years below 1900 aren't moved on by 1900 and month or day overflow is invalid.
/// The 1900 system also takes 1900-02-29 (serial 60), which some writers use for that day; the
/// 1904 system takes 1899-12-30 as the date part of a time (serial 0). `None` for an invalid date,
/// or one before the epoch or after 9999-12-31.
pub fn serial_from_iso_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Option<f64> {
let (y, m, d) = (i32::try_from(year).ok()?, u32::try_from(month).ok()?, u32::try_from(day).ok()?);
match (sys, y, m, d) {
(DateSystem::D1900, 1900, 2, 29) => return Some(60.0),
(DateSystem::D1904, 1899, 12, 30) => return Some(0.0),
_ => {}
}
if !(1..=9999).contains(&y) || !(1..=12).contains(&m) || d < 1 || d > days_in_month(y, m) {
return None;
}
let base = match sys {
DateSystem::D1900 => UNIX_1899_12_30,
DateSystem::D1904 => UNIX_1904_01_01,
};
let serial = days_from_civil(y, m, d) - base;
(0..=max_serial(sys)).contains(&serial).then_some(serial as f64)
}
/// Date/time from a serial. `None` for negative or too-large serials.
pub fn datetime_from_serial(sys: DateSystem, serial: f64) -> Option<DateTime> {
if !serial.is_finite() || !(0.0..max_serial(sys) as f64 + 1.0).contains(&serial) {
@@ -384,4 +421,32 @@ mod tests {
assert_eq!(d.weekday, 0); // 1900-01-01 was a Sunday in Excel's calendar
Ok(())
}
#[test]
fn iso_dates_count_real_days() {
let s = DateSystem::D1900;
// Excel writes serial 0 (a time's date part) as 1899-12-30 and serial 1 as 1899-12-31.
for (serial, ymd) in
[(0, (1899, 12, 30)), (1, (1899, 12, 31)), (2, (1900, 1, 1)), (60, (1900, 2, 28)), (61, (1900, 3, 1)), (46302, (2026, 10, 7))]
{
let d = datetime_from_serial(s, serial as f64).unwrap();
assert_eq!(iso_ymd(s, d.year, d.month, d.day), ymd, "{serial}");
assert_eq!(serial_from_iso_ymd(s, ymd.0 as i64, ymd.1 as i64, ymd.2 as i64), Some(serial as f64), "{serial}");
}
assert_eq!(serial_from_iso_ymd(s, 1900, 2, 29), Some(60.0));
assert_eq!(serial_from_iso_ymd(s, 1899, 12, 29), None);
assert_eq!(serial_from_iso_ymd(s, 2024, 2, 30), None);
assert_eq!(serial_from_iso_ymd(s, 2024, 13, 1), None);
assert_eq!(serial_from_iso_ymd(s, 9999, 12, 31), Some(2958465.0));
assert_eq!(serial_from_iso_ymd(s, 10000, 1, 1), None);
assert_eq!(serial_from_iso_ymd(s, i64::MAX, 1, 1), None);
// The 1904 system has no offset; 1899-12-30 stands for a time's date part there too.
let s = DateSystem::D1904;
let d = datetime_from_serial(s, 0.5).unwrap();
assert_eq!(iso_ymd(s, d.year, d.month, d.day), (1904, 1, 1));
assert_eq!(serial_from_iso_ymd(s, 1904, 1, 1), Some(0.0));
assert_eq!(serial_from_iso_ymd(s, 1904, 3, 1), Some(60.0));
assert_eq!(serial_from_iso_ymd(s, 1899, 12, 30), Some(0.0));
assert_eq!(serial_from_iso_ymd(s, 1903, 12, 31), None);
}
}
+9 -1
View File
@@ -118,7 +118,15 @@ pub fn specs() -> Vec<CommandSpec> {
value_settings
),
cmd!("pivot.filter", "Filter Items", [], None, "{pivot?, field, selected: [\"East\", ..] | null (all), replace?}", has_doc, filter),
cmd!("pivot.sort", "Sort Field", [], None, "{pivot?, field, order: asc|desc|none, replace?}", has_doc, sort),
cmd!(
"pivot.sort",
"Sort Field",
[],
None,
"{pivot?, field, order: asc|desc|none, by?: \"Sum of Sales\" (sort by a value field), replace?}",
has_doc,
sort
),
cmd!(
"pivot.group",
"Group Field",
+16 -4
View File
@@ -1,8 +1,8 @@
use super::fields::{AreaPlacement, add_to_area, in_axes};
use super::params::{func_name, func_param, group_name, group_param, layout_name, show_as_name, sort_name};
use super::{
Arc, Cell, CellRef, Ctx, EngineError, Json, NumFmt, PivotDateGroup, PivotTable, RangeRef, Result, Session, Sheet, StyleId, Workbook, bad,
bool_param, cell_param, current_region, edit, find_pivot, json, other, pv, str_param, with,
Arc, Cell, CellRef, Ctx, EngineError, Json, NumFmt, PivotDateGroup, PivotField, PivotTable, RangeRef, Result, Session, Sheet, StyleId, Workbook,
bad, bool_param, cell_param, current_region, edit, find_pivot, json, other, pv, str_param, with,
};
// ---------------------------------------------------------------- insert
@@ -327,6 +327,18 @@ pub(super) fn summarize_table(s: &mut Session, p: &Json) -> Result<Json> {
// ---------------------------------------------------------------- queries
fn field_json(f: &PivotField) -> Json {
json!({
"field": f.source_col,
"caption": f.caption,
"sort": sort_name(f.sort),
"sortBy": f.sort_by,
"group": group_name(f.date_group),
"numberFormat": f.number_format,
"collapsed": f.collapsed_items,
})
}
pub(super) fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json {
json!({
"id": pt.id,
@@ -335,8 +347,8 @@ pub(super) fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json {
"anchor": pt.anchor.a1(),
"range": pt.last_range.map(|r| r.a1()),
"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::<Vec<_>>(),
"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::<Vec<_>>(),
"rows": pt.rows.iter().map(field_json).collect::<Vec<_>>(),
"columns": pt.columns.iter().map(field_json).collect::<Vec<_>>(),
"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::<Vec<_>>(),
"filters": pt.filters.iter().map(|f| json!({"field": f.source_col, "selected": f.selected, "report": !in_axes(pt, &f.source_col)})).collect::<Vec<_>>(),
"layout": layout_name(pt.layout),
+6
View File
@@ -551,6 +551,12 @@ pub(super) fn value_settings(s: &mut Session, p: &Json) -> Result<Json> {
None => {}
}
let name = v.name.clone();
// Fields sorted by this value field follow its new caption.
for f in pt.rows.iter_mut().chain(pt.columns.iter_mut()) {
if f.sort_by.as_deref().is_some_and(|b| b.eq_ignore_ascii_case(&cur.name)) {
f.sort_by = Some(name.clone());
}
}
if let Some(slot) = pt.values.get_mut(i) {
*slot = v;
}
+21 -1
View File
@@ -71,8 +71,24 @@ pub(super) fn sort(s: &mut Session, p: &Json) -> Result<Json> {
"none" | "manual" | "source" => PivotSort::None,
o => return Err(bad(C, format!("unknown order `{o}` (asc|desc|none)"))),
};
// Sort by a value field (its caption or source field) instead of by the item labels.
let by = str_param(p, "by").map(str::to_string);
update(s, p, |pt, _, _| {
axis_field(C, pt, &field)?.sort = order;
let by = match by {
Some(b) => Some(
pt.values
.iter()
.find(|v| v.name.eq_ignore_ascii_case(&b))
.or_else(|| pt.values.iter().find(|v| v.source_col.eq_ignore_ascii_case(&b)))
.map(|v| v.name.clone())
.ok_or_else(|| bad(C, format!("`{b}` isn't in the values area")))?,
),
None => None,
};
let f = axis_field(C, pt, &field)?;
f.sort = order;
f.sort_by = by;
f.sort_scope.clear();
Ok(json!({}))
})
}
@@ -164,7 +180,11 @@ pub(super) fn layout(s: &mut Session, p: &Json) -> Result<Json> {
}
}
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;
}
+508 -4
View File
@@ -1,4 +1,5 @@
use gridcraft_core::{CellError, CellRef, Value};
use gridcraft_model::{PivotLayout, PivotSort};
use serde_json::{Value as Json, json};
use crate::Session;
@@ -317,6 +318,10 @@ fn assert_values_on_rows_tabular(s: &mut Session) {
assert_eq!(text(s, "A3"), "Region");
assert_eq!(text(s, "B3"), "Values");
assert_eq!(text(s, "C3"), "Total");
// The Values field's caption heads its column, as in Excel's saved reports.
edit_pt(s, |p| p.data_caption = Some("Data".into()));
assert_eq!(text(s, "B3"), "Data");
edit_pt(s, |p| p.data_caption = None);
}
fn assert_values_on_rows_position(s: &mut Session) {
@@ -501,6 +506,231 @@ fn refresh_after_source_edits() {
s.execute("pivot.refresh", json!({"pivot": "PivotTable1"})).unwrap();
}
/// Edits the active sheet's last PivotTable in the model (settings only a file sets) and
/// refreshes it.
fn edit_pt(s: &mut Session, f: impl FnOnce(&mut gridcraft_model::PivotTable)) {
let d = s.doc_mut().unwrap();
let wb = std::sync::Arc::make_mut(&mut d.wb);
let si = wb.active_sheet();
f(wb.sheet_mut(si).unwrap().pivots.last_mut().unwrap());
s.execute("pivot.refresh", json!({})).unwrap();
}
#[test]
fn sort_by_value_within_each_parent() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap();
// East 415, West 285, North 135.
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Sum of Sales"));
assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["East", "West", "North"]);
s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Sales"})).unwrap();
assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["North", "West", "East"]);
assert!(s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Nope"})).is_err());
// The sort follows a renamed value field; sorting without `by` sorts by label again.
s.execute("pivot.valueSettings", json!({"field": "Sum of Sales", "name": "Revenue"})).unwrap();
assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Revenue"));
assert_eq!(text(&s, "A4"), "North");
s.execute("pivot.sort", json!({"field": "Region", "order": "desc"})).unwrap();
assert_eq!(pt(&s).rows[0].sort_by, None);
assert_eq!(text(&s, "A4"), "West");
// Inner items sort within their parent; subtotals stay with their group.
s.execute("pivot.addField", json!({"field": "Product", "area": "rows"})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Revenue"})).unwrap();
s.execute("pivot.sort", json!({"field": "Product", "order": "desc", "by": "Revenue"})).unwrap();
// East: Pears 195, Apples 160, Plums 60.
assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "B5"), text(&s, "B6"), text(&s, "A7")], ["East", "Pears", "Apples", "Plums", "East Total"]);
assert_eq!(val(&s, "C4"), Value::Number(195.0));
// West: Apples 170, Plums 70, Pears 45.
assert_eq!([text(&s, "A8"), text(&s, "B8"), text(&s, "B9"), text(&s, "B10")], ["West", "Apples", "Plums", "Pears"]);
// Columns sort by their row totals.
s.execute("pivot.moveField", json!({"field": "Region", "from": "rows", "to": "columns"})).unwrap();
assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4")], ["East", "West", "North"]);
}
#[test]
fn captions_renamed_items_and_manual_order() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap();
edit_pt(&mut s, |p| {
p.row_header_caption = Some("Area".into());
p.col_header_caption = Some("Fruit".into());
p.grand_total_caption = Some("Everything".into());
p.rows[0].item_captions = vec![("East".into(), "Eastern".into())];
p.columns[0].sort = PivotSort::None;
p.columns[0].item_order = vec!["Plums".into(), "Pears".into()];
});
assert_eq!(text(&s, "A4"), "Area");
assert_eq!(text(&s, "B3"), "Fruit");
// Listed items first, the rest after.
assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4"), text(&s, "E4")], ["Plums", "Pears", "Apples", "Everything"]);
assert_eq!(text(&s, "A5"), "Eastern");
assert_eq!(text(&s, "A8"), "Everything");
// A renamed item sorts by its label still, and a filter still names it by its label.
s.execute("pivot.filter", json!({"field": "Region", "selected": ["East"]})).unwrap();
assert_eq!(text(&s, "A5"), "Eastern");
assert_eq!(val(&s, "E5"), Value::Number(415.0));
// Outline layout: the field's custom name heads its column.
edit_pt(&mut s, |p| {
p.layout = PivotLayout::Outline;
p.rows[0].caption = Some("Sales area".into());
p.columns[0].caption = Some("Kind".into());
});
assert_eq!(text(&s, "A4"), "Sales area");
assert_eq!(text(&s, "B3"), "Kind");
}
#[test]
fn field_subtotals_repeat_labels_and_values_row() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales"]})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
assert_eq!(text(&s, "A7"), "East Total");
// Region without subtotals although the table has them; labels repeated on every row.
edit_pt(&mut s, |p| {
p.rows[0].subtotal = Some(false);
p.rows[0].repeat_labels = true;
});
assert_eq!(pt(&s).last_range.unwrap().height(), 1 + 9 + 1);
assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6"), text(&s, "A7")], ["East", "East", "East", "North"]);
assert_eq!(text(&s, "B7"), "Apples");
// Outline repeats the labels too.
s.execute("pivot.layout", json!({"layout": "outline"})).unwrap();
assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "A5"), text(&s, "B5")], ["East", "", "East", "Apples"]);
// Two values without a column field: the Values row (Outline/Tabular) holds the caption.
s.execute("pivot.removeField", json!({"field": "Product"})).unwrap();
s.execute("pivot.addField", json!({"field": "Units", "area": "values"})).unwrap();
assert_eq!(text(&s, "B3"), "Values");
assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "C4")], ["Region", "Sum of Sales", "Sum of Units"]);
edit_pt(&mut s, |p| p.data_caption = Some("Data".into()));
assert_eq!(text(&s, "B3"), "Data");
edit_pt(&mut s, |p| p.show_values_row = false);
assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Region", "Sum of Sales"]);
// Compact layout never shows it.
edit_pt(&mut s, |p| {
p.show_values_row = true;
p.layout = PivotLayout::Compact;
});
assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Row Labels", "Sum of Sales"]);
}
#[test]
fn empty_cell_caption_classic_layout_and_date_order() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Units"], "values": ["Sales"]})).unwrap();
// East has no record with 1 unit: blank, or the "For empty cells show" caption.
assert_eq!([text(&s, "A5"), text(&s, "B4"), text(&s, "B5")], ["East", "1", ""]);
edit_pt(&mut s, |p| p.empty_caption = Some("0".into()));
assert_eq!(text(&s, "B5"), "0");
// Classic layout, one value and no column field: the value caption above the row
// headers and a "Total" column.
s.execute("pivot.removeField", json!({"field": "Units"})).unwrap();
edit_pt(&mut s, |p| {
p.layout = PivotLayout::Tabular;
p.classic_layout = true;
});
assert_eq!([text(&s, "A3"), text(&s, "A4"), text(&s, "B4"), text(&s, "A5")], ["Sum of Sales", "Region", "Total", "East"]);
assert_eq!(pt(&s).last_range.unwrap().height(), 2 + 3 + 1);
// A field number format applies to the item labels; date items sort after text, as in
// Excel.
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
s.execute("cell.set", json!({"cell": "C13", "input": "NA"})).unwrap();
s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap();
s.execute("pivot.removeField", json!({"field": "Region"})).unwrap();
s.execute("pivot.addField", json!({"field": "Date", "area": "rows"})).unwrap();
edit_pt(&mut s, |p| p.rows[0].number_format = Some("m/d/yyyy".into()));
assert_eq!(text(&s, "A5"), "NA");
}
#[test]
fn only_date_formatted_cells_sort_as_dates() {
// The two mixed columns of ClosedXML's VariousDataTypesInTableColumns, in source order.
// Excel caches each date-formatted cell as `<d>` and each General one as `<n>`, and its
// saved items list numbers first and dates after errors, whatever the first cell is.
let mixed = ["", "TRUE", "14.5", "10", "ABC", "=1/0", "8/10/2020", "16:30"];
// 1 and 1.52… are 12/31/1899 and 12/31/1899 12:30, which typed input reads as text.
let with_num = ["1", "1.5208333333333333", "12/24/2020", "16:30", "0.1", "45000", ""];
let order = |inputs: &[&str], dates: Option<&str>| -> Vec<String> {
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "K"})).unwrap();
s.execute("cell.set", json!({"cell": "B1", "input": "V"})).unwrap();
for (i, input) in inputs.iter().enumerate() {
s.execute("cell.set", json!({"cell": format!("A{}", i + 2), "input": input})).unwrap();
s.execute("cell.set", json!({"cell": format!("B{}", i + 2), "input": "1"})).unwrap();
}
if let Some(range) = dates {
s.execute("home.formatCells", json!({"range": range, "style": {"num_fmt": "m/d/yyyy h:mm"}})).unwrap();
}
s.execute("selection.set", json!({"range": "A1"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["K"], "values": ["V"]})).unwrap();
edit_pt(&mut s, |p| p.rows[0].sort = PivotSort::Asc);
let wb = &s.doc().unwrap().wb;
let si = wb.active_sheet();
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
out.grid.iter().skip(1).filter_map(|r| r.first().map(|c| c.value.display())).filter(|l| l != "Grand Total").collect()
};
// Excel's saved <items> order for each field.
let excel_mixed = ["10", "14.5", "ABC", "TRUE", "#DIV/0!", "0.6875", "44053", "(blank)"];
let excel_with_num = ["0.1", "45000", "0.6875", "1", "1.52083333333333", "44189", "(blank)"];
assert_eq!(order(&mixed, None), excel_mixed);
assert_eq!(order(&with_num, Some("A2:A3")), excel_with_num);
// One number in a date cell and in a General cell is one item, which sorts as a number
// whichever cell comes first.
let number = ["5", "44053", "ABC"];
assert_eq!(order(&["5", "8/10/2020", "44053", "ABC"], None), number);
assert_eq!(order(&["5", "44053", "8/10/2020", "ABC"], None), number);
}
#[test]
fn a_general_cell_filtered_out_still_makes_its_number_sort_as_a_number() {
// 3/15/2023 is 45000: the General 45000 in row 3 makes that item a number, as in Excel's
// cache, even when the report filter leaves only the date cell.
let order = |filter: bool| -> Vec<String> {
let mut s = Session::new();
s.new_workbook();
for (cell, input) in [("A1", "K"), ("B1", "V"), ("C1", "R"), ("A2", "3/15/2023"), ("A3", "45000"), ("A4", "ABC")] {
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
}
for (row, r) in [(2, "a"), (3, "b"), (4, "a")] {
s.execute("cell.set", json!({"cell": format!("B{row}"), "input": "1"})).unwrap();
s.execute("cell.set", json!({"cell": format!("C{row}"), "input": r})).unwrap();
}
s.execute("selection.set", json!({"range": "A1"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["K"], "values": ["V"], "filters": ["R"]})).unwrap();
s.execute("pivot.sort", json!({"field": "K", "order": "asc"})).unwrap();
if filter {
s.execute("pivot.filter", json!({"field": "R", "selected": ["a"]})).unwrap();
}
let wb = &s.doc().unwrap().wb;
let si = wb.active_sheet();
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
out.grid.iter().filter_map(|r| r.first().map(|c| c.value.display())).filter(|l| l == "45000" || l == "ABC").collect()
};
assert_eq!(order(false), ["45000", "ABC"]);
assert_eq!(order(true), ["45000", "ABC"]);
}
#[test]
fn dates_sort_after_logicals_and_errors() {
// Excel's ascending item order: numbers, text, logicals, errors, dates, blanks.
let mut s = sales();
s.execute("cell.set", json!({"cell": "C11", "input": "TRUE"})).unwrap();
s.execute("cell.set", json!({"cell": "C12", "input": "=1/0"})).unwrap();
s.execute("cell.set", json!({"cell": "C13", "input": "NA"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["Date"], "values": ["Sales"]})).unwrap();
edit_pt(&mut s, |p| {
p.rows[0].number_format = None;
p.rows[0].sort = PivotSort::Asc;
});
let p = pt(&s);
let r = p.last_range.unwrap();
let labels: Vec<String> = (r.start.row + 1..=r.end.row).map(|row| text(&s, &CellRef::new(row, r.start.col).a1())).collect();
// 46037 is 1/15/2026, the first date.
assert_eq!(labels[..4], ["NA", "TRUE", "#DIV/0!", "46037"]);
}
fn pivot_chart(s: &Session) -> gridcraft_model::Chart {
s.doc().unwrap().wb.active().unwrap().charts.last().unwrap().clone()
}
@@ -1153,12 +1383,289 @@ fn collapsed_column_items_count_as_one_column_group() {
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<String>) {
reopen_patched_part(s, "xl/pivotTables/pivotTable1.xml", patch)
}
/// Saves the active workbook, applies `patch` to `part` and reopens it.
fn reopen_patched_part(s: &Session, part: &str, patch: impl Fn(&str) -> String) -> (gridcraft_model::Workbook, Vec<String>) {
use std::io::{Read, Write};
let bytes = crate::io::save_bytes(&s.doc().unwrap().wb, "t.xlsx").unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
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().unwrap().to_string();
let mut b = Vec::new();
f.read_to_end(&mut b).unwrap();
if name == part {
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 = "<references count=\"1\"><reference field=\"4294967294\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>";
let values_ref = "<reference field=\"4294967294\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>";
let two = format!("<references count=\"2\">{values_ref}<reference field=\"1\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>");
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();
let apples = gridcraft_model::PivotScopeItem { source_col: "Product".into(), item: "Apples".into(), ..Default::default() };
assert_eq!(p.rows[0].sort_scope, vec![apples]);
let out = crate::pivot::compute(&wb, p, si).unwrap();
let labels: Vec<String> = 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!("<references count=\"2\">{values_ref}<reference field=\"1\" count=\"2\" selected=\"0\"><x v=\"0\"/><x v=\"1\"/></reference>");
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:?}");
}
/// Saves and reopens a workbook.
fn reopen_wb(wb: &gridcraft_model::Workbook) -> gridcraft_model::Workbook {
let bytes = crate::io::save_bytes(wb, "t.xlsx").unwrap();
crate::io::open_bytes("t.xlsx", &bytes).unwrap().0
}
/// The labels in the report's first column, as computed from `wb`, keeping only `keep`.
fn first_col(wb: &gridcraft_model::Workbook, keep: &[&str]) -> Vec<String> {
let si = wb.active_sheet();
let p = wb.sheet(si).unwrap().pivots.last().unwrap();
let out = crate::pivot::compute(wb, p, si).unwrap();
out.grid.iter().filter_map(|r| r.first()).map(|c| c.value.display()).filter(|l| keep.contains(&l.as_str())).collect()
}
const VALUES_REF: &str = "<reference field=\"4294967294\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>";
/// The Values-only sort scope the writer emits, as a `<references>` opening.
fn values_only() -> String {
format!("<references count=\"1\">{VALUES_REF}")
}
#[test]
fn sort_scope_tells_date_levels_of_one_column_apart() {
use gridcraft_model::{PivotDateGroup, PivotField};
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Date"], "values": ["Sales"]})).unwrap();
edit_pt(&mut s, |p| {
let date = p.columns[0].clone();
p.columns =
vec![PivotField { date_group: PivotDateGroup::Years, ..date.clone() }, PivotField { date_group: PivotDateGroup::Quarters, ..date }];
});
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
// Sort by the values in the 2026 › Qtr2 column: Years is cache field 5 (item 1 = 2026,
// after "<1/15/2026"), Quarters the Date field 2 (item 2 = Qtr2). Qtr2 holds West 70,
// East 60, North 30; the totals are East 415, West 285, North 135.
let refs = format!(
"<references count=\"3\">{VALUES_REF}<reference field=\"5\" count=\"1\" selected=\"0\"><x v=\"1\"/></reference><reference field=\"2\" count=\"1\" selected=\"0\"><x v=\"2\"/></reference>"
);
let (wb, _) = reopen_patched(&s, |x| {
assert!(x.contains(&values_only()), "{x}");
x.replace(&values_only(), &refs)
});
let regions = ["East", "West", "North"];
assert_eq!(first_col(&wb, &regions), ["West", "East", "North"]);
// Saving writes both references back.
let back = reopen_wb(&wb);
let scope = |wb: &gridcraft_model::Workbook| wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap().rows[0].sort_scope.clone();
assert_eq!(scope(&back).len(), 2);
assert_eq!(scope(&back), scope(&wb));
assert_eq!(first_col(&back, &regions), ["West", "East", "North"]);
}
#[test]
fn custom_subtotal_functions_keep_the_subtotal_rows() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Units"]})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
// Field Settings › Subtotals › Custom (Sum and Count) on Product, as Excel stores it.
let (wb, warnings) = reopen_patched(&s, |x| {
let start = x.match_indices("<pivotField ").nth(1).unwrap().0;
let end = start + x[start..].find("</pivotField>").unwrap();
let field = x[start..end]
.replacen("<pivotField ", "<pivotField defaultSubtotal=\"0\" sumSubtotal=\"1\" countSubtotal=\"1\" ", 1)
.replace("<item t=\"default\"/>", "<item t=\"sum\"/><item t=\"count\"/>");
assert!(field.contains("t=\"sum\""), "{field}");
format!("{}{field}{}", &x[..start], &x[end..])
});
let p = wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap();
assert_ne!(p.rows[1].subtotal, Some(false));
// Shown with the automatic subtotal, with a warning.
let plain = reopen_wb(&s.doc().unwrap().wb);
let all = |wb: &gridcraft_model::Workbook| {
let si = wb.active_sheet();
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
out.grid.iter().map(|r| r.iter().map(|c| c.value.display()).collect::<Vec<_>>()).collect::<Vec<_>>()
};
assert_eq!(all(&wb), all(&plain));
assert!(warnings.iter().any(|w| w.contains("subtotal")), "{warnings:?}");
}
#[test]
fn custom_subtotals_on_the_first_field_keep_the_table_default() {
use std::io::Read;
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Units"]})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
// Custom Sum subtotal on Region (cache field 0, the first axis field), no xpdl extension.
let (wb, _) = reopen_patched(&s, |x| {
assert!(!x.contains("pivotTableDefinition16"), "{x}");
let start = x.find("<pivotField ").unwrap();
let end = start + x[start..].find("</pivotField>").unwrap();
let field = x[start..end]
.replacen("<pivotField ", "<pivotField defaultSubtotal=\"0\" sumSubtotal=\"1\" ", 1)
.replace("<item t=\"default\"/>", "<item t=\"sum\"/>");
assert!(field.contains("t=\"sum\""), "{field}");
format!("{}{field}{}", &x[..start], &x[end..])
});
let p = wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap();
assert!(p.subtotals);
assert_eq!([p.rows[0].subtotal, p.rows[1].subtotal], [None, None]);
// Saving doesn't add a table default of "off" the file never had.
let bytes = crate::io::save_bytes(&wb, "t.xlsx").unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
z.by_name("xl/pivotTables/pivotTable1.xml").unwrap().read_to_string(&mut xml).unwrap();
assert!(!xml.contains("EnabledSubtotalsDefault=\"0\""), "{xml}");
}
#[test]
fn sort_scope_on_a_vanished_item_sorts_as_after_saving() {
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();
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
// Sorted by the values in the Kiwis column (Product item 3)…
let refs = format!("<references count=\"2\">{VALUES_REF}<reference field=\"1\" count=\"1\" selected=\"0\"><x v=\"3\"/></reference>");
let (mut wb, _) = reopen_patched(&s, |x| x.replace(&values_only(), &refs));
assert_eq!(wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap().rows[0].sort_scope.len(), 1);
// …then Kiwis leaves the source: the rows sort by the grand total, before and after saving.
let src = wb.sheets.iter().position(|sh| sh.name == "Sheet1").unwrap();
wb.sheet_mut(src).unwrap().set_value(CellRef::parse("B14").unwrap(), Value::text("Apples"));
let regions = ["East", "West", "North", "South"];
let total_order = ["East", "West", "North", "South"];
assert_eq!(first_col(&wb, &regions), total_order);
assert_eq!(first_col(&reopen_wb(&wb), &regions), total_order);
}
#[test]
fn date_groups_not_sorted_are_in_date_order() {
let mut s = sales();
// The first record is in Qtr4.
s.execute("cell.set", json!({"cell": "C2", "input": "12/1/2026"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["Date"], "values": ["Sales"]})).unwrap();
s.execute("pivot.group", json!({"field": "Date", "by": "quarters"})).unwrap();
s.execute("pivot.sort", json!({"field": "Date", "order": "none"})).unwrap();
let quarters = ["Qtr1", "Qtr2", "Qtr3", "Qtr4"];
assert_eq!(first_col(&s.doc().unwrap().wb, &quarters), quarters);
let back = reopen_wb(&s.doc().unwrap().wb);
assert_eq!(first_col(&back, &quarters), quarters);
// A reordered list still wins; items it doesn't name follow in date order.
let mut wb = back;
let si = wb.active_sheet();
wb.sheet_mut(si).unwrap().pivots.last_mut().unwrap().rows[0].item_order = vec!["Qtr3".into()];
assert_eq!(first_col(&wb, &quarters), ["Qtr3", "Qtr1", "Qtr2", "Qtr4"]);
assert_eq!(first_col(&reopen_wb(&wb), &quarters), ["Qtr3", "Qtr1", "Qtr2", "Qtr4"]);
}
#[test]
fn manual_order_of_time_items_from_an_excel_cache() {
// Excel caches times as `<d v="1899-12-30T08:00:00"/>`: those items must name the
// report's 8:00 and 9:30, or a refresh puts the blank ahead of them.
let mut s = Session::new();
s.new_workbook();
for (cell, input) in [("A1", "Shift"), ("B1", "Sales"), ("A2", "8:00"), ("B2", "10"), ("A3", "9:30"), ("B3", "20"), ("B4", "5")] {
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
}
s.execute("selection.set", json!({"range": "A1"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["Shift"], "values": ["Sales"]})).unwrap();
s.execute("pivot.sort", json!({"field": "Shift", "order": "none"})).unwrap();
// The report's first column: times as minutes, and the blank item.
let shifts = |wb: &gridcraft_model::Workbook| -> Vec<String> {
let si = wb.active_sheet();
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
out.grid
.iter()
.filter_map(|r| match &r.first()?.value {
Value::Number(n) => Some(format!("{}", (n * 1440.0).round())),
v if v.display() == "(blank)" => Some(v.display()),
_ => None,
})
.collect()
};
let order = ["480", "570", "(blank)"];
assert_eq!(shifts(&s.doc().unwrap().wb), order);
let excel_items = "<d v=\"1899-12-30T08:00:00\"/><d v=\"1899-12-30T09:30:00\"/><m/>";
let (back, _) = reopen_patched_part(&s, "xl/pivotCache/pivotCacheDefinition1.xml", |x| {
let ours = "<n v=\"0.3333333333333333\"/><n v=\"0.3958333333333333\"/><m/>";
assert!(x.contains(ours), "{x}");
x.replace(ours, excel_items)
});
assert_eq!(shifts(&back), order);
// Saving writes that order back.
assert_eq!(shifts(&reopen_wb(&back)), order);
}
#[test]
fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"source": "Sheet1!A1:E13", "destination": "Sheet1!H10", "rows": ["Region"], "values": ["Sales"]})).unwrap();
assert_eq!(pt(&s).last_range.unwrap().a1(), "H10:I14");
// Rows above the report (and below the source) move the report only.
s.execute("home.insertRows", json!({"rows": "16:17"})).unwrap();
s.execute("home.insertRows", json!({"rows": "6:7"})).unwrap();
assert_eq!(text(&s, "H12"), "Row Labels");
@@ -1166,7 +1673,6 @@ fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() {
assert_eq!(l[0]["anchor"], "H12");
assert_eq!(l[0]["range"], "H12:I16");
assert_eq!(l[0]["source"], "Sheet1!A1:E15");
// A row above the source moves both.
s.execute("home.insertRows", json!({"rows": "1:1"})).unwrap();
let p = pt(&s);
assert_eq!(p.source, "Sheet1!A2:E16");
@@ -1175,12 +1681,10 @@ fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() {
assert_eq!(pt(&s).last_range.unwrap().a1(), "H13:I17");
assert_eq!(text(&s, "H13"), "Row Labels");
assert_eq!(val(&s, "I17"), Value::Number(TOTAL));
// Deleting a column left of the report moves it left.
s.execute("home.deleteColumns", json!({"cols": "F:F"})).unwrap();
let p = pt(&s);
assert_eq!(p.anchor.a1(), "G13");
assert_eq!(p.last_range.unwrap().a1(), "G13:H17");
// Deleting rows above moves it up.
s.execute("home.deleteRows", json!({"rows": "1:1"})).unwrap();
assert_eq!(pt(&s).source, "Sheet1!A1:E15");
assert_eq!(pt(&s).anchor.a1(), "G12");
+44 -3
View File
@@ -10,7 +10,7 @@ use std::collections::{HashMap, HashSet};
use gridcraft_core::date::datetime_from_serial;
pub use gridcraft_core::quote_sheet;
use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, split_sheet};
use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, number_to_text, split_sheet};
use gridcraft_model::{
BorderLine, BorderStyle, Cell, Chart, Color, Fill, HAlign, NumFmt, PivotDataCell, PivotDateGroup, PivotField, PivotFilter, PivotFunc,
PivotItemRef, PivotLayout, PivotLookup, PivotShowAs, PivotSort, PivotTable, PivotValue, Series, Style, StyleId, Workbook,
@@ -32,7 +32,6 @@ pub use items::{distinct_labels, func_caption, item_label};
use output::data_cols_exceed_sheet;
pub use output::{CellKind, OutCell, Output, RowKind};
use output::{cell_style, look};
/// Largest source block read (cells).
pub const MAX_SOURCE_CELLS: u64 = 10_000_000;
/// Largest report written (cells).
@@ -61,12 +60,52 @@ pub struct Source {
/// Numeric with a date number format.
pub dates: Vec<bool>,
pub rows: Vec<Vec<Value>>,
/// The sheet row of each record (blank rows are skipped).
pub record_rows: Vec<u32>,
}
impl Source {
pub fn col(&self, name: &str) -> Option<usize> {
self.headers.iter().position(|h| h.eq_ignore_ascii_case(name))
}
/// Per record: the column's cell is a number whose own format is a date (Excel caches such
/// a number as `<d>` and sorts it after errors), and no cell of the column holds that number
/// with a non-date format: a number in any General cell is a number item, whatever the row
/// order or report filter. Looks up each distinct style once.
pub fn date_cells(&self, wb: &Workbook, col: usize) -> Vec<bool> {
let (Some(sh), Ok(off)) = (wb.sheet(self.sheet), u32::try_from(col)) else {
return vec![false; self.rows.len()];
};
let c = self.range.start.col + off;
let mut memo: HashMap<StyleId, bool> = HashMap::new();
let mut dates: Vec<bool> = self
.rows
.iter()
.zip(&self.record_rows)
.map(|(rec, &row)| {
rec.get(col).is_some_and(Value::is_number)
&& *memo
.entry(sh.style_id(CellRef::new(row, c)))
.or_insert_with_key(|id| crate::display::number_format(wb.styles.get(*id).num_fmt.as_str()).is_date())
})
.collect();
if !dates.contains(&true) {
return dates;
}
let number = |rec: &Vec<Value>| match rec.get(col) {
Some(Value::Number(n)) => Some(n.to_bits()),
_ => None,
};
let general: HashSet<u64> = dates.iter().zip(&self.rows).filter(|(d, _)| !**d).filter_map(|(_, rec)| number(rec)).collect();
if !general.is_empty() {
for (d, rec) in dates.iter_mut().zip(&self.rows) {
if *d && number(rec).is_some_and(|n| general.contains(&n)) {
*d = false;
}
}
}
dates
}
}
/// Absolute reference text for a range on a sheet: `Sheet1!$A$1:$E$20`.
@@ -159,6 +198,7 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result<So
}
let w = headers.len();
let mut rows = Vec::new();
let mut record_rows = Vec::new();
let mut numeric = vec![true; w];
let mut any = vec![false; w];
if r.end.row > r.start.row {
@@ -179,6 +219,7 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result<So
}
}
}
record_rows.push(row);
rows.push(rec);
}
}
@@ -186,7 +227,7 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result<So
*n = *n && *a;
}
let dates = numeric.iter().zip(formats.iter()).map(|(n, f)| *n && crate::display::parsed(f).is_date()).collect();
Ok(Source { sheet: si, range: r, headers, formats, numeric, dates, rows })
Ok(Source { sheet: si, range: r, headers, formats, numeric, dates, rows, record_rows })
}
/// Computes a PivotTable report from the workbook.
+228 -72
View File
@@ -1,4 +1,4 @@
use super::items::{Acc, FieldItems, build_tree, collect_siblings, is_collapsed, item_label};
use super::items::{Acc, ByValue, FieldItems, build_tree, collect_siblings, date_flags, is_collapsed, item_label};
use super::output::{
AggMap, CellKind, ColKind, ColSpec, Ctx, Grid, Line, LineKind, Output, RowKind, ValSrc, caption, data_cols_exceed_sheet, flatten_cols,
};
@@ -83,6 +83,8 @@ struct AggregateInput<'a> {
filter_sets: &'a [Option<HashSet<String>>],
row_fmts: &'a [String],
col_fmts: &'a [String],
row_dates: &'a [Vec<bool>],
col_dates: &'a [Vec<bool>],
empty: bool,
}
@@ -119,12 +121,14 @@ fn aggregate_record(
return Ok(());
}
let mut row_path = Vec::with_capacity(input.rows.len());
for (((column, field), items), fmt) in input.rows.iter().zip(data.row_items.iter_mut()).zip(input.row_fmts) {
row_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, ri));
for ((((column, field), items), fmt), dates) in input.rows.iter().zip(data.row_items.iter_mut()).zip(input.row_fmts).zip(input.row_dates) {
let date = dates.get(ri).copied().unwrap_or(false);
row_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, date, ri));
}
let mut col_path = Vec::with_capacity(input.cols.len());
for (((column, field), items), fmt) in input.cols.iter().zip(data.col_items.iter_mut()).zip(input.col_fmts) {
col_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, ri));
for ((((column, field), items), fmt), dates) in input.cols.iter().zip(data.col_items.iter_mut()).zip(input.col_fmts).zip(input.col_dates) {
let date = dates.get(ri).copied().unwrap_or(false);
col_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, date, ri));
}
for row_depth in 0..=row_path.len() {
for col_depth in 0..=col_path.len() {
@@ -197,23 +201,49 @@ struct HeaderInput<'a> {
k: usize,
l: usize,
headers_on: bool,
row_caption: Option<&'a str>,
data_caption: Option<&'a str>,
col_caption: Option<&'a str>,
grand_caption: &'a str,
classic: bool,
show_values_row: bool,
}
fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
let HeaderInput { vals, row_fields, col_fields, col_items, col_fmts, vpos, data_cols, specs, row_levels, compact, on_rows, k, l, headers_on } =
input;
let HeaderInput {
vals,
row_fields,
col_fields,
col_items,
col_fmts,
vpos,
data_cols,
specs,
row_levels,
compact,
on_rows,
k,
l,
headers_on,
row_caption,
data_caption,
col_caption,
grand_caption,
classic,
show_values_row,
} = input;
let val_name = |vi: usize| vals.get(vi).map(|(_, v)| v.name.clone()).unwrap_or_default();
let row_header = |g: &mut Grid, r: usize| {
if row_levels == 0 || !headers_on {
return;
}
if compact {
g.set(r, 0, Value::text("Row Labels"), CellKind::Header, 0, None);
g.set(r, 0, Value::text(row_caption.unwrap_or("Row Labels")), CellKind::Header, 0, None);
} else {
// One column per row field, Σ Values ("Values") at its place.
let mut names: Vec<&str> = row_fields.iter().map(|f| f.source_col.as_str()).collect();
// One column per row field, Σ Values (its caption, "Values" by default) at its place.
let mut names: Vec<&str> = row_fields.iter().map(|f| f.header()).collect();
if let Some(p) = vpos {
names.insert(p.min(names.len()), "Values");
names.insert(p.min(names.len()), data_caption.unwrap_or("Values"));
}
for (i, name) in names.into_iter().enumerate() {
g.set(r, i, Value::text(name), CellKind::Header, 0, None);
@@ -223,12 +253,23 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
// ---- header rows
if col_fields.is_empty() {
let classic = classic && !compact && k == 1 && headers_on;
if classic {
let r = g.push_row(RowKind::Header)?;
g.set(r, 0, Value::text(val_name(0)), CellKind::Header, 0, None);
}
if !compact && k > 1 && !on_rows && show_values_row && headers_on {
let r = g.push_row(RowKind::Header)?;
g.set(r, l, Value::text(data_caption.unwrap_or("Values")), CellKind::Header, 0, None);
}
let r = g.push_row(RowKind::Header)?;
row_header(g, r);
for (j, (_, vi)) in data_cols.iter().enumerate() {
match vi {
Some(vi) => 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.
Some(vi) => {
let caption = if classic { "Total".to_string() } else { val_name(*vi) };
g.set(r, l + j, Value::text(caption), CellKind::Header, 0, None);
}
None if on_rows => g.set(r, l + j, Value::text("Total"), CellKind::Header, 0, None),
None => {}
}
@@ -239,7 +280,11 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
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() };
let caption = if compact {
col_caption.unwrap_or("Column Labels").to_string()
} else {
col_fields.first().map(|f| f.header().to_string()).unwrap_or_default()
};
g.set(cap, l, Value::text(caption), CellKind::Header, 0, None);
}
let levels = col_fields.len() + usize::from(k > 1 && !on_rows);
@@ -257,8 +302,8 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
let same = prev.is_some_and(|p| p.kind != ColKind::Grand && p.path.get(..=lv) == spec.path.get(..=lv));
if !same {
let Some(item) = col_items.get(lv).and_then(|fi| fi.get(it)) else { continue };
let fmt = if item.formatted { col_fmts.get(lv).cloned() } else { None };
g.set(first_level + lv, c, item.value.clone(), CellKind::ColLabel, 0, fmt);
let fmt = if item.formatted && item.caption.is_none() { col_fmts.get(lv).cloned() } else { None };
g.set(first_level + lv, c, item.shown_value(), CellKind::ColLabel, 0, fmt);
}
}
if k > 1
@@ -269,7 +314,7 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
}
ColKind::Subtotal => {
let lv = spec.path.len().saturating_sub(1);
let label = spec.path.last().and_then(|it| col_items.get(lv).map(|fi| fi.label(*it))).unwrap_or_default();
let label = spec.path.last().and_then(|it| col_items.get(lv).map(|fi| fi.shown_label(*it))).unwrap_or_default();
let text = match vi {
Some(vi) if k > 1 => caption(&label, &val_name(*vi)),
_ => caption(&label, "Total"),
@@ -279,7 +324,7 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
ColKind::Grand => {
let text = match vi {
Some(vi) if k > 1 => format!("Total {}", val_name(*vi)),
_ => "Grand Total".to_string(),
_ => grand_caption.to_string(),
};
g.set(first_level, c, Value::text(text), CellKind::ColLabel, 0, None);
}
@@ -292,7 +337,6 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
Ok(())
}
struct ValueLookup<'a> {
wb: &'a Workbook,
source: &'a Source,
@@ -539,8 +583,11 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
let filter_fmts: Vec<String> = filters.iter().map(|f| fmt_of(f.0)).collect();
let filter_sets: Vec<Option<HashSet<String>>> =
filters.iter().map(|(_, field, _, _)| field.selected.as_ref().map(|s| s.iter().map(|v| v.to_ascii_lowercase()).collect())).collect();
let row_fmts: Vec<String> = rows.iter().map(|(c, _)| fmt_of(*c)).collect();
let col_fmts: Vec<String> = cols.iter().map(|(c, _)| fmt_of(*c)).collect();
let field_fmt = |c: usize, f: &PivotField| f.number_format.clone().unwrap_or_else(|| fmt_of(c));
let row_fmts: Vec<String> = rows.iter().map(|(c, f)| field_fmt(*c, f)).collect();
let col_fmts: Vec<String> = cols.iter().map(|(c, f)| field_fmt(*c, f)).collect();
let row_dates: Vec<Vec<bool>> = rows.iter().map(|(c, f)| date_flags(wb, src, *c, f.date_group)).collect();
let col_dates: Vec<Vec<bool>> = cols.iter().map(|(c, f)| date_flags(wb, src, *c, f.date_group)).collect();
let aggregate = aggregate_source(
AggregateInput {
wb,
@@ -555,33 +602,83 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
filter_sets: &filter_sets,
row_fmts: &row_fmts,
col_fmts: &col_fmts,
row_dates: &row_dates,
col_dates: &col_dates,
empty,
},
&mut probe,
)?;
let AggregateData { row_items, col_items, aggs, row_set, col_set, col_leaves: _ } = aggregate;
let AggregateData { mut row_items, mut col_items, aggs, row_set, col_set, col_leaves: _ } = aggregate;
for (fi, (_, f)) in row_items.iter_mut().zip(rows.iter()) {
fi.apply(f);
}
for (fi, (_, f)) in col_items.iter_mut().zip(cols.iter()) {
fi.apply(f);
}
let get = |rp: &[u32], cp: &[u32], vi: usize| -> Option<Value> {
let (vs, v) = vals.get(vi)?;
let accs = aggs.get(&(rp.to_vec(), cp.to_vec()))?;
match vs {
ValSrc::Col(_) => accs.get(vi).map(|a| a.result(v.func)),
ValSrc::Calc(i) => {
let sum = |name: &str| -> Value {
src.col(name)
.and_then(|c| extra.iter().position(|x| *x == c))
.and_then(|j| accs.get(k + j))
.map(|a| a.result(PivotFunc::Sum))
.unwrap_or(Value::Number(0.0))
};
Some(calc.value(wb, *i, &sum))
}
}
};
// ---- axes
let row_fields: Vec<&PivotField> = rows.iter().map(|(_, f)| *f).collect();
let col_fields: Vec<&PivotField> = 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 row_tree = build_tree(&row_paths, 0, &row_fields, &row_items);
let col_tree = build_tree(&col_paths, 0, &col_fields, &col_items);
// 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. A scope naming an item that isn't there sorts by the
// grand total, as the writer then drops it.
let scope_path = |f: &PivotField, others: &[(usize, &PivotField)], other_items: &[FieldItems]| -> Vec<u32> {
let mut path = Vec::new();
for ((_, o), oi) in others.iter().zip(other_items) {
let Some(e) = f.sort_scope.iter().find(|e| e.is_of(o)) else { break };
match oi.find(&e.item) {
Some(i) => path.push(i),
None => return Vec::new(),
}
}
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<u32>, Vec<u32>> = HashMap::new();
collect_siblings(&row_tree, &mut Vec::new(), &mut siblings);
let level0: Vec<u32> = row_tree.iter().map(|n| n.item).collect();
let val_names: Vec<String> = vals.iter().map(|(_, v)| v.name.clone()).collect();
let grand_caption = pt.grand_total_caption.as_deref().unwrap_or("Grand Total");
let ctx = Ctx { pt, rows: row_fields.clone(), row_items, row_fmts: row_fmts.clone(), vpos, val_names: val_names.clone() };
let mut lines: Vec<Line> = Vec::new();
if row_levels == 0 {
lines.push(Line { kind: LineKind::Item(false), leaf: true, path: vec![], values: true, labels: vec![], vi: None });
} else {
if pt.layout == PivotLayout::Tabular {
ctx.flatten_tabular(&row_tree, 0, None, &mut Vec::new(), &[], &mut lines);
ctx.flatten_tabular(&row_tree, 0, None, &mut Vec::new(), &[], &mut Vec::new(), &mut lines);
} else {
ctx.flatten(&row_tree, 0, None, &mut Vec::new(), &mut lines);
ctx.flatten(&row_tree, 0, None, &mut Vec::new(), &mut Vec::new(), &mut lines);
}
// With only Σ Values in Rows its items are the totals already.
if pt.grand_totals_cols && !rows.is_empty() {
@@ -596,7 +693,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
if on_rows {
lines.extend(val_names.iter().enumerate().map(|(vi, name)| grand(format!("Total {name}"), Some(vi))));
} else {
lines.push(grand("Grand Total".into(), None));
lines.push(grand(grand_caption.into(), None));
}
}
}
@@ -604,7 +701,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
if cols.is_empty() {
specs.push(ColSpec { kind: ColKind::Leaf, path: vec![] });
} else {
flatten_cols(&col_tree, 0, &col_fields, &col_items, pt.subtotals, &mut Vec::new(), &mut specs);
flatten_cols(&col_tree, 0, &col_fields, &col_items, pt, &mut Vec::new(), &mut specs);
if pt.grand_totals_rows {
specs.push(ColSpec { kind: ColKind::Grand, path: vec![] });
}
@@ -678,6 +775,12 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
k,
l,
headers_on: pt.show_headers,
row_caption: pt.row_header_caption.as_deref(),
data_caption: pt.data_caption.as_deref(),
col_caption: pt.col_header_caption.as_deref(),
grand_caption: pt.grand_total_caption.as_deref().unwrap_or("Grand Total"),
classic: pt.classic_layout,
show_values_row: pt.show_values_row,
},
)?;
let val_name = |vi: usize| vals.get(vi).map(|(_, value)| value.name.clone()).unwrap_or_default();
@@ -714,7 +817,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
return None;
}
let mut parts: Vec<String> =
spec.path.iter().enumerate().map(|(lv, it)| col_items.get(lv).map(|fi| fi.label(*it)).unwrap_or_default()).collect();
spec.path.iter().enumerate().map(|(lv, it)| col_items.get(lv).map(|fi| fi.shown_label(*it)).unwrap_or_default()).collect();
if let Some(vi) = vi
&& (k > 1 || parts.is_empty())
{
@@ -733,15 +836,6 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
} else {
Some(row_levels.saturating_sub(1) as u32)
};
let item_refs = |fields: &[&PivotField], items: &[FieldItems], path: &[u32]| -> Vec<PivotItemRef> {
path.iter()
.enumerate()
.filter_map(|(d, it)| {
let (f, item) = (fields.get(d)?, items.get(d)?.get(*it)?);
Some(PivotItemRef { field: f.source_col.clone(), label: item.label.clone(), value: item.value.clone() })
})
.collect()
};
let mut data: Vec<PivotDataCell> = Vec::new();
for line in &lines {
let rk = match line.kind {
@@ -764,40 +858,102 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
if !line.values {
continue;
}
let rp = line.path.as_slice();
for (j, (si, col_vi)) in data_cols.iter().enumerate() {
let line_vi = col_vi.or(line.vi);
let (Some(spec), Some(vi)) = (specs.get(*si), &line_vi) else { continue };
let Some((_, vdef)) = vals.get(*vi) else { continue };
let cp = spec.path.as_slice();
let Some(raw) = lookup.get(rp, cp, *vi) else { continue };
let context = ShowContext { row_path: rp, col_path: cp, value_index: *vi, level0: &level0, siblings: &siblings, cache: &show_cache };
let shown = show_value(vdef, raw, &lookup, &context);
// Every value cell of the report is indexed, so a report that needs more cells than
// the index cap is rejected outright — never written with a truncated index that
// would answer #REF! for the values the sheet shows.
if data.len() >= MAX_INDEXED_CELLS {
return Err(format!("A PivotTable report can have at most {MAX_INDEXED_CELLS} value cells."));
}
let mut items = item_refs(&ctx.rows, &ctx.row_items, rp);
items.extend(item_refs(&col_fields, &col_items, cp));
data.push(PivotDataCell {
data_field: vdef.name.clone(),
source_col: vdef.source_col.clone(),
items,
row: u32::try_from(r).unwrap_or(u32::MAX),
col: u32::try_from(l + j).unwrap_or(u32::MAX),
});
if let Some(pr) = probe.as_deref_mut() {
if pr.at == Some((r, l + j)) {
pr.hit = Some((rp.to_vec(), cp.to_vec()));
}
if let Some(cells) = pr.cells.as_mut() {
cells.insert((r, l + j));
}
}
g.set(r, l + j, shown, ck.1, 0, data_fmt.get(*vi).cloned().flatten());
}
fill_line_values(
&mut g,
r,
line,
&data_cols,
&specs,
&vals,
&data_fmt,
l,
ck.1,
pt,
&ctx,
&col_fields,
&col_items,
&lookup,
&level0,
&siblings,
&show_cache,
&mut probe,
&mut data,
)?;
}
Ok(Output { width: g.width as u32, grid: g.rows, row_kinds: g.kinds, body_offset, chart_rows, chart_cols, label_col, data })
}
#[allow(clippy::too_many_arguments)]
fn fill_line_values(
g: &mut Grid,
r: usize,
line: &Line,
data_cols: &[(usize, Option<usize>)],
specs: &[ColSpec],
vals: &[(ValSrc, &PivotValue)],
data_fmt: &[Option<String>],
l: usize,
ck: CellKind,
pt: &PivotTable,
ctx: &Ctx<'_>,
col_fields: &[&PivotField],
col_items: &[FieldItems],
lookup: &ValueLookup<'_>,
level0: &[u32],
siblings: &HashMap<Vec<u32>, Vec<u32>>,
show_cache: &ShowCache,
probe: &mut Option<&mut Probe>,
data: &mut Vec<PivotDataCell>,
) -> Result<(), String> {
let rp = line.path.as_slice();
for (j, (si, col_vi)) in data_cols.iter().enumerate() {
let line_vi = col_vi.or(line.vi);
let (Some(spec), Some(vi)) = (specs.get(*si), &line_vi) else { continue };
let Some((_, vdef)) = vals.get(*vi) else { continue };
let cp = spec.path.as_slice();
let Some(raw) = lookup.get(rp, cp, *vi) else {
// No records: blank, or the "For empty cells show" caption (a number when it
// reads as one, as Excel stores `missingCaption="0"`).
if let Some(c) = &pt.empty_caption {
let v = c.trim().parse::<f64>().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, 0, fmt);
}
continue;
};
let context = ShowContext { row_path: rp, col_path: cp, value_index: *vi, level0, siblings, cache: show_cache };
let shown = show_value(vdef, raw, lookup, &context);
if data.len() >= MAX_INDEXED_CELLS {
return Err(format!("A PivotTable report can have at most {MAX_INDEXED_CELLS} value cells."));
}
let mut items = item_refs(&ctx.rows, &ctx.row_items, rp);
items.extend(item_refs(col_fields, col_items, cp));
data.push(PivotDataCell {
data_field: vdef.name.clone(),
source_col: vdef.source_col.clone(),
items,
row: u32::try_from(r).unwrap_or(u32::MAX),
col: u32::try_from(l + j).unwrap_or(u32::MAX),
});
if let Some(pr) = probe.as_deref_mut() {
if pr.at == Some((r, l + j)) {
pr.hit = Some((rp.to_vec(), cp.to_vec()));
}
if let Some(cells) = pr.cells.as_mut() {
cells.insert((r, l + j));
}
}
g.set(r, l + j, shown, ck, 0, data_fmt.get(*vi).cloned().flatten());
}
Ok(())
}
fn item_refs(fields: &[&PivotField], items: &[FieldItems], path: &[u32]) -> Vec<PivotItemRef> {
path.iter()
.enumerate()
.filter_map(|(d, it)| {
let (f, item) = (fields.get(d)?, items.get(d)?.get(*it)?);
Some(PivotItemRef { field: f.source_col.clone(), label: item.label.clone(), value: item.value.clone() })
})
.collect()
}
+99 -18
View File
@@ -1,6 +1,9 @@
use std::collections::HashSet;
use super::{CellError, HashMap, MONTHS, Ordering, PivotDateGroup, PivotField, PivotFunc, PivotSort, Source, Value, Workbook, datetime_from_serial};
use super::{
CellError, HashMap, MONTHS, Ordering, PivotDateGroup, PivotField, PivotFunc, PivotSort, Source, Value, Workbook, datetime_from_serial,
number_to_text,
};
// ---------------------------------------------------------------- items
@@ -14,6 +17,20 @@ pub(super) struct Item {
first: usize,
/// The value is a number shown with the source format.
pub(super) formatted: bool,
/// The item's custom name (a renamed item).
pub(super) caption: Option<String>,
/// Position in the field's manual item order.
rank: Option<usize>,
}
impl Item {
/// The value shown: the custom name, else the item's value.
pub(super) fn shown_value(&self) -> Value {
self.caption.as_deref().map(Value::text).unwrap_or_else(|| self.value.clone())
}
pub(super) fn shown_label(&self) -> &str {
self.caption.as_deref().unwrap_or(&self.label)
}
}
#[derive(Default)]
@@ -22,12 +39,15 @@ pub(super) struct FieldItems {
index: HashMap<String, u32>,
}
/// Sort classes: numbers, text, logicals, errors, dates (a number whose own cell has a date
/// format, which Excel caches as `<d>` and sorts after errors), blanks.
fn cmp_items(a: &Item, b: &Item) -> Ordering {
a.class.cmp(&b.class).then(a.num.total_cmp(&b.num)).then_with(|| gridcraft_core::compare_text(&a.text, &b.text))
}
/// (identity key, item) for a source value under a field's date grouping.
fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: usize) -> (String, Item) {
/// (identity key, item) for a source value under a field's date grouping; `date` marks a number
/// whose cell has a date format.
fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, date: bool, first: usize) -> (String, Item) {
let it = |value: Value, label: String, class: u8, num: f64, formatted: bool| Item {
text: label.to_lowercase(),
value,
@@ -36,9 +56,11 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first:
num,
first,
formatted,
caption: None,
rank: None,
};
match v {
Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 4, 0.0, false)),
Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 5, 0.0, false)),
Value::Number(n) => {
if group != PivotDateGroup::None
&& let Some(dt) = datetime_from_serial(wb.date_system, *n)
@@ -55,8 +77,9 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first:
};
return (format!("g{key}"), it(Value::text(label.as_str()), label, 0, key, false));
}
let label = crate::display::format(v, fmt, wb).text;
(format!("n{}", n.to_bits()), it(v.clone(), label, 0, *n, true))
let shown = crate::display::format(v, fmt, wb);
let class = if date { 4 } else { 0 };
(format!("n{}", n.to_bits()), it(v.clone(), shown.text, class, *n, true))
}
Value::Text(t) => (format!("t{}", t.to_lowercase()), it(v.clone(), t.to_string(), 1, 0.0, false)),
Value::Bool(b) => {
@@ -64,13 +87,13 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first:
(format!("l{l}"), it(Value::Bool(*b), l.into(), 2, *b as u8 as f64, false))
}
Value::Error(e) => (format!("e{}", e.as_str()), it(v.clone(), e.as_str().into(), 3, 0.0, false)),
Value::Array(_) => make_item(wb, &v.scalar(), group, fmt, first),
Value::Array(_) => make_item(wb, &v.scalar(), group, fmt, date, first),
}
}
impl FieldItems {
pub(super) fn intern(&mut self, wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: usize) -> u32 {
let (key, item) = make_item(wb, v, group, fmt, first);
pub(super) fn intern(&mut self, wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, date: bool, first: usize) -> u32 {
let (key, item) = make_item(wb, v, group, fmt, date, first);
if let Some(i) = self.index.get(&key) {
return *i;
}
@@ -85,20 +108,50 @@ impl FieldItems {
pub(super) fn label(&self, i: u32) -> String {
self.get(i).map(|x| x.label.clone()).unwrap_or_default()
}
pub(super) 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).
pub(super) fn find(&self, label: &str) -> Option<u32> {
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).
pub(super) fn apply(&mut self, f: &PivotField) {
if f.item_captions.is_empty() && f.item_order.is_empty() {
return;
}
let mut order: HashMap<String, usize> = HashMap::new();
for (i, l) in f.item_order.iter().enumerate() {
order.entry(l.to_lowercase()).or_insert(i);
}
let mut captions: HashMap<String, &str> = HashMap::new();
for (l, c) in &f.item_captions {
captions.entry(l.to_lowercase()).or_insert(c.as_str());
}
for it in &mut self.items {
let raw = if it.formatted { Some(number_to_text(it.num).to_lowercase()) } else { None };
it.rank = order.get(&it.text).or_else(|| raw.as_ref().and_then(|r| order.get(r))).copied();
it.caption = captions.get(&it.text).or_else(|| raw.as_ref().and_then(|r| captions.get(r))).map(|c| c.to_string());
}
}
}
/// The label of a source value under a date grouping (for filters and field lists).
pub fn item_label(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str) -> String {
make_item(wb, v, group, fmt, 0).1.label
make_item(wb, v, group, fmt, false, 0).1.label
}
/// Distinct item labels of a source column, sorted like the field list shows them.
pub fn distinct_labels(wb: &Workbook, src: &Source, col: usize, group: PivotDateGroup, limit: usize) -> Vec<String> {
let mut fi = FieldItems::default();
let fmt = src.formats.get(col).map(String::as_str).unwrap_or("General");
let dates = date_flags(wb, src, col, group);
for (i, r) in src.rows.iter().enumerate() {
if let Some(v) = r.get(col) {
fi.intern(wb, v, group, fmt, i);
fi.intern(wb, v, group, fmt, dates.get(i).copied().unwrap_or(false), i);
}
if fi.items.len() > 100_000 {
break;
@@ -109,6 +162,11 @@ pub fn distinct_labels(wb: &Workbook, src: &Source, col: usize, group: PivotDate
items.into_iter().take(limit).map(|i| i.label).collect()
}
/// [`Source::date_cells`] for an ungrouped field; a date-grouped field doesn't use them.
pub(super) fn date_flags(wb: &Workbook, src: &Source, col: usize, group: PivotDateGroup) -> Vec<bool> {
if group == PivotDateGroup::None { src.date_cells(wb, col) } else { Vec::new() }
}
// ---------------------------------------------------------------- aggregation
#[derive(Clone, Debug, Default)]
@@ -252,7 +310,17 @@ pub(super) struct Node {
pub(super) children: Vec<Node>,
}
pub(super) fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems]) -> Vec<Node> {
/// 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.
pub(super) type ValueLookup<'a> = &'a dyn Fn(&[u32], &[u32], usize) -> Option<f64>;
pub(super) struct ByValue<'a> {
pub(super) fields: Vec<Option<(usize, Vec<u32>)>>,
pub(super) value: ValueLookup<'a>,
}
pub(super) fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems], by_value: &ByValue) -> Vec<Node> {
let (Some(field), Some(fi)) = (fields.get(depth), items.get(depth)) else { return vec![] };
let mut order: Vec<u32> = Vec::new();
let mut groups: HashMap<u32, Vec<&[u32]>> = HashMap::new();
@@ -265,23 +333,36 @@ pub(super) fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField],
g.push(p);
}
}
let mut nodes: Vec<Node> = order
let vi = by_value.fields.get(depth).and_then(Option::as_ref).filter(|_| field.sort != PivotSort::None);
let mut nodes: Vec<(Option<f64>, Node)> = order
.into_iter()
.map(|it| {
let ps = groups.remove(&it).unwrap_or_default();
Node { item: it, children: build_tree(&ps, depth + 1, fields, items) }
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();
let by = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) {
let by_label = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) {
(Some(x), Some(y)) => match field.sort {
PivotSort::Asc => cmp_items(x, y),
PivotSort::Desc => cmp_items(y, x),
PivotSort::None => x.first.cmp(&y.first),
PivotSort::None => x.rank.unwrap_or(usize::MAX).cmp(&y.rank.unwrap_or(usize::MAX)).then_with(|| {
// Date groups are in date order, like the groups Excel's cache lists.
if field.date_group == PivotDateGroup::None { x.first.cmp(&y.first) } else { cmp_items(x, y) }
}),
},
_ => Ordering::Equal,
};
nodes.sort_by(by);
nodes
// By value: numbers in the sort direction, then items without a number; ties by label.
let by_key = |a: &Option<f64>, b: &Option<f64>| match (a, b) {
(Some(x), Some(y)) if field.sort == PivotSort::Desc => y.total_cmp(x),
(Some(x), Some(y)) => x.total_cmp(y),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
};
nodes.sort_by(|(ka, a), (kb, b)| by_key(ka, kb).then_with(|| by_label(a, b)));
nodes.into_iter().map(|(_, n)| n).collect()
}
pub(super) fn is_collapsed(field: &PivotField, label: &str) -> bool {
+98 -71
View File
@@ -151,11 +151,22 @@ pub(super) struct Ctx<'a> {
pub(super) val_names: Vec<String>,
}
/// A label cell of a report line: (column, value, indent, number format).
type Label = (usize, Value, u8, Option<String>);
/// Whether an axis field shows subtotals (its own setting, else the table's).
pub(super) fn shows_subtotals(pt: &PivotTable, f: Option<&&PivotField>) -> bool {
f.and_then(|f| f.subtotal).unwrap_or(pt.subtotals)
}
impl Ctx<'_> {
fn label_cell(&self, depth: usize, item: u32) -> (Value, Option<String>, String) {
let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else { return (Value::Empty, None, String::new()) };
let fmt = if it.formatted { self.row_fmts.get(depth).cloned() } else { None };
(it.value.clone(), fmt, it.label.clone())
/// (shown value, number format, item label, shown label) of a row item.
fn label_cell(&self, depth: usize, item: u32) -> (Value, Option<String>, String, String) {
let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else {
return (Value::Empty, None, String::new(), String::new());
};
let fmt = if it.formatted && it.caption.is_none() { self.row_fmts.get(depth).cloned() } else { None };
(it.shown_value(), fmt, it.label.clone(), it.shown_label().to_string())
}
/// (column, indent) of a row level (Σ Values counts as a level) in Compact/Outline form.
@@ -184,86 +195,87 @@ impl Ctx<'_> {
/// The Σ Values level at row field depth `depth`: one item per value field, each followed by
/// the row fields below it (`nodes`) or, innermost, holding that value.
fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec<u32>, out: &mut Vec<Line>) {
fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec<u32>, repeat: &mut Vec<Label>, out: &mut Vec<Line>) {
let (col, indent) = self.level_cell(depth);
for (vi, name) in self.val_names.iter().enumerate() {
let labels = vec![(col, Value::text(name.as_str()), indent, None)];
let mut labels = repeat.clone();
labels.push((col, Value::text(name.as_str()), indent, None));
let leaf = nodes.is_empty();
out.push(Line { kind: LineKind::Item(!leaf), leaf, path: prefix.clone(), values: leaf, labels, vi: Some(vi) });
if !leaf {
self.flatten(nodes, depth, Some(vi), prefix, out);
self.flatten(nodes, depth, Some(vi), prefix, repeat, out);
}
}
}
pub(super) fn flatten(&self, nodes: &[Node], depth: usize, vi: Option<usize>, prefix: &mut Vec<u32>, out: &mut Vec<Line>) {
/// Compact and Outline rows. `repeat` holds the labels of enclosing items repeated on each
/// row (Outline, Repeat Item Labels).
pub(super) fn flatten(
&self,
nodes: &[Node],
depth: usize,
vi: Option<usize>,
prefix: &mut Vec<u32>,
repeat: &mut Vec<Label>,
out: &mut Vec<Line>,
) {
if self.values_here(depth, vi) {
self.flatten_values(nodes, depth, prefix, out);
self.flatten_values(nodes, depth, prefix, repeat, out);
return;
}
let n = self.rows.len();
let outline = self.pt.layout == PivotLayout::Outline;
let field = self.rows.get(depth);
let subtotals = shows_subtotals(self.pt, field);
// Σ Values still to come below this level: totals need one line per value field.
let values_below = vi.is_none() && self.vpos.is_some();
let (col, indent) = self.level_cell(depth + usize::from(vi.is_some() && self.vpos.is_some()));
for node in nodes {
prefix.push(node.item);
let (v, fmt, label) = self.label_cell(depth, node.item);
let collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label));
let (v, fmt, label, shown) = self.label_cell(depth, node.item);
let collapsed = depth + 1 < n && field.is_some_and(|f| is_collapsed(f, &label));
let leaf = depth + 1 >= n || collapsed || node.children.is_empty();
let mut labels = repeat.clone();
labels.push((col, v.clone(), indent, fmt.clone()));
let pushed = !leaf && outline && field.is_some_and(|f| f.repeat_labels);
if leaf && !values_below {
out.push(Line {
kind: LineKind::Item(depth + 1 < n),
leaf: true,
path: prefix.clone(),
values: true,
labels: vec![(col, v, indent, fmt)],
vi,
});
out.push(Line { kind: LineKind::Item(depth + 1 < n), leaf: true, path: prefix.clone(), values: true, labels, vi });
} else if leaf {
out.push(Line {
kind: LineKind::Item(true),
leaf: false,
path: prefix.clone(),
values: false,
labels: vec![(col, v, indent, fmt)],
vi,
});
out.push(Line { kind: LineKind::Item(true), leaf: false, path: prefix.clone(), values: false, labels, vi });
// Outline gives each level its own column, so the captions go in the Values
// column even when the levels between are collapsed away.
let level = if self.pt.layout == PivotLayout::Outline { self.vpos.unwrap_or(depth + 1) } else { depth + 1 };
self.flatten_values(&[], level, prefix, out);
let level = if outline { self.vpos.unwrap_or(depth + 1) } else { depth + 1 };
self.flatten_values(&[], level, prefix, repeat, out);
} else if values_below {
// Subtotals per value field, below the group (one line can't hold them all).
out.push(Line {
kind: LineKind::Item(true),
leaf: false,
path: prefix.clone(),
values: false,
labels: vec![(col, v, indent, fmt)],
vi,
});
self.flatten(&node.children, depth + 1, None, prefix, out);
if self.pt.subtotals {
self.value_subtotals(col, indent, &label, prefix, out);
out.push(Line { kind: LineKind::Item(true), leaf: false, path: prefix.clone(), values: false, labels, vi });
if pushed {
repeat.push((col, v, indent, fmt));
}
self.flatten(&node.children, depth + 1, None, prefix, repeat, out);
if pushed {
repeat.pop();
}
if subtotals {
self.value_subtotals(col, indent, &shown, prefix, out);
}
} else {
let top = self.pt.subtotals && self.pt.subtotals_top;
out.push(Line {
kind: LineKind::Item(true),
leaf: false,
path: prefix.clone(),
values: top,
labels: vec![(col, v, indent, fmt)],
vi,
});
self.flatten(&node.children, depth + 1, vi, prefix, out);
if self.pt.subtotals && !self.pt.subtotals_top {
let top = subtotals && self.pt.subtotals_top;
out.push(Line { kind: LineKind::Item(true), leaf: false, path: prefix.clone(), values: top, labels, vi });
if pushed {
repeat.push((col, v, indent, fmt));
}
self.flatten(&node.children, depth + 1, vi, prefix, repeat, out);
if pushed {
repeat.pop();
}
if subtotals && !self.pt.subtotals_top {
out.push(Line {
kind: LineKind::Subtotal,
leaf: false,
path: prefix.clone(),
values: true,
labels: vec![(col, Value::text(caption(&label, "Total")), indent, None)],
labels: vec![(col, Value::text(caption(&shown, "Total")), indent, None)],
vi,
});
}
@@ -278,59 +290,73 @@ impl Ctx<'_> {
nodes: &[Node],
depth: usize,
prefix: &mut Vec<u32>,
pending: &[(usize, Value, u8, Option<String>)],
pending: &[Label],
repeat: &mut Vec<Label>,
out: &mut Vec<Line>,
) {
for (vi, name) in self.val_names.iter().enumerate() {
let mut labels: Vec<(usize, Value, u8, Option<String>)> = if vi == 0 { pending.to_vec() } else { vec![] };
let mut labels: Vec<Label> = if vi == 0 { pending.to_vec() } else { repeat.clone() };
labels.push((depth, Value::text(name.as_str()), 0, None));
if nodes.is_empty() {
out.push(Line { kind: LineKind::Item(false), leaf: true, path: prefix.clone(), values: true, labels, vi: Some(vi) });
} else {
self.flatten_tabular(nodes, depth, Some(vi), prefix, &labels, out);
self.flatten_tabular(nodes, depth, Some(vi), prefix, &labels, repeat, out);
}
}
}
/// Tabular rows: an item's label sits on its first child's row (`pending`); `repeat` holds
/// the labels of enclosing items repeated on the other rows (Repeat Item Labels).
#[allow(clippy::too_many_arguments)]
pub(super) fn flatten_tabular(
&self,
nodes: &[Node],
depth: usize,
vi: Option<usize>,
prefix: &mut Vec<u32>,
pending: &[(usize, Value, u8, Option<String>)],
pending: &[Label],
repeat: &mut Vec<Label>,
out: &mut Vec<Line>,
) {
if self.values_here(depth, vi) {
self.flatten_tabular_values(nodes, depth, prefix, pending, out);
self.flatten_tabular_values(nodes, depth, prefix, pending, repeat, out);
return;
}
let n = self.rows.len();
let field = self.rows.get(depth);
let values_below = vi.is_none() && self.vpos.is_some();
let col = depth + usize::from(vi.is_some() && self.vpos.is_some());
for (i, node) in nodes.iter().enumerate() {
prefix.push(node.item);
let (v, fmt, label) = self.label_cell(depth, node.item);
let mut labels: Vec<(usize, Value, u8, Option<String>)> = if i == 0 { pending.to_vec() } else { vec![] };
labels.push((col, v, 0, fmt));
let collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label));
let (v, fmt, label, shown) = self.label_cell(depth, node.item);
let mut labels: Vec<Label> = if i == 0 { pending.to_vec() } else { repeat.clone() };
labels.push((col, v.clone(), 0, fmt.clone()));
let collapsed = depth + 1 < n && field.is_some_and(|f| is_collapsed(f, &label));
if depth + 1 >= n || collapsed || node.children.is_empty() {
if values_below {
self.flatten_tabular_values(&[], self.vpos.unwrap_or(depth + 1), prefix, &labels, out);
self.flatten_tabular_values(&[], self.vpos.unwrap_or(depth + 1), prefix, &labels, repeat, out);
} else {
out.push(Line { kind: LineKind::Item(false), leaf: true, path: prefix.clone(), values: true, labels, vi });
}
} else {
self.flatten_tabular(&node.children, depth + 1, vi, prefix, &labels, out);
if self.pt.subtotals && values_below {
self.value_subtotals(col, 0, &label, prefix, out);
} else if self.pt.subtotals {
let pushed = field.is_some_and(|f| f.repeat_labels);
if pushed {
repeat.push((col, v, 0, fmt));
}
self.flatten_tabular(&node.children, depth + 1, vi, prefix, &labels, repeat, out);
if pushed {
repeat.pop();
}
let subtotals = shows_subtotals(self.pt, field);
if subtotals && values_below {
self.value_subtotals(col, 0, &shown, prefix, out);
} else if subtotals {
out.push(Line {
kind: LineKind::Subtotal,
leaf: false,
path: prefix.clone(),
values: true,
labels: vec![(col, Value::text(caption(&label, "Total")), 0, None)],
labels: vec![(col, Value::text(caption(&shown, "Total")), 0, None)],
vi,
});
}
@@ -345,20 +371,21 @@ pub(super) fn flatten_cols(
depth: usize,
fields: &[&PivotField],
items: &[FieldItems],
subtotals: bool,
pt: &PivotTable,
prefix: &mut Vec<u32>,
out: &mut Vec<ColSpec>,
) {
let n = fields.len();
let field = fields.get(depth);
for node in nodes {
prefix.push(node.item);
let label = items.get(depth).map(|fi| fi.label(node.item)).unwrap_or_default();
let collapsed = depth + 1 < n && fields.get(depth).is_some_and(|f| is_collapsed(f, &label));
let collapsed = depth + 1 < n && field.is_some_and(|f| is_collapsed(f, &label));
if depth + 1 >= n || collapsed || node.children.is_empty() {
out.push(ColSpec { kind: ColKind::Leaf, path: prefix.clone() });
} else {
flatten_cols(&node.children, depth + 1, fields, items, subtotals, prefix, out);
if subtotals {
flatten_cols(&node.children, depth + 1, fields, items, pt, prefix, out);
if shows_subtotals(pt, field) {
out.push(ColSpec { kind: ColKind::Subtotal, path: prefix.clone() });
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ mod print;
pub use pivot::{
PIVOT_INDEXER, PivotCalcField, PivotDataCell, PivotDateGroup, PivotField, PivotFilter, PivotFunc, PivotIndexer, PivotItemRef, PivotLayout,
PivotLookup, PivotShowAs, PivotSort, PivotTable, PivotValue, pivot_key,
PivotLookup, PivotScopeItem, PivotShowAs, PivotSort, PivotTable, PivotValue, pivot_key,
};
pub use print::{EditRange, HfPage, LineInfo, Orientation, PageOrder, PrintSettings, SheetProtection, password_hash};
+71
View File
@@ -37,6 +37,25 @@ pub enum PivotDateGroup {
Days,
}
/// An item of a field on the other axis that a sort by value takes its values from (e.g. the
/// "Apples" column). The field is named by source column and date grouping, so two levels
/// grouped from one date column (Years and Quarters) stay apart.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct PivotScopeItem {
pub source_col: String,
pub date_group: PivotDateGroup,
/// The item's label.
pub item: String,
}
impl PivotScopeItem {
/// Whether this names an item of `f`.
pub fn is_of(&self, f: &PivotField) -> bool {
self.date_group == f.date_group && self.source_col.eq_ignore_ascii_case(&f.source_col)
}
}
/// A field placed in the Rows or Columns area.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
@@ -47,6 +66,35 @@ pub struct PivotField {
pub date_group: PivotDateGroup,
/// Item labels whose detail is hidden (collapsed).
pub collapsed_items: Vec<String>,
/// Custom name shown in the field's header (Field Settings > Custom Name); `None` = the
/// source column name.
pub caption: Option<String>,
/// 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<String>,
/// Where `sort_by` takes its values: an item of each field on the other axis, outer field
/// first, up to the first field it doesn't name (e.g. sort the rows by the "Apples" column).
/// Empty, or naming an item that isn't there, = the grand total.
pub sort_scope: Vec<PivotScopeItem>,
/// Manual item order (item labels), used when `sort` is `None`; unlisted items follow in
/// source order (date groups in date order).
pub item_order: Vec<String>,
/// Renamed items: (item label, caption shown instead).
pub item_captions: Vec<(String, String)>,
/// Subtotals of this field; `None` = the table's `subtotals`.
pub subtotal: Option<bool>,
/// Repeat the item labels on every row (Outline/Tabular, Repeat Item Labels).
pub repeat_labels: bool,
/// Number format of the item labels (Field Settings > Number Format); `None` = the source
/// column's format.
pub number_format: Option<String>,
}
impl PivotField {
/// The header text: the custom name, else the source column name.
pub fn header(&self) -> &str {
self.caption.as_deref().unwrap_or(&self.source_col)
}
}
/// Summarize-values-by function.
@@ -134,6 +182,22 @@ pub struct PivotTable {
pub show_headers: bool,
/// Area written by the last refresh.
pub last_range: Option<RangeRef>,
/// Header of the row labels in Compact layout; `None` = "Row Labels".
pub row_header_caption: Option<String>,
/// Header of the column labels in Compact layout; `None` = "Column Labels".
pub col_header_caption: Option<String>,
/// Caption of the Values field; `None` = "Values".
pub data_caption: Option<String>,
/// Caption of the grand totals; `None` = "Grand Total".
pub grand_total_caption: Option<String>,
/// Shown in value cells that summarize no records (For empty cells show); `None` = blank.
pub empty_caption: Option<String>,
/// Show the Values row: a header row with `data_caption` above the value captions
/// (Outline/Tabular, several values and no column field). Excel's default is on.
pub show_values_row: bool,
/// Classic PivotTable layout (fields dragged in the grid): with one value field and no
/// column field, the value caption sits above the row headers and the column reads "Total".
pub classic_layout: bool,
/// Calculated fields, usable in the Values area by name.
pub calculated_fields: Vec<PivotCalcField>,
/// Where GETPIVOTDATA finds the report's value cells, as of the last refresh. Shared between
@@ -316,6 +380,13 @@ impl Default for PivotTable {
style: "PivotStyleLight16".into(),
show_headers: true,
last_range: None,
row_header_caption: None,
col_header_caption: None,
data_caption: None,
grand_total_caption: None,
empty_caption: None,
show_values_row: true,
classic_layout: false,
calculated_fields: vec![],
data_index: PivotLookup::default(),
values_on_rows: false,
+31 -6
View File
@@ -30,11 +30,12 @@
use std::collections::HashMap;
use std::fmt::Write as _;
use gridcraft_core::date::datetime_from_serial;
use gridcraft_core::date::{datetime_from_serial, iso_ymd, serial_from_iso_ymd};
use gridcraft_core::{CellRef, DateSystem, RangeRef, Value, number_to_text};
use gridcraft_formula::quote_sheet;
use gridcraft_model::{
PivotCalcField, PivotDateGroup, PivotField, PivotFilter, PivotFunc, PivotLayout, PivotShowAs, PivotSort, PivotTable, PivotValue, Workbook,
PivotCalcField, PivotDateGroup, PivotField, PivotFilter, PivotFunc, PivotLayout, PivotScopeItem, PivotShowAs, PivotSort, PivotTable, PivotValue,
Workbook,
};
use crate::IoError;
@@ -47,7 +48,6 @@ mod write;
pub use read::{CachesIn, ExternalPivot, KeptSource, read_pivots};
pub use write::PivotWriter;
pub const CT_PIVOT_TABLE: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml";
pub const CT_PIVOT_CACHE_DEF: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml";
pub const CT_PIVOT_CACHE_REC: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml";
@@ -62,7 +62,31 @@ 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}";
const EXT_X14_PIVOT_TABLE: &str = "{962EF5D1-5CA2-4c93-8EF4-DBF5C05439D2}";
/// The `x14:pivotField` extension (Repeat Item Labels: `fillDownLabels`).
const EXT_X14_FIELD: &str = "{2946ED86-A175-432a-8AC1-64E0C546D7DE}";
/// The `x14:pivotTableDefinition` extension (Show the Values row: `hideValuesRow`).
const EXT_X14_TABLE: &str = "{962EF5D1-5CA2-4c93-8EF4-DBF5C05439D2}";
/// The `xpdl:pivotTableDefinition16` extension: the table's default subtotal setting
/// (`EnabledSubtotalsDefault`) when its fields override it.
const EXT_XPDL_TABLE: &str = "{747A6164-185A-40DC-8AA5-F01512510D54}";
const NS_XPDL: &str = "http://schemas.microsoft.com/office/spreadsheetml/2016/pivotdefaultlayout";
/// The field index of the Values (data) field in pivot areas and `<colFields>` is -2, which
/// `<reference field>` stores unsigned.
const VALUES_FIELD: &str = "4294967294";
/// `<pivotField>` attributes that turn on a custom subtotal function.
const CUSTOM_SUBTOTALS: [&str; 11] = [
"sumSubtotal",
"countASubtotal",
"avgSubtotal",
"maxSubtotal",
"minSubtotal",
"productSubtotal",
"countSubtotal",
"stdDevSubtotal",
"stdDevPSubtotal",
"varSubtotal",
"varPSubtotal",
];
const NS_X14: &str = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main";
/// GridCraft's `dataField` extension: `<gc:summary func="distinctCount"/>` marks a value field
/// written as `subtotal="count"` as a Distinct Count (see the module documentation).
@@ -163,10 +187,11 @@ fn group_caption(g: PivotDateGroup) -> &'static str {
}
}
/// `2024-03-05T00:00:00` for a date serial.
/// `2024-03-05T00:00:00` for a date serial; a time alone is on `1899-12-30` (see [`iso_ymd`]).
fn iso(sys: DateSystem, serial: f64) -> Option<String> {
let d = datetime_from_serial(sys, serial)?;
Some(format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}", d.year, d.month, d.day, d.hour, d.minute, d.second))
let (y, m, day) = iso_ymd(sys, d.year, d.month, d.day);
Some(format!("{y:04}-{m:02}-{day:02}T{:02}:{:02}:{:02}", d.hour, d.minute, d.second))
}
/// `3/5/2024` for a date serial (group boundary captions).
+136 -8
View File
@@ -1,11 +1,9 @@
use super::{
CellRef, Ctx, DateSystem, EXT_GC_DATA_FIELD, El, HashMap, IoError, MAX_FIELDS, PivotCalcField, PivotDateGroup, PivotField, PivotFilter,
PivotFunc, PivotLayout, PivotShowAs, PivotSort, PivotTable, PivotValue, RangeRef, abs_range, func_caption, func_from, number_to_text,
quote_sheet,
CUSTOM_SUBTOTALS, CellRef, Ctx, DateSystem, EXT_GC_DATA_FIELD, EXT_X14_FIELD, EXT_X14_TABLE, EXT_XPDL_TABLE, El, HashMap, IoError, MAX_FIELDS,
PivotCalcField, PivotDateGroup, PivotField, PivotFilter, PivotFunc, PivotLayout, PivotScopeItem, PivotShowAs, PivotSort, PivotTable, PivotValue,
RangeRef, VALUES_FIELD, abs_range, func_caption, func_from, number_to_text, quote_sheet, serial_from_iso_ymd,
};
// ================================================================ reading
/// A cache field as read.
#[derive(Clone, Debug, Default)]
struct FieldIn {
@@ -125,7 +123,10 @@ fn item_label_el(e: &El, sys: DateSystem) -> String {
"m" => "(blank)".into(),
"n" => v.trim().parse::<f64>().ok().filter(|n| n.is_finite()).map(number_to_text).unwrap_or_else(|| v.to_string()),
"b" => if matches!(v.trim(), "1" | "true") { "TRUE" } else { "FALSE" }.into(),
"d" => crate::sheet_read::parse_iso_datetime(v, sys).map(number_to_text).unwrap_or_else(|| v.to_string()),
// Cache dates count real days from the epoch, as Excel writes them (see `iso`).
"d" => crate::sheet_read::parse_iso_datetime_with(v, |y, m, d| serial_from_iso_ymd(sys, y, m, d))
.map(number_to_text)
.unwrap_or_else(|| v.to_string()),
_ => v.to_string(),
}
}
@@ -286,6 +287,47 @@ fn items_of(e: &El) -> Vec<&El> {
e.child("items").map(|it| it.kids("item").filter(|i| i.attr("t").is_none_or(|t| t == "data")).collect()).unwrap_or_default()
}
/// Whether a `<pivotField>` shows subtotals: custom subtotal functions (Field Settings ›
/// Subtotals › Custom, `sumSubtotal` and the like, ECMA-376 §18.10.1.69) turn them on as
/// well as `defaultSubtotal`.
fn field_subtotals(e: &El) -> bool {
has_custom_subtotals(e) || e.flag("defaultSubtotal", true)
}
fn has_custom_subtotals(e: &El) -> bool {
CUSTOM_SUBTOTALS.iter().any(|a| e.flag(a, false))
}
/// The x14 element of an `<extLst><ext uri>` (e.g. `x14:pivotField`), if present.
fn x14_ext<'a>(e: &'a El, uri: &str) -> Option<&'a El> {
let ext = e.child("extLst")?.kids("ext").find(|x| x.attr("uri").is_some_and(|u| u.eq_ignore_ascii_case(uri)))?;
ext.children.first()
}
/// A pivot field's sort by value, from its `<autoSortScope>`: the data field (dataFields
/// position) the scope's Values reference (`4294967294`) names, and the other references as
/// (cache field, index into that field's `<items>`). `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<AutoSort> {
let refs = e.path(&["autoSortScope", "pivotArea", "references"])?;
let r = refs.kids("reference").find(|r| r.attr("field") == Some(VALUES_FIELD))?;
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.
fn field_ref(cx: &mut Ctx<'_>, cache: &CacheIn, i: usize) -> Option<(String, PivotDateGroup)> {
let f = cache.fields.get(i)?;
@@ -359,7 +401,9 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
PivotLayout::Tabular
};
if let Some(f) = first_axis {
pt.subtotals = f.flag("defaultSubtotal", true);
pt.subtotals = x14_ext(x, EXT_XPDL_TABLE)
.and_then(|e| e.attr("EnabledSubtotalsDefault"))
.map_or_else(|| field_subtotals(f), |v| v == "1" || v.eq_ignore_ascii_case("true"));
pt.subtotals_top = f.flag("subtotalTop", true);
}
pt.grand_totals_rows = x.flag("colGrandTotals", true);
@@ -367,12 +411,24 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
pt.show_headers = x.flag("showHeaders", true);
pt.enable_show_details = x.flag("enableDrill", true);
pt.style = x.child("pivotTableStyleInfo").and_then(|s| s.attr("name")).unwrap_or("").to_string();
let caption = |a: &str| x.attr(a).filter(|c| !c.is_empty()).map(str::to_string);
pt.row_header_caption = caption("rowHeaderCaption");
pt.col_header_caption = caption("colHeaderCaption");
pt.data_caption = caption("dataCaption").filter(|c| c != "Values");
pt.grand_total_caption = caption("grandTotalCaption");
pt.empty_caption = caption("missingCaption").filter(|_| x.flag("showMissing", true));
pt.show_values_row = !x14_ext(x, EXT_X14_TABLE).is_some_and(|e| e.flag("hideValuesRow", false));
pt.classic_layout = x.flag("gridDropZones", false);
if x.child("calculatedItems").is_some() || x.path(&["filters", "filter"]).is_some() {
cx.warn(format!("PivotTable \"{}\": calculated items and label/value filters are not supported", pt.name));
}
let mut filters: Vec<PivotFilter> = Vec::new();
// Per axis field (in rows-then-columns order): its cache field and its sort by value.
let mut sort_by: Vec<Option<AutoSort>> = Vec::new();
let mut axis_ix: Vec<usize> = Vec::new();
let table_subtotals = pt.subtotals;
// Lower-cased names of the fields already filtered on an axis, the first of which wins (as
// `same` compares them): scanning the filters for each field would be quadratic.
let mut axis_filtered: std::collections::HashSet<String> = std::collections::HashSet::new();
@@ -391,21 +447,48 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
let i = i as usize;
let Some((name, group)) = field_ref(cx, cache, i) else { continue };
let labels: &[String] = cache.fields.get(i).map(|f| f.labels()).unwrap_or(&[]);
let mut f = PivotField { source_col: name.clone(), date_group: group, sort: PivotSort::None, collapsed_items: vec![] };
let mut f = PivotField { source_col: name.clone(), date_group: group, sort: PivotSort::None, ..PivotField::default() };
let mut by = None;
if let Some(e) = pf(i) {
f.sort = match e.attr("sortType") {
Some("ascending") => PivotSort::Asc,
Some("descending") => PivotSort::Desc,
_ => PivotSort::None,
};
by = auto_sort_scope(e);
f.caption = e.attr("name").filter(|n| !n.is_empty()).map(str::to_string);
let custom = has_custom_subtotals(e);
if custom {
cx.warn(format!("PivotTable field \"{name}\": custom subtotal functions are not supported; it shows the automatic subtotal"));
}
let own = field_subtotals(e);
f.subtotal = (own != table_subtotals).then_some(own);
f.repeat_labels = x14_ext(e, EXT_X14_FIELD).is_some_and(|x| x.flag("fillDownLabels", false));
if group == PivotDateGroup::None {
f.number_format = e
.attr_u32("numFmtId")
.filter(|id| *id != 0)
.and_then(|id| crate::tables::builtin_format(id).map(str::to_string).or_else(|| cx.num_fmts.get(&id).cloned()));
}
let items = items_of(e);
let lab = |it: &El| it.attr_u32("x").and_then(|k| labels.get(k as usize)).cloned();
f.collapsed_items = items.iter().filter(|it| !it.flag("sd", true)).filter_map(|it| lab(it)).collect();
f.item_captions = items.iter().filter_map(|it| Some((lab(it)?, it.attr("n").filter(|n| !n.is_empty())?.to_string()))).collect();
// Not auto-sorted: the `<items>` list fixes the order, even when it happens to be
// cache order (new items follow it). The engine shows date groups in date order,
// so they keep a list only when it was reordered.
let xs: Vec<u32> = items.iter().filter_map(|it| it.attr_u32("x")).collect();
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)) && axis_filtered.insert(name.to_lowercase()) {
let shown: Vec<String> = items.iter().filter(|it| !it.flag("h", false)).filter_map(|it| lab(it)).collect();
filters.push(PivotFilter { source_col: name.clone(), selected: Some(shown) });
}
}
sort_by.push(by);
axis_ix.push(i);
v.push(f);
}
(v, values_at)
@@ -446,9 +529,12 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
pt.filters = filters;
// Values.
// dataFields position -> value index.
let mut data_value: Vec<Option<usize>> = Vec::new();
if let Some(df) = x.child("dataFields") {
truncated |= df.kids("dataField").nth(MAX_FIELDS).is_some();
for d in df.kids("dataField").take(MAX_FIELDS) {
data_value.push(None);
let Some(i) = d.attr_u32("fld").map(|i| i as usize) else { continue };
let Some(f) = cache.fields.get(i) else { continue };
let func = match d.attr("subtotal") {
@@ -488,9 +574,51 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
.filter(|id| *id != 0)
.and_then(|id| crate::tables::builtin_format(id).map(str::to_string).or_else(|| cx.num_fmts.get(&id).cloned()));
let name = d.attr("name").map(str::to_string).unwrap_or_else(|| format!("{} of {}", func_caption(func), f.name));
if let Some(last) = data_value.last_mut() {
*last = Some(pt.values.len());
}
pt.values.push(PivotValue { source_col: f.name.clone(), func, name, show_as, number_format });
}
}
// Sort scopes: each reference must name an item of a field on the other axis.
let n_rows = pt.rows.len();
let keys: Vec<(String, PivotDateGroup)> = pt.rows.iter().chain(pt.columns.iter()).map(|f| (f.source_col.clone(), f.date_group)).collect();
let item_label = |j: usize, x: usize| -> Option<String> {
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<Option<(usize, Vec<PivotScopeItem>)>> = Vec::with_capacity(sort_by.len());
for (p, by) in sort_by.into_iter().enumerate() {
let others = if p < n_rows { n_rows..keys.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(())?;
let (source_col, date_group) = keys.get(k).cloned().ok_or(())?;
Ok(PivotScopeItem { source_col, date_group, item: item_label(j, x).ok_or(())? })
})
.collect::<Result<Vec<_>, ()>>()?;
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,
keys.get(p).map(|k| k.0.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(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); the first of a
// lower-cased name wins, looked up in a set rather than by scanning the fields kept so far.
+136 -25
View File
@@ -191,10 +191,9 @@ impl PivotWriter {
let mut v = Vec::new();
for p in &self.pending {
if let Some(pt) = wb.sheet(p.sheet).and_then(|s| s.pivots.get(p.idx)) {
for val in &pt.values {
if let Some(f) = &val.number_format
&& !v.contains(f)
{
let fields = pt.rows.iter().chain(pt.columns.iter()).filter_map(|f| f.number_format.as_ref());
for f in pt.values.iter().filter_map(|v| v.number_format.as_ref()).chain(fields) {
if !v.contains(f) {
v.push(f.clone());
}
}
@@ -637,6 +636,20 @@ fn cache_xml(c: &Cache, records_rid: Option<&str>, sys: DateSystem, refresh_on_l
s
}
/// A field's `<items>` 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<usize> {
let mut order: Vec<usize> = (0..labels.len()).collect();
if let Some(af) = af.filter(|f| f.sort == PivotSort::None && !f.item_order.is_empty()) {
let mut rank: HashMap<String, usize> = 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
}
struct PivotTableLayout<'a> {
row_fields: Vec<usize>,
column_fields: Vec<usize>,
@@ -678,9 +691,17 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn
let compact = pt.layout == PivotLayout::Compact;
let name = if pt.name.trim().is_empty() { format!("PivotTable{}", idx + 1) } else { pt.name.clone() };
let mut s = format!(
"{XML_DECL}<pivotTableDefinition xmlns=\"{NS_MAIN}\" name=\"{}\" cacheId=\"{cache_id}\" applyNumberFormats=\"0\" applyBorderFormats=\"0\" applyFontFormats=\"0\" applyPatternFormats=\"0\" applyAlignmentFormats=\"0\" applyWidthHeightFormats=\"1\" dataCaption=\"Values\" updatedVersion=\"6\" minRefreshableVersion=\"3\" useAutoFormatting=\"1\" itemPrintTitles=\"1\" createdVersion=\"6\" indent=\"0\"",
esc_attr(&name)
"{XML_DECL}<pivotTableDefinition xmlns=\"{NS_MAIN}\" name=\"{}\" cacheId=\"{cache_id}\" applyNumberFormats=\"0\" applyBorderFormats=\"0\" applyFontFormats=\"0\" applyPatternFormats=\"0\" applyAlignmentFormats=\"0\" applyWidthHeightFormats=\"1\" dataCaption=\"{}\"",
esc_attr(&name),
esc_attr(pt.data_caption.as_deref().unwrap_or("Values"))
);
if let Some(c) = &pt.grand_total_caption {
let _ = write!(s, " grandTotalCaption=\"{}\"", esc_attr(c));
}
if let Some(c) = &pt.empty_caption {
let _ = write!(s, " missingCaption=\"{}\"", esc_attr(c));
}
s.push_str(" updatedVersion=\"6\" minRefreshableVersion=\"3\" useAutoFormatting=\"1\" itemPrintTitles=\"1\" createdVersion=\"6\" indent=\"0\"");
match pt.layout {
PivotLayout::Compact => s.push_str(" outline=\"1\" outlineData=\"1\""),
PivotLayout::Outline => s.push_str(" compact=\"0\" compactData=\"0\" outline=\"1\" outlineData=\"1\""),
@@ -703,7 +724,17 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn
if !pt.grand_totals_rows {
s.push_str(" colGrandTotals=\"0\"");
}
s.push_str(" multipleFieldFilters=\"0\">");
s.push_str(" multipleFieldFilters=\"0\"");
if pt.classic_layout {
s.push_str(" gridDropZones=\"1\"");
}
if let Some(c) = &pt.row_header_caption {
let _ = write!(s, " rowHeaderCaption=\"{}\"", esc_attr(c));
}
if let Some(c) = &pt.col_header_caption {
let _ = write!(s, " colHeaderCaption=\"{}\"", esc_attr(c));
}
s.push('>');
// Location: the body (report filters sit above it).
let a = pt.anchor;
@@ -716,7 +747,16 @@ 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, layout.row_fields.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(layout.column_fields.len());
let first_data_row = if layout.column_fields.is_empty() { 1 } else { 1 + layout.column_fields.len() + usize::from(col_values.is_some()) };
// The engine shows the Values row and the classic caption row only with field headers on.
let values_row = layout.column_fields.is_empty()
&& !compact
&& pt.show_headers
&& ((col_values.is_some() && pt.show_values_row) || (k == 1 && pt.classic_layout));
let first_data_row = if layout.column_fields.is_empty() {
1 + usize::from(values_row)
} else {
1 + layout.column_fields.len() + usize::from(col_values.is_some())
};
let row_levels = layout.row_fields.len() + usize::from(row_values.is_some());
let first_data_col = if row_levels == 0 && layout.column_fields.is_empty() {
0
@@ -725,8 +765,11 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn
} else {
row_levels.max(1)
};
// Two or more value fields in Columns alone: Excel 365 would add a `Values` caption row.
let hide_values_row = col_values.is_some() && layout.column_fields.is_empty();
// Two or more value fields in Columns alone: Excel 365 adds a `Values` caption row
// when field headers are shown. Page-filter layouts retain their classic header row
// unless the table explicitly hides the Values row.
let hide_values_row =
col_values.is_some() && layout.column_fields.is_empty() && (layout.page_fields.is_empty() || !pt.show_values_row) && pt.show_headers;
let first_header_row = usize::from(!hide_values_row);
let _ = write!(
s,
@@ -738,7 +781,7 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn
}
s.push_str("/>");
write_pivot_fields(&mut s, pt, c, &layout);
write_pivot_fields(&mut s, pt, c, &layout, fmt_id);
axis_fields_xml(&mut s, "rowFields", &layout.row_fields, row_values);
axis_fields_xml(&mut s, "colFields", &layout.column_fields, col_values);
write_page_fields(&mut s, c, &layout);
@@ -748,11 +791,20 @@ fn table_xml(pt: &PivotTable, idx: usize, cache_id: u32, c: &Cache, fmt_id: &dyn
let _ = write!(s, " name=\"{}\"", esc_attr(&pt.style));
}
s.push_str(" showRowHeaders=\"1\" showColHeaders=\"1\" showRowStripes=\"0\" showColStripes=\"0\" showLastColumn=\"1\"/>");
if hide_values_row {
let _ = write!(
s,
"<extLst><ext uri=\"{EXT_X14_PIVOT_TABLE}\" xmlns:x14=\"{NS_X14}\"><x14:pivotTableDefinition hideValuesRow=\"1\"/></ext></extLst>"
);
let overridden = pt.rows.iter().chain(&pt.columns).any(|f| f.subtotal.is_some_and(|own| own != pt.subtotals));
if !pt.show_values_row || overridden {
s.push_str("<extLst>");
if !pt.show_values_row {
let _ = write!(s, "<ext uri=\"{EXT_X14_TABLE}\" xmlns:x14=\"{NS_X14}\"><x14:pivotTableDefinition hideValuesRow=\"1\"/></ext>");
}
if overridden {
let _ = write!(
s,
"<ext uri=\"{EXT_XPDL_TABLE}\" xmlns:xpdl=\"{NS_XPDL}\"><xpdl:pivotTableDefinition16 EnabledSubtotalsDefault=\"{}\"/></ext>",
u8::from(pt.subtotals)
);
}
s.push_str("</extLst>");
}
s.push_str("</pivotTableDefinition>");
s
@@ -763,7 +815,8 @@ fn axis_field<'a>(pt: &'a PivotTable, c: &Cache, i: usize) -> Option<&'a PivotFi
pt.rows.iter().chain(pt.columns.iter()).nth(p)
}
fn write_pivot_fields(s: &mut String, pt: &PivotTable, c: &Cache, layout: &PivotTableLayout<'_>) {
fn write_pivot_fields(s: &mut String, pt: &PivotTable, c: &Cache, layout: &PivotTableLayout<'_>, fmt_id: &dyn Fn(&str) -> Option<u32>) {
let vals = &layout.values;
let _ = write!(s, "<pivotFields count=\"{}\">", c.fields.len());
for (i, f) in c.fields.iter().enumerate() {
s.push_str("<pivotField");
@@ -792,6 +845,8 @@ fn write_pivot_fields(s: &mut String, pt: &PivotTable, c: &Cache, layout: &Pivot
}
if f.group.is_some() {
s.push_str(" numFmtId=\"14\"");
} else if let Some(id) = axis_field(pt, c, i).and_then(|f| f.number_format.as_deref()).and_then(fmt_id) {
let _ = write!(s, " numFmtId=\"{id}\"");
}
let filter = layout.hidden_fields.get(&i).copied();
let labels = f.item_labels();
@@ -808,25 +863,38 @@ fn write_pivot_fields(s: &mut String, pt: &PivotTable, c: &Cache, layout: &Pivot
s.push_str(" multipleItemSelectionAllowed=\"1\"");
}
s.push_str(" showAll=\"0\"");
if let Some(af) = axis_field(pt, c, i) {
let af = axis_field(pt, c, i);
if let Some(af) = af {
match af.sort {
PivotSort::Asc => s.push_str(" sortType=\"ascending\""),
PivotSort::Desc => s.push_str(" sortType=\"descending\""),
PivotSort::None => {}
}
if let Some(c) = &af.caption {
let _ = write!(s, " name=\"{}\"", esc_attr(c));
}
}
if !pt.subtotals {
let subtotals = af.and_then(|f| f.subtotal).unwrap_or(pt.subtotals);
if !subtotals {
s.push_str(" defaultSubtotal=\"0\"");
}
if !pt.subtotals_top {
s.push_str(" subtotalTop=\"0\"");
}
if axis.is_some() {
let collapsed: &[String] = axis_field(pt, c, i).map(|f| f.collapsed_items.as_slice()).unwrap_or(&[]);
let count = labels.len() + usize::from(pt.subtotals);
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 order = written_order(&labels, af);
let count = labels.len() + usize::from(subtotals);
let _ = write!(s, "><items count=\"{count}\">");
for (x, l) in labels.iter().enumerate() {
let _ = write!(s, "<item x=\"{x}\"");
for x in order {
let Some(l) = labels.get(x) else { continue };
let _ = write!(s, "<item");
if let Some((_, n)) = captions.iter().find(|(il, _)| same(il, l)) {
let _ = write!(s, " n=\"{}\"", esc_attr(n));
}
let _ = write!(s, " x=\"{x}\"");
if hide.get(x).copied().unwrap_or(false) {
s.push_str(" h=\"1\"");
}
@@ -835,10 +903,20 @@ fn write_pivot_fields(s: &mut String, pt: &PivotTable, c: &Cache, layout: &Pivot
}
s.push_str("/>");
}
if pt.subtotals {
if subtotals {
s.push_str("<item t=\"default\"/>");
}
s.push_str("</items></pivotField>");
s.push_str("</items>");
// 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 `<items>`), as
// the engine resolves them: outer field first, up to the first field it doesn't
// name; none when it names an item that isn't there (the grand total).
write_auto_sort_scope(s, pt, c, vals, af);
if af.is_some_and(|f| f.repeat_labels) {
let _ =
write!(s, "<extLst><ext uri=\"{EXT_X14_FIELD}\" xmlns:x14=\"{NS_X14}\"><x14:pivotField fillDownLabels=\"1\"/></ext></extLst>");
}
s.push_str("</pivotField>");
} else {
s.push_str("/>");
}
@@ -846,6 +924,37 @@ fn write_pivot_fields(s: &mut String, pt: &PivotTable, c: &Cache, layout: &Pivot
s.push_str("</pivotFields>");
}
fn write_auto_sort_scope(s: &mut String, pt: &PivotTable, c: &Cache, vals: &[(usize, &PivotValue)], af: Option<&PivotField>) {
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)))
else {
return;
};
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 (q, o) in others.iter().enumerate() {
// A field without a source column isn't on the axis (the engine skips it too).
let Some(j) = c.axis_map.get(base + q).copied().flatten() else { continue };
let Some(e) = af.sort_scope.iter().find(|e| e.is_of(o)) else { break };
let labels = c.fields.get(j).map(CField::item_labels).unwrap_or_default();
match written_order(&labels, Some(o)).iter().position(|x| labels.get(*x).is_some_and(|l| same(l, &e.item))) {
Some(pos) => refs.push((j.to_string(), pos)),
None => {
refs.truncate(1);
break;
}
}
}
}
let _ = write!(s, "<autoSortScope><pivotArea dataOnly=\"0\" outline=\"0\" fieldPosition=\"0\"><references count=\"{}\">", refs.len());
for (field, x) in &refs {
let _ = write!(s, "<reference field=\"{field}\" count=\"1\" selected=\"0\"><x v=\"{x}\"/></reference>");
}
s.push_str("</references></pivotArea></autoSortScope>");
}
fn write_page_fields(s: &mut String, c: &Cache, layout: &PivotTableLayout<'_>) {
if layout.page_fields.is_empty() {
return;
@@ -938,3 +1047,5 @@ fn axis_fields_xml(s: &mut String, tag: &str, idx: &[usize], values_at: Option<u
}
let _ = write!(s, "</{tag}>");
}
// ================================================================ reading
+6 -1
View File
@@ -939,6 +939,11 @@ fn read_craft_formula_text(
/// `2024-03-15`, `2024-03-15T10:30:00Z`, `10:30:00` → serial.
pub fn parse_iso_datetime(s: &str, sys: DateSystem) -> Option<f64> {
parse_iso_datetime_with(s, |y, m, d| serial_from_ymd(sys, y, m, d))
}
/// [`parse_iso_datetime`] with `ymd` turning the date part (year, month 1–12, day 1–31) into a serial.
pub(crate) fn parse_iso_datetime_with(s: &str, ymd: impl Fn(i64, i64, i64) -> Option<f64>) -> Option<f64> {
let s = s.trim_end_matches('Z');
let (date, time) = match s.split_once('T') {
Some((d, t)) => (d, Some(t)),
@@ -954,7 +959,7 @@ pub fn parse_iso_datetime(s: &str, sys: DateSystem) -> Option<f64> {
if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
return None;
}
serial = serial_from_ymd(sys, y, m, d)?;
serial = ymd(y, m, d)?;
}
if let Some(t) = time {
// Drop a time-zone offset.
+97 -9
View File
@@ -87,8 +87,20 @@ fn workbook() -> Workbook {
name: "Sales by Region".into(),
source: "Data!$A$1:$F$9".into(),
anchor: at("A4"),
rows: vec![PivotField { source_col: "Region".into(), sort: PivotSort::Asc, collapsed_items: vec!["East".into()], ..PivotField::default() }],
columns: vec![PivotField { sort: PivotSort::None, ..field("Product") }],
rows: vec![PivotField {
source_col: "Region".into(),
sort: PivotSort::Desc,
collapsed_items: vec!["East".into()],
caption: Some("Area".into()),
sort_by: Some("Sum of Sales".into()),
sort_scope: vec![PivotScopeItem { source_col: "Product".into(), item: "B".into(), ..PivotScopeItem::default() }],
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, item_order: vec!["C".into(), "A".into(), "B".into()], ..field("Product") }],
values: vec![
PivotValue {
source_col: "Sales".into(),
@@ -115,6 +127,13 @@ fn workbook() -> Workbook {
style: "PivotStyleMedium9".into(),
show_headers: false,
last_range: Some(rr("A2:H12")),
row_header_caption: Some("Vehicle".into()),
col_header_caption: Some("Type".into()),
data_caption: Some("Data".into()),
grand_total_caption: Some("Days".into()),
empty_caption: Some("0".into()),
show_values_row: false,
classic_layout: true,
calculated_fields: vec![],
data_index: Default::default(),
values_on_rows: false,
@@ -128,8 +147,14 @@ 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::Months, sort: PivotSort::Asc, collapsed_items: vec![] },
PivotField {
source_col: "Date".into(),
date_group: PivotDateGroup::Years,
sort: PivotSort::None,
collapsed_items: vec!["2024".into()],
..PivotField::default()
},
PivotField { source_col: "Date".into(), date_group: PivotDateGroup::Months, sort: PivotSort::Asc, ..PivotField::default() },
],
columns: vec![PivotField { sort: PivotSort::Desc, ..field("Product") }],
values: vec![
@@ -176,10 +201,7 @@ fn workbook() -> Workbook {
style: "PivotStyleDark3".into(),
show_headers: true,
last_range: Some(rr("K2:Z30")),
calculated_fields: vec![],
data_index: Default::default(),
values_on_rows: false,
values_position: None,
..PivotTable::default()
};
// Pivot 3: defaults, defined-name source, compact.
let p3 = PivotTable {
@@ -362,6 +384,11 @@ fn pivot_xml_details() {
"{t1}"
);
assert!(t1.contains("<field x=\"-2\"/>"));
// Sort by the values in the "B" column: Product's item B sits third in its `<items>`.
assert!(
t1.contains("<references count=\"2\"><reference field=\"4294967294\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference><reference field=\"1\" count=\"1\" selected=\"0\"><x v=\"2\"/></reference></references>"),
"{t1}"
);
assert!(t1.contains("subtotal=\"count\""));
assert!(t1.contains("numFmtId=\"4\""));
assert!(t1.contains("axis=\"axisPage\""));
@@ -775,6 +802,57 @@ fn data_on_rows_with_one_value_field_reads_without_warning() {
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 early_dates_in_caches_count_real_days() {
// Excel writes serial 1 as 1899-12-31 (ISO dates count days from 1899-12-30), not as the
// 1900 calendar's 1900-01-01, which it reads as serial 2.
let mut wb = workbook();
let date_style = wb.sheet(0).unwrap().cells.get(at("C2")).unwrap().style;
wb.sheet_mut(0).unwrap().cells.set(at("C2"), Cell { value: Value::number(1.5), formula: None, style: date_style, py: None });
let parts = unzip(&write_xlsx(&wb).unwrap());
let caches: String =
parts.iter().filter(|(k, _)| k.contains("pivotCacheDefinition")).map(|(_, v)| String::from_utf8_lossy(v).into_owned()).collect();
assert!(caches.contains("minDate=\"1899-12-31T12:00:00\"") && caches.contains("startDate=\"1899-12-31T00:00:00\""), "{caches}");
assert!(!caches.contains("1900-01-01T"), "{caches}");
}
#[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}");
{
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.show_values_row = 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=\"0\""), "{t3}");
assert!(t3.contains("<x14:pivotTableDefinition hideValuesRow=\"1\"/>"), "{t3}");
}
const SIMPLE_TABLE: &str = r#"<pivotTableDefinition name="Sales"><location ref="C1:D4"/><pivotFields><pivotField axis="axisRow"><items><item x="0"/><item t="default"/></items></pivotField><pivotField dataField="1"/></pivotFields><rowFields><field x="0"/></rowFields><dataFields><dataField name="Total" fld="1"/></dataFields></pivotTableDefinition>"#;
const CACHE_PART: &str = "xl/pivotCache/pivotCacheDefinition1.xml";
@@ -860,7 +938,7 @@ fn two_value_fields_without_columns_hide_the_values_row() {
});
let t = &two["xl/pivotTables/pivotTable1.xml"];
assert!(t.contains("firstHeaderRow=\"0\" firstDataRow=\"1\""), "{t}");
assert!(t.contains("<x14:pivotTableDefinition hideValuesRow=\"1\"/>"), "{t}");
assert!(!t.contains("hideValuesRow"), "{t}");
let one = small_pivot(&cols, |p| {
p.rows = vec![field("Region")];
p.values = vec![value("Sales")];
@@ -868,6 +946,16 @@ fn two_value_fields_without_columns_hide_the_values_row() {
let t = &one["xl/pivotTables/pivotTable1.xml"];
assert!(t.contains("firstHeaderRow=\"1\""), "{t}");
assert!(!t.contains("hideValuesRow"), "{t}");
let mut wb = workbook();
let p = &mut wb.sheet_mut(1).unwrap().pivots[2];
p.filters.clear();
p.layout = PivotLayout::Outline;
p.show_headers = true;
p.show_values_row = true;
p.values.push(value("Sales"));
let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
assert!(back.sheet(1).unwrap().pivots[2].show_values_row);
}
/// The "Trend" pivot of [`workbook`] with `values` as its value fields, written; returns the file
+2 -1
View File
@@ -105,7 +105,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
values on rows and GETPIVOTDATA done). Show Details (double-click a value, subtotal or grand total cell) lists
its source records on a new sheet. The "Enable show details" option (`pivot.options`
`enableShowDetails`, saved as `enableDrill`) turns it off; it has no PivotTable Options dialog
yet (command only).
yet (command only). Refreshing a file's pivot keeps its sort-by-value, captions, item order and layout settings; Excel's order among items with equal sort values is not reproduced.
- **Impact:** pivots are the analyst's main tool.
- **Estimate:** 20–30 h for beta (25–40 h full).
@@ -221,6 +221,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
| 2026-10-17 | minor | Conditional formatting: the 2-/3-colour scale branch of the New Formatting Rule dialog edits per-stop type/value/colour and updates rules in place (part of #1165) |
| 2026-10-15 | minor | §6: Maximum Iterations and Maximum Change in File › Options › Formulas; dropped the stale "no Options dialog yet" |
| 2026-10-15 | minor | §13: Solver prepares reports before committing the solution, model and report sheets together; report refusal preserves the workbook and Undo/Redo (#1050) |
| 2026-10-13 | minor | §8: refresh fidelity for file pivots (sort by value, captions, item order, layout settings) |
| 2026-10-13 | minor | §3: Excel 2010 conditional formats (`x14:conditionalFormattings`, cross-sheet rules) read, evaluated and written back in the extension |
| 2026-10-13 | trivial | §4: multi-level category axes landed |
| 2026-10-12 | minor | §9: next/previous sheet commands retain the current visible sheet and selection when there is no visible destination |
+2 -1
View File
@@ -85,7 +85,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. Advanced Filter copy-to preserves cells outside its result and rejects worksheet overflow (#1031). 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, GETPIVOTDATA, XLSX round-trip. Missing: slicers, timelines, calculated items, PivotCharts, value/label filters, number grouping, Generate 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, GETPIVOTDATA, sort by a value field, custom captions and item names, XLSX round-trip of the layout settings refreshed file pivots need. Missing: slicers, timelines, calculated items, PivotCharts, value/label filters, number grouping, Generate GetPivotData, data-model pivots. Round-trip never checked in Excel |
| Charts and sparklines | 8 | ~50% | ~30% | 40–60 | 25 chart kinds, all 2-D. Doughnut charts draw every series as a concentric ring (first series innermost), with editable hole size and first slice angle. The chart model holds title, legend position, a data-labels flag, gridlines flag, axis titles and chart data tables (legend keys, borders, XLSX round-trip and print/PDF); no axis scaling, error bars, per-point formatting, chart sheets, 3-D, surface, map, Pareto. Kinds survive XLSX round trip (#158, #161), except stock charts: only 3–4 series are a stock chart, and any other count is written and reimported as a line chart. [chart-parity.md](chart-parity.md) |
| Page layout, print, PDF | 5 | ~80% | ~55% | 12–20 | Page setup, print titles, breaks, page order, Page Break Preview, headers/footers, PDF export and printing. Paper sizes match Japanese Excel: B4/B5/B6 are the JIS sizes, ISO B4/B5/B6 stay reachable by name, and Japanese Postcard (はがき), Japanese Double Postcard (往復はがき), the chou/kaku envelopes and A6 are available. 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 (all 19 tools, no charts), Solver (Simplex LP, a local nonlinear method and Evolutionary; Answer, Sensitivity and Limits reports; Load/Save Model, Reset All and Solver Options; no Population report), Forecast Sheet. Missing: Analyze Data |
@@ -367,6 +367,7 @@ The inventory carried over from the 2026-10-07 ROADMAP.md, updated for what land
| 2026-10-15 | minor | Row auto-fit: line breaks count only in wrapping cells (Excel: wrap off shows one line, AutoFit gives one line); unwrapped multi-line cells from files no longer grow rows on open (no score change) |
| 2026-10-12 | minor | Worksheet functions 514 / 523 (98.3%; 505 working): GETPIVOTDATA |
| 2026-10-21 | minor | Automation: typed macros in the engine and `macro.*` commands, no interface yet (no score change); catalog 274 / 290 → 275 / 291 (View › Macros › Record Macro) |
| 2026-10-13 | minor | PivotTables: sort by a value field (`pivot.sort by:`), row/column/data/grand-total/empty-cell captions, field and item custom names, manual item order, per-field subtotals and number formats, Repeat Item Labels, Values row, classic layout. Refreshing 26 PivotTables from 11 real workbooks: 7,271 cell differences against Excel's saved output on main (6e984bb) → 3,446, the rest filters (#498) and Excel's order among tied values |
| 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) |