Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
297 changes: 257 additions & 40 deletions crates/engine/src/cmd/pivot.rs

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion crates/engine/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,11 @@ pub fn save_bytes_as(wb: &Workbook, path: &str, kind: FileKind) -> Result<Vec<u8
match kind {
// The extension picks the package kind; only the macro-enabled kinds (.xlsm, .xltm) carry
// the VBA project, so any other name saves without it, as Excel does.
FileKind::Xlsx => gridcraft_xlsx::write_xlsx_as(wb, gridcraft_xlsx::XlsxKind::from_path(path)).map_err(|e| EngineError::Other(e.to_string())),
FileKind::Xlsx => {
// The file name is what a PivotChart's link names the workbook by.
let name = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or_default();
gridcraft_xlsx::write_xlsx_named(wb, gridcraft_xlsx::XlsxKind::from_path(path), name).map_err(|e| EngineError::Other(e.to_string()))
}
FileKind::Xls => {
Err(EngineError::Other("Excel 97-2003 (.xls) is supported for import only. Save as .xlsx or another supported export format.".into()))
}
Expand Down
114 changes: 73 additions & 41 deletions crates/engine/src/pivot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,17 @@ pub struct Source {
}

impl Source {
/// The column of a field. Headers keep their spaces, as in Excel (`Region `); a name typed
/// without them still finds the field when only one header matches that way.
pub fn col(&self, name: &str) -> Option<usize> {
self.headers.iter().position(|h| h.eq_ignore_ascii_case(name))
self.headers.iter().position(|h| h.eq_ignore_ascii_case(name)).or_else(|| {
let name = name.trim();
let mut hits = self.headers.iter().enumerate().filter(|(_, h)| h.trim().eq_ignore_ascii_case(name));
match (hits.next(), hits.next()) {
(Some((i, _)), None) => Some(i),
_ => None,
}
})
}
}

Expand Down Expand Up @@ -134,8 +143,9 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result<So
let mut next_suffix: HashMap<String, usize> = HashMap::new();
let mut formats = Vec::new();
for c in r.start.col..=r.end.col {
let h = crate::display::cell_text(wb, sh, CellRef::new(r.start.row, c)).trim().to_string();
if h.is_empty() {
// A field is named by its header exactly, spaces included, as in Excel and in the cache.
let h = crate::display::cell_text(wb, sh, CellRef::new(r.start.row, c));
if h.trim().is_empty() {
return Err(FIELD_NAME_ERR.into());
}
let key = h.to_ascii_lowercase();
Expand Down Expand Up @@ -341,6 +351,10 @@ impl Acc {
}
}
fn result(&self, f: PivotFunc) -> Value {
// An item whose values are all blank shows an empty cell, whatever the function (Excel 365).
if self.count == 0 {
return Value::Empty;
}
let n = self.nums as f64;
match f {
PivotFunc::Count => return Value::number(self.count as f64),
Expand Down Expand Up @@ -384,23 +398,6 @@ impl Acc {
}
}

/// Excel's caption verb for a function ("Sum of Sales").
pub fn func_caption(f: PivotFunc) -> &'static str {
match f {
PivotFunc::Sum => "Sum",
PivotFunc::Count => "Count",
PivotFunc::Average => "Average",
PivotFunc::Max => "Max",
PivotFunc::Min => "Min",
PivotFunc::Product => "Product",
PivotFunc::CountNumbers => "Count Numbers",
PivotFunc::StdDev => "StdDev",
PivotFunc::StdDevP => "StdDevp",
PivotFunc::Var => "Var",
PivotFunc::VarP => "Varp",
}
}

// ---------------------------------------------------------------- trees

#[derive(Clone, Debug)]
Expand Down Expand Up @@ -959,7 +956,12 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
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 });
// Column fields and one value field: Excel labels the data line with the value's caption.
let labels = match val_names.first() {
Some(name) if k == 1 && !cols.is_empty() => vec![(0, Value::text(name.as_str()), 0, None)],
_ => vec![],
};
lines.push(Line { kind: LineKind::Item(false), leaf: true, path: vec![], values: true, labels, vi: None });
} else {
if pt.layout == PivotLayout::Tabular {
ctx.flatten_tabular(&row_tree, 0, None, &mut Vec::new(), &[], &mut lines);
Expand Down Expand Up @@ -1012,7 +1014,10 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
}

let compact = pt.layout == PivotLayout::Compact;
let l = if row_levels == 0 && cols.is_empty() {
// No row fields: no label column, except that column fields with one value field label the
// data line with the value's caption (Excel 365; with two or more values the report starts at
// the first column item).
let l = if row_levels == 0 && (cols.is_empty() || k > 1) {
0
} else if compact {
1
Expand Down Expand Up @@ -1081,27 +1086,42 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
};

// ---- header rows
// Σ Values in Columns: a row of value captions below the column fields. Alone it adds no row
// of its own (Excel 365 hides that Values row; the file says so, see the XLSX writer).
let values_in_cols = k > 1 && !on_rows;
if cols.is_empty() {
let r = g.push_row(RowKind::Header)?;
row_header(&mut g, r);
// Values on rows, no column field: Excel leaves the one data column's header empty.
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.
None if on_rows => g.set(r, l + j, Value::text("Total"), CellKind::Header, 0, None),
None => {}
if let Some(vi) = vi {
g.set(r, l + j, Value::text(val_name(*vi)), CellKind::Header, 0, None);
}
}
} else {
let cap = g.push_row(RowKind::Header)?;
if l > 0 && k == 1 {
g.set(cap, 0, Value::text(val_name(0)), CellKind::Header, 0, None);
}
if headers_on {
let caption = if compact { "Column Labels".to_string() } else { col_fields.first().map(|f| f.source_col.clone()).unwrap_or_default() };
g.set(cap, l, Value::text(caption), CellKind::Header, 0, None);
// The caption row holds the value field's caption (one value field, with row fields; without
// them the caption labels the data line instead, see `lines`) and, with headers shown, the
// column caption. With headers off and nothing to show in it, Excel leaves it out.
let value_caption = l > 0 && k == 1 && row_levels > 0;
if value_caption || headers_on {
let cap = g.push_row(RowKind::Header)?;
if value_caption {
g.set(cap, 0, Value::text(val_name(0)), CellKind::Header, 0, None);
}
if headers_on {
// Compact: "Column Labels". Outline and tabular name each column field from the
// first data column on, Σ Values as "Values".
let names: Vec<String> = if compact {
vec!["Column Labels".to_string()]
} else {
col_fields.iter().map(|f| f.source_col.clone()).chain(values_in_cols.then(|| "Values".to_string())).collect()
};
for (i, name) in names.into_iter().enumerate() {
g.set(cap, l + i, Value::text(name), CellKind::Header, 0, None);
}
}
}
let levels = cols.len() + usize::from(k > 1 && !on_rows);
let levels = cols.len() + usize::from(values_in_cols);
let first_level = g.rows.len();
for _ in 0..levels {
g.push_row(RowKind::Header)?;
Expand Down Expand Up @@ -1160,7 +1180,7 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
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))
.map(|a| if a.count == 0 { Value::Number(0.0) } else { a.result(PivotFunc::Sum) })
.unwrap_or(Value::Number(0.0))
};
Some(calc.value(wb, *i, &sum))
Expand Down Expand Up @@ -1257,12 +1277,22 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
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) = get(rp, cp, *vi) else { continue };
// Shown as a share or a running total, an intersection without records, or with only
// blank values, counts as 0 (Excel 365 shows 0 % and the carried running total there).
let counted = !matches!(vdef.show_as, PivotShowAs::Normal | PivotShowAs::Rank);
let raw = match get(rp, cp, *vi) {
Some(Value::Empty) if counted => Value::Number(0.0),
Some(v) => v,
None if counted => Value::Number(0.0),
None => continue,
};
let shown = match vdef.show_as {
PivotShowAs::Normal => raw,
PivotShowAs::PercentOfGrandTotal => ratio(raw, get(&[], &[], *vi)),
PivotShowAs::PercentOfColumnTotal => ratio(raw, get(&[], cp, *vi)),
PivotShowAs::PercentOfRowTotal => ratio(raw, get(rp, &[], *vi)),
// Excel leaves a running total's grand total line empty.
PivotShowAs::RunningTotal if line.kind == LineKind::Grand => Value::Empty,
PivotShowAs::RunningTotal => match (rp.first(), &raw) {
(Some(first), Value::Number(_)) => {
let mut acc = 0.0;
Expand All @@ -1282,16 +1312,18 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
},
PivotShowAs::Rank => match (rp.split_last(), raw.as_f64()) {
(Some((_, parent)), Some(me)) => {
// Dense ranks, as Excel gives them: ties share a rank and the next value
// takes the next one (5, 4, 4, 3 rank 1, 2, 2, 3).
let sibs = siblings.get(parent).cloned().unwrap_or_default();
let mut rank = 1u64;
let mut greater: HashSet<u64> = HashSet::new();
for sib in sibs {
let mut p = parent.to_vec();
p.push(sib);
if num(&get(&p, cp, *vi)).is_some_and(|x| x > me) {
rank += 1;
if let Some(x) = num(&get(&p, cp, *vi)).filter(|x| *x > me) {
greater.insert(if x == 0.0 { 0 } else { x.to_bits() });
}
}
Value::number(rank as f64)
Value::number(greater.len() as f64 + 1.0)
}
(None, _) => Value::Empty,
_ => raw,
Expand Down
95 changes: 95 additions & 0 deletions crates/model/src/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,80 @@ pub enum PivotFunc {
VarP,
}

impl PivotFunc {
/// Every function, in the order of Excel's Value Field Settings list.
pub const ALL: [PivotFunc; 11] = [
PivotFunc::Sum,
PivotFunc::Count,
PivotFunc::Average,
PivotFunc::Max,
PivotFunc::Min,
PivotFunc::Product,
PivotFunc::CountNumbers,
PivotFunc::StdDev,
PivotFunc::StdDevP,
PivotFunc::Var,
PivotFunc::VarP,
];

/// The word Excel puts in front of a new value field's name ("Sum of Sales"). Count Numbers
/// is captioned "Count", as in Excel.
pub fn caption(self) -> &'static str {
match self {
PivotFunc::Sum => "Sum",
PivotFunc::Count | PivotFunc::CountNumbers => "Count",
PivotFunc::Average => "Average",
PivotFunc::Max => "Max",
PivotFunc::Min => "Min",
PivotFunc::Product => "Product",
PivotFunc::StdDev => "StdDev",
PivotFunc::StdDevP => "StdDevp",
PivotFunc::Var => "Var",
PivotFunc::VarP => "Varp",
}
}

/// The name commands take and report (`countNumbers`, `stdDevP`).
pub fn name(self) -> &'static str {
match self {
PivotFunc::Sum => "sum",
PivotFunc::Count => "count",
PivotFunc::Average => "average",
PivotFunc::Max => "max",
PivotFunc::Min => "min",
PivotFunc::Product => "product",
PivotFunc::CountNumbers => "countNumbers",
PivotFunc::StdDev => "stdDev",
PivotFunc::StdDevP => "stdDevP",
PivotFunc::Var => "var",
PivotFunc::VarP => "varP",
}
}

/// The name in an XLSX file (`dataField@subtotal`: `countNums`, `stdDevp`, `varp`).
pub fn file_name(self) -> &'static str {
match self {
PivotFunc::CountNumbers => "countNums",
PivotFunc::StdDevP => "stdDevp",
PivotFunc::VarP => "varp",
f => f.name(),
}
}

/// A function from its name, case-insensitively: the command name, the file name or a
/// common alias (`avg`, `counta`, `count numbers`).
pub fn parse(s: &str) -> Option<PivotFunc> {
let s = s.trim().to_ascii_lowercase();
let alias = match s.as_str() {
"counta" => Some(PivotFunc::Count),
"avg" | "mean" => Some(PivotFunc::Average),
"count numbers" => Some(PivotFunc::CountNumbers),
_ => None,
};
alias.or_else(|| PivotFunc::ALL.into_iter().find(|f| f.name().eq_ignore_ascii_case(&s) || f.file_name().eq_ignore_ascii_case(&s)))
}
}

/// Show-values-as transform.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum PivotShowAs {
Expand Down Expand Up @@ -1046,3 +1120,24 @@ impl Default for PivotTable {
}
}
}

#[cfg(test)]
mod pivot_func_tests {
use super::PivotFunc;

#[test]
fn captions_and_names_round_trip() {
// Excel 365's captions; Count Numbers is captioned like Count ("Count of Units").
let captions: Vec<&str> = PivotFunc::ALL.iter().map(|f| f.caption()).collect();
assert_eq!(captions, ["Sum", "Count", "Average", "Max", "Min", "Product", "Count", "StdDev", "StdDevp", "Var", "Varp"]);
for f in PivotFunc::ALL {
assert_eq!(PivotFunc::parse(f.name()), Some(f));
assert_eq!(PivotFunc::parse(f.file_name()), Some(f));
assert_eq!(PivotFunc::parse(&f.name().to_uppercase()), Some(f));
}
assert_eq!(PivotFunc::CountNumbers.file_name(), "countNums");
assert_eq!(PivotFunc::parse("avg"), Some(PivotFunc::Average));
assert_eq!(PivotFunc::parse("Count Numbers"), Some(PivotFunc::CountNumbers));
assert_eq!(PivotFunc::parse("median"), None);
}
}
29 changes: 24 additions & 5 deletions crates/xlsx/src/chart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,8 @@ pub fn read_chart(root: &El) -> Option<Chart> {
y_title: y_ax.and_then(|a| a.child("title")).and_then(rich_title),
source: None,
by_rows: false,
pivot: root.path(&["pivotSource", "name"]).map(|n| n.text.trim().to_string()).filter(|n| !n.is_empty()),
// The link without its workbook, which only names the file the chart was saved in.
pivot: root.path(&["pivotSource", "name"]).map(|n| without_book(n.text.trim()).trim().to_string()).filter(|n| !n.is_empty()),
})
}

Expand Down Expand Up @@ -610,17 +611,35 @@ fn axis_xml(a: &Ax<'_>) -> String {
s
}

/// Chart part XML for a model chart on sheet `si`.
pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart) -> String {
/// A PivotChart link without its workbook: `[Book.xlsx]Sheet2!PivotTable1` → `Sheet2!PivotTable1`.
fn without_book(link: &str) -> &str {
match link.strip_prefix('[') {
Some(rest) => rest.split_once(']').map_or(rest, |(_, r)| r),
None => link,
}
}

/// A PivotChart's `c:pivotSource` name: its link (`Sheet2!PivotTable1`) with the workbook in
/// brackets in front, replacing any there. Excel 365 binds the chart to its PivotTable only with a
/// bracketed workbook name; any name will do, so without the file's name a placeholder is used.
fn pivot_source_name(link: &str, book: Option<&str>) -> String {
let bare = without_book(link);
let book = book.map(str::trim).filter(|b| !b.is_empty() && !b.contains(['[', ']'])).unwrap_or("Workbook.xlsx");
format!("[{book}]{bare}")
}

/// Chart part XML for a model chart on sheet `si`. `book`: the file name of the workbook being
/// written, used in a PivotChart's link.
pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book: Option<&str>) -> String {
let mut s = String::from(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<c:chartSpace xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"><c:roundedCorners val=\"0\"/>",
);
if (1..=48).contains(&ch.style) {
let _ = write!(s, "<c:style val=\"{}\"/>", ch.style);
}
// A PivotChart names its PivotTable (`Sheet2!PivotTable1`).
// A PivotChart names its PivotTable with the workbook (`[Book.xlsx]Sheet2!PivotTable1`).
if let Some(link) = ch.pivot.as_deref().map(str::trim).filter(|l| !l.is_empty()) {
let _ = write!(s, "<c:pivotSource><c:name>{}</c:name><c:fmtId val=\"0\"/></c:pivotSource>", esc(link));
let _ = write!(s, "<c:pivotSource><c:name>{}</c:name><c:fmtId val=\"0\"/></c:pivotSource>", esc(&pivot_source_name(link, book)));
}
s.push_str("<c:chart>");
match &ch.title {
Expand Down
10 changes: 8 additions & 2 deletions crates/xlsx/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,18 @@ impl XlsxKind {

/// Writes a workbook as an `.xlsx` package, or as an `.xlsm` one when it holds a VBA project.
pub fn write_xlsx(wb: &Workbook) -> Result<Vec<u8>, IoError> {
write::write_xlsx(wb, if wb.vba_project.is_some() { XlsxKind::MacroWorkbook } else { XlsxKind::Workbook })
write::write_xlsx(wb, if wb.vba_project.is_some() { XlsxKind::MacroWorkbook } else { XlsxKind::Workbook }, None)
}

/// Writes a workbook as the given member of the `.xlsx` family.
pub fn write_xlsx_as(wb: &Workbook, kind: XlsxKind) -> Result<Vec<u8>, IoError> {
write::write_xlsx(wb, kind)
write::write_xlsx(wb, kind, None)
}

/// [`write_xlsx_as`] for a file named `file_name` (`Book.xlsx`): links that name the workbook
/// itself, such as a PivotChart's link to its PivotTable, use that name.
pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, file_name: &str) -> Result<Vec<u8>, IoError> {
write::write_xlsx(wb, kind, Some(file_name))
}

/// CSV import options.
Expand Down
Loading