mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-02 10:37:05 -06:00
PivotTables: Distinct Count as a value summary (#3385)
* PivotTables: Distinct Count as a value summary (#3336) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Pivot: refuse Distinct Count for calculated fields A calculated field is evaluated on the report totals, so there are no per-record values to count. pivot.addField and pivot.valueSettings now reject the combination. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * PivotTables: do not offer Distinct Count for a calculated field in the field menu Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * fix(xlsx): keep pivot Distinct Count through a save (#3336) SpreadsheetML has no distinct-count subtotal, so a Distinct Count value field is still written as subtotal="count", now with a GridCraft dataField extension that reads back as Distinct Count. A field with Rank as well gets both extensions. The cache of such a PivotTable is written without refreshOnLoad, so Excel opens it showing the computed distinct counts on the sheet; a manual Refresh in Excel recomputes the field as Count. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * PivotTables: tell the user on .xlsx export that Distinct Count is read only by GridCraft (#3336) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * PivotTables: disclose a new Distinct Count field on an ordinary Save too (#3336) The notice no longer depends on the save path being new: the document remembers which Distinct Count value fields an .xlsx save already reported. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * i18n: translate the Distinct Count strings in every catalog (#3336) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> Co-authored-by: skylartaylor <skylartaylor@users.noreply.github.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
skylartaylor
parent
f9af787c7b
commit
1b92ec071e
@@ -130,6 +130,13 @@ fn save(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
None => crate::io::save_bytes(wb, &path)?,
|
||||
};
|
||||
crate::io::write_file(&path, &bytes)?;
|
||||
// Only a field the user was not told about yet raises the notice: a known path is no proof,
|
||||
// since a Distinct Count added after an earlier save is still unreported.
|
||||
let distinct = distinct_count_fields(wb);
|
||||
let distinct_notice = kind == Some(crate::io::FileKind::Xlsx) && distinct.iter().any(|f| !d.distinct_disclosed.contains(f));
|
||||
if kind == Some(crate::io::FileKind::Xlsx) {
|
||||
d.distinct_disclosed = distinct;
|
||||
}
|
||||
// Only a full-fidelity format clears the dirty flag and becomes the document's file.
|
||||
if matches!(kind, Some(crate::io::FileKind::Xlsx | crate::io::FileKind::Json)) {
|
||||
// The new file is the workbook's own now, so `CELL("filename")` reports it (#1489). Set
|
||||
@@ -142,9 +149,31 @@ fn save(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
d.saved = d.wb.clone();
|
||||
d.path = Some(path.clone());
|
||||
}
|
||||
if distinct_notice {
|
||||
s.ui_requests.push(crate::UiRequest::Message(DISTINCT_COUNT_NOTICE.into()));
|
||||
}
|
||||
Ok(json!({"path": path, "bytes": bytes.len()}))
|
||||
}
|
||||
|
||||
/// Shown when a workbook with a Distinct Count PivotTable value field is saved as .xlsx for the first time (#3336): the
|
||||
/// file stores a plain Count that only GridCraft's private marker turns back into Distinct Count.
|
||||
const DISTINCT_COUNT_NOTICE: &str = "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count.";
|
||||
|
||||
/// Every Distinct Count value field of the workbook, as (sheet, pivot, value) positions.
|
||||
fn distinct_count_fields(wb: &gridcraft_model::Workbook) -> Vec<(usize, usize, usize)> {
|
||||
let mut fields = Vec::new();
|
||||
for (si, sheet) in wb.sheets.iter().enumerate() {
|
||||
for (pi, pt) in sheet.pivots.iter().enumerate() {
|
||||
for (vi, v) in pt.values.iter().enumerate() {
|
||||
if v.func == gridcraft_model::PivotFunc::DistinctCount {
|
||||
fields.push((si, pi, vi));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fields
|
||||
}
|
||||
|
||||
fn save_as(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if str_param(p, "path").is_none() {
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("saveAs".into(), json!({})));
|
||||
@@ -159,6 +188,9 @@ fn save_bytes(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let name = format!("{}.{fmt}", std::path::Path::new(&d.display_title()).file_stem().and_then(|x| x.to_str()).unwrap_or("Book"));
|
||||
// The file name goes into a PivotChart's link to its PivotTable.
|
||||
let bytes = crate::io::save_bytes(&d.wb, &name)?;
|
||||
if fmt == "xlsx" && !distinct_count_fields(&d.wb).is_empty() {
|
||||
s.ui_requests.push(crate::UiRequest::Message(DISTINCT_COUNT_NOTICE.into()));
|
||||
}
|
||||
Ok(json!({"name": name, "base64": crate::io::base64_encode(&bytes), "bytes": bytes.len()}))
|
||||
}
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Field",
|
||||
[],
|
||||
None,
|
||||
"{pivot?, field, area: rows|columns|values|filters, func?: sum|count|average|max|min|product|countNumbers|stdDev|stdDevP|var|varP, name?, position?: index, replace?}",
|
||||
"{pivot?, field, area: rows|columns|values|filters, func?: sum|count|average|max|min|product|countNumbers|distinctCount|stdDev|stdDevP|var|varP, name?, position?: index, replace?}",
|
||||
has_doc,
|
||||
add_field
|
||||
),
|
||||
|
||||
@@ -106,6 +106,10 @@ fn auto_name(f: PivotFunc, field: &str) -> String {
|
||||
format!("{} of {field}", pv::func_caption(f))
|
||||
}
|
||||
|
||||
/// A calculated field is evaluated on the report's totals, not per source record, so there is
|
||||
/// no set of values to count the distinct members of.
|
||||
const NO_CALC_DISTINCT: &str = "A calculated field can't use Distinct Count.";
|
||||
|
||||
/// Adds `field` to an area (moving it out of the other axis areas).
|
||||
pub(super) struct AreaPlacement<'a> {
|
||||
pub cmd: &'a str,
|
||||
@@ -140,6 +144,9 @@ pub(super) fn add_to_area(pt: &mut PivotTable, src: &pv::Source, placement: Area
|
||||
}
|
||||
let numeric = is_calc || src.col(&field).and_then(|c| src.numeric.get(c).copied()).unwrap_or(false);
|
||||
let f = func.unwrap_or(if numeric { PivotFunc::Sum } else { PivotFunc::Count });
|
||||
if is_calc && f == PivotFunc::DistinctCount {
|
||||
return Err(other(NO_CALC_DISTINCT));
|
||||
}
|
||||
let base = match name {
|
||||
Some(n) if !n.trim().is_empty() => {
|
||||
if src.col(n).is_some() {
|
||||
@@ -506,6 +513,9 @@ pub(super) fn value_settings(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let cur = pt.values.get(i).cloned().ok_or_else(|| bad(C, "no value field at that index"))?;
|
||||
let mut v = cur.clone();
|
||||
if let Some(f) = func {
|
||||
if f == PivotFunc::DistinctCount && src.col(&cur.source_col).is_none() && calc_field(pt, &cur.source_col).is_some() {
|
||||
return Err(other(NO_CALC_DISTINCT));
|
||||
}
|
||||
v.func = f;
|
||||
// An automatic caption follows the function. Count Numbers was captioned "Count
|
||||
// Numbers of …" before it took Excel's "Count of …", and saved workbooks still carry it.
|
||||
|
||||
@@ -20,6 +20,7 @@ pub(super) fn func_param(v: Option<&str>) -> Option<PivotFunc> {
|
||||
"min" => PivotFunc::Min,
|
||||
"product" => PivotFunc::Product,
|
||||
"countnumbers" | "countnums" | "count numbers" => PivotFunc::CountNumbers,
|
||||
"distinctcount" | "distinct count" | "distinct" => PivotFunc::DistinctCount,
|
||||
"stddev" => PivotFunc::StdDev,
|
||||
"stddevp" => PivotFunc::StdDevP,
|
||||
"var" => PivotFunc::Var,
|
||||
@@ -37,6 +38,7 @@ pub(super) fn func_name(f: PivotFunc) -> &'static str {
|
||||
PivotFunc::Min => "min",
|
||||
PivotFunc::Product => "product",
|
||||
PivotFunc::CountNumbers => "countNumbers",
|
||||
PivotFunc::DistinctCount => "distinctCount",
|
||||
PivotFunc::StdDev => "stdDev",
|
||||
PivotFunc::StdDevP => "stdDevP",
|
||||
PivotFunc::Var => "var",
|
||||
|
||||
@@ -571,6 +571,25 @@ fn pivot_chart_errors() {
|
||||
assert!(s.doc().unwrap().wb.active().unwrap().charts.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_calculated_field_cannot_use_distinct_count() {
|
||||
// It is computed from the report's totals, so there are no per-record values to count.
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap();
|
||||
s.execute("pivot.calculatedField", json!({"name": "Price", "formula": "Sales / Units"})).unwrap();
|
||||
assert_eq!(text(&s, "C3"), "Sum of Price");
|
||||
let before = s.doc().unwrap().wb.clone();
|
||||
let set = s.execute("pivot.valueSettings", json!({"field": "Price", "func": "distinctCount"}));
|
||||
assert!(set.unwrap_err().to_string().contains("Distinct Count"));
|
||||
assert_eq!(s.doc().unwrap().wb, before, "a rejected change leaves the workbook as it was");
|
||||
s.execute("pivot.removeField", json!({"field": "Price", "area": "values"})).unwrap();
|
||||
let add = s.execute("pivot.addField", json!({"field": "Price", "area": "values", "func": "distinctCount"}));
|
||||
assert!(add.unwrap_err().to_string().contains("Distinct Count"));
|
||||
// A source field still takes it, and a calculated field keeps its other functions.
|
||||
s.execute("pivot.addField", json!({"field": "Product", "area": "values", "func": "distinctCount"})).unwrap();
|
||||
s.execute("pivot.addField", json!({"field": "Price", "area": "values", "func": "sum"})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculated_field_on_sums() {
|
||||
let mut s = sales();
|
||||
@@ -1429,6 +1448,107 @@ fn legacy_count_numbers_caption_follows_the_function() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_count_counts_each_different_value_once_per_cell_and_in_the_totals() {
|
||||
// #3336: Alice, Bob, Alice, Charlie is 3 distinct customers, where Count says 4. Case does not
|
||||
// make a name different, and an empty cell is not a value.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let rows = json!([
|
||||
["Region", "Customer"],
|
||||
["East", "Alice"],
|
||||
["East", "Bob"],
|
||||
["East", "alice"],
|
||||
["East", null],
|
||||
["West", "Alice"],
|
||||
["West", "Charlie"]
|
||||
]);
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
|
||||
let make = json!({"source": "Sheet1!$A$1:$B$7", "destination": "Sheet1!D3", "rows": ["Region"], "values": ["Customer"]});
|
||||
s.execute("insert.pivotTable", make).unwrap();
|
||||
s.execute("pivot.valueSettings", json!({"index": 0, "func": "count"})).unwrap();
|
||||
let counts: Vec<Value> = ["E4", "E5", "E6"].iter().map(|a| val(&s, a)).collect();
|
||||
assert_eq!(counts, [3.0, 2.0, 5.0].map(Value::Number), "Count counts every non-empty cell");
|
||||
s.execute("pivot.valueSettings", json!({"index": 0, "func": "distinctCount"})).unwrap();
|
||||
assert_eq!(text(&s, "E3"), "Distinct Count of Customer");
|
||||
let distinct: Vec<Value> = ["E4", "E5", "E6"].iter().map(|a| val(&s, a)).collect();
|
||||
assert_eq!(distinct, [2.0, 2.0, 3.0].map(Value::Number), "East has Alice and Bob, West Alice and Charlie, 3 in all");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_count_survives_an_xlsx_round_trip_and_a_refresh() {
|
||||
// #3385: saving wrote Distinct Count as Count, so Alice, Bob, Alice became 3 after reopening
|
||||
// and refreshing. The sheet keeps the computed distinct counts for other readers too.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let rows = json!([["Region", "Customer"], ["East", "Alice"], ["East", "Bob"], ["East", "alice"], ["West", "Alice"], ["West", "Charlie"]]);
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
|
||||
let make = json!({"source": "Sheet1!$A$1:$B$6", "destination": "Sheet1!D3", "rows": ["Region"], "values": ["Customer"]});
|
||||
s.execute("insert.pivotTable", make).unwrap();
|
||||
s.execute("pivot.valueSettings", json!({"index": 0, "func": "distinctCount"})).unwrap();
|
||||
let cells = ["E4", "E5", "E6"];
|
||||
let expected = [2.0, 2.0, 3.0].map(Value::Number);
|
||||
assert_eq!(cells.map(|a| val(&s, a)), expected);
|
||||
let bytes = crate::io::save_bytes(&s.doc().unwrap().wb, "book.xlsx").unwrap();
|
||||
|
||||
// The written sheet holds the distinct counts, and the cache doesn't ask for a refresh on open.
|
||||
let (written, _) = gridcraft_xlsx::read_xlsx(&bytes).unwrap();
|
||||
let sheet = written.sheet(0).unwrap();
|
||||
assert_eq!(cells.map(|a| sheet.value(CellRef::parse(a).unwrap())), expected);
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut cache = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("xl/pivotCache/pivotCacheDefinition1.xml").unwrap(), &mut cache).unwrap();
|
||||
assert!(!cache.contains("refreshOnLoad"), "{cache}");
|
||||
|
||||
let mut back = Session::new();
|
||||
back.execute("file.open", json!({"name": "book.xlsx", "base64": crate::io::base64_encode(&bytes)})).unwrap();
|
||||
assert_eq!(pt(&back).values[0].func, gridcraft_model::PivotFunc::DistinctCount);
|
||||
back.execute("pivot.refresh", json!({"pivot": "PivotTable1"})).unwrap();
|
||||
assert_eq!(text(&back, "E3"), "Distinct Count of Customer");
|
||||
assert_eq!(cells.map(|a| val(&back, a)), expected, "a refresh after reopening still counts distinct customers");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_a_distinct_count_pivot_as_xlsx_says_only_gridcraft_reads_it() {
|
||||
// #3385: the file stores a plain Count; Excel's Refresh turns it into a count, so the user is told.
|
||||
let notices =
|
||||
|s: &mut Session| s.take_ui_requests().iter().filter(|r| matches!(r, crate::UiRequest::Message(m) if m.contains("Distinct Count"))).count();
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-distinct-notice-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let rows = json!([["Region", "Customer"], ["East", "Alice"], ["East", "Bob"], ["West", "Alice"]]);
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
|
||||
let make = json!({"source": "Sheet1!$A$1:$B$4", "destination": "Sheet1!D3", "rows": ["Region"], "values": ["Customer"]});
|
||||
s.execute("insert.pivotTable", make).unwrap();
|
||||
s.take_ui_requests();
|
||||
|
||||
s.execute("file.saveAs", json!({"path": dir.join("plain.xlsx")})).unwrap();
|
||||
assert_eq!(notices(&mut s), 0, "a plain Count is saved as it is");
|
||||
|
||||
s.execute("pivot.valueSettings", json!({"index": 0, "func": "distinctCount"})).unwrap();
|
||||
s.execute("file.saveBytes", json!({"format": "csv"})).unwrap();
|
||||
s.execute("file.saveAs", json!({"path": dir.join("book.csv")})).unwrap();
|
||||
assert_eq!(notices(&mut s), 0, "only an .xlsx file stores the marker");
|
||||
s.execute("file.saveAs", json!({"path": dir.join("book.xlsx")})).unwrap();
|
||||
assert_eq!(notices(&mut s), 1);
|
||||
s.execute("file.save", json!({})).unwrap();
|
||||
assert_eq!(notices(&mut s), 0, "saving the same file again does not repeat it");
|
||||
// The path is known now, but a Distinct Count added later was never disclosed.
|
||||
s.execute("insert.pivotTable", json!({"source": "Sheet1!$A$1:$B$4", "destination": "Sheet1!H3", "rows": ["Region"], "values": ["Customer"]}))
|
||||
.unwrap();
|
||||
s.execute("file.save", json!({})).unwrap();
|
||||
assert_eq!(notices(&mut s), 0, "a plain Count adds nothing to disclose");
|
||||
s.execute("pivot.valueSettings", json!({"index": 0, "func": "distinctCount"})).unwrap();
|
||||
s.execute("file.save", json!({})).unwrap();
|
||||
assert_eq!(notices(&mut s), 1, "a new Distinct Count field is disclosed on an ordinary Save to the same path");
|
||||
s.execute("file.save", json!({})).unwrap();
|
||||
assert_eq!(notices(&mut s), 0, "and only once");
|
||||
s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
|
||||
assert_eq!(notices(&mut s), 1, "a download is an export too");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// A defined name with a table's name doesn't stop a PivotTable's table source following a rename
|
||||
/// of the table: a bare source binds to the table first.
|
||||
#[test]
|
||||
|
||||
@@ -225,6 +225,9 @@ pub struct DocState {
|
||||
/// The references `edit.goTo` with `record: true` went to in this document, newest first,
|
||||
/// without names, each area written with its sheet (`Sheet1!B14:C22,Sheet1!F19:G30`).
|
||||
pub go_to_recent: Vec<String>,
|
||||
/// The Distinct Count PivotTable value fields (sheet, pivot, value) an .xlsx save has already
|
||||
/// told the user about (#3336), so only a field not yet disclosed raises the notice again.
|
||||
pub distinct_disclosed: Vec<(usize, usize, usize)>,
|
||||
}
|
||||
|
||||
static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
@@ -362,6 +365,7 @@ impl DocState {
|
||||
touched: None,
|
||||
edits: None,
|
||||
go_to_recent: vec![],
|
||||
distinct_disclosed: vec![],
|
||||
}
|
||||
}
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
|
||||
@@ -128,10 +128,14 @@ fn aggregate_record(
|
||||
}
|
||||
for row_depth in 0..=row_path.len() {
|
||||
for col_depth in 0..=col_path.len() {
|
||||
let accs = data
|
||||
.aggs
|
||||
.entry((row_path[..row_depth].to_vec(), col_path[..col_depth].to_vec()))
|
||||
.or_insert_with(|| vec![Acc::default(); input.vals.len() + input.extra.len()]);
|
||||
let accs = data.aggs.entry((row_path[..row_depth].to_vec(), col_path[..col_depth].to_vec())).or_insert_with(|| {
|
||||
input
|
||||
.vals
|
||||
.iter()
|
||||
.map(|(_, v)| Acc::for_func(v.func))
|
||||
.chain(std::iter::repeat_n(Acc::default(), input.extra.len()))
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
for (acc, (source, _)) in accs.iter_mut().zip(input.vals) {
|
||||
if let ValSrc::Col(column) = source {
|
||||
acc.add(rec.get(*column).unwrap_or(&Value::Empty));
|
||||
@@ -687,7 +691,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
|
||||
}
|
||||
PivotShowAs::Rank => v.number_format.clone(),
|
||||
_ => v.number_format.clone().or_else(|| match v.func {
|
||||
PivotFunc::Count | PivotFunc::CountNumbers => None,
|
||||
PivotFunc::Count | PivotFunc::CountNumbers | PivotFunc::DistinctCount => None,
|
||||
_ => {
|
||||
let f = match vs {
|
||||
ValSrc::Col(c) => fmt_of(*c),
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::{CellError, HashMap, MONTHS, Ordering, PivotDateGroup, PivotField, PivotFunc, PivotSort, Source, Value, Workbook, datetime_from_serial};
|
||||
|
||||
// ---------------------------------------------------------------- items
|
||||
@@ -120,10 +122,35 @@ pub(super) struct Acc {
|
||||
mean: f64,
|
||||
m2: f64,
|
||||
err: Option<CellError>,
|
||||
/// The values seen so far, kept only for a Distinct Count accumulator.
|
||||
distinct: Option<HashSet<String>>,
|
||||
}
|
||||
|
||||
/// What makes two values the same for a Distinct Count: text ignores case, like item labels do.
|
||||
fn distinct_key(v: &Value) -> Option<String> {
|
||||
Some(match v {
|
||||
Value::Empty => return None,
|
||||
Value::Number(n) => format!("n{}", if *n == 0.0 { 0.0 } else { *n }.to_bits()),
|
||||
Value::Text(t) if t.is_empty() => return None,
|
||||
Value::Text(t) => format!("t{}", t.to_lowercase()),
|
||||
Value::Bool(b) => format!("b{b}"),
|
||||
Value::Error(e) => format!("e{}", e.as_str()),
|
||||
Value::Array(_) => return distinct_key(&v.scalar()),
|
||||
})
|
||||
}
|
||||
|
||||
impl Acc {
|
||||
/// An accumulator for value field function `f`: a Distinct Count also remembers each value it saw.
|
||||
pub(super) fn for_func(f: PivotFunc) -> Self {
|
||||
Self { distinct: (f == PivotFunc::DistinctCount).then(HashSet::new), ..Self::default() }
|
||||
}
|
||||
|
||||
pub(super) fn add(&mut self, v: &Value) {
|
||||
if let Some(seen) = &mut self.distinct
|
||||
&& let Some(key) = distinct_key(v)
|
||||
{
|
||||
seen.insert(key);
|
||||
}
|
||||
match v {
|
||||
Value::Empty => {}
|
||||
Value::Number(n) => {
|
||||
@@ -158,6 +185,7 @@ impl Acc {
|
||||
match f {
|
||||
PivotFunc::Count => return Value::number(self.count as f64),
|
||||
PivotFunc::CountNumbers => return Value::number(n),
|
||||
PivotFunc::DistinctCount => return Value::number(self.distinct.as_ref().map_or(0, HashSet::len) as f64),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(e) = self.err {
|
||||
@@ -192,7 +220,7 @@ impl Acc {
|
||||
Value::number(if f == PivotFunc::VarP { var } else { var.sqrt() })
|
||||
}
|
||||
}
|
||||
PivotFunc::Count | PivotFunc::CountNumbers => Value::Empty,
|
||||
PivotFunc::Count | PivotFunc::CountNumbers | PivotFunc::DistinctCount => Value::Empty,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -208,6 +236,7 @@ pub fn func_caption(f: PivotFunc) -> &'static str {
|
||||
PivotFunc::Min => "Min",
|
||||
PivotFunc::Product => "Product",
|
||||
PivotFunc::CountNumbers => "Count",
|
||||
PivotFunc::DistinctCount => "Distinct Count",
|
||||
PivotFunc::StdDev => "StdDev",
|
||||
PivotFunc::StdDevP => "StdDevp",
|
||||
PivotFunc::Var => "Var",
|
||||
|
||||
@@ -60,6 +60,9 @@ pub enum PivotFunc {
|
||||
Min,
|
||||
Product,
|
||||
CountNumbers,
|
||||
/// Number of different non-empty values (Excel's Distinct Count, a Data Model summary).
|
||||
/// A workbook file has no field for it: it is saved as Count.
|
||||
DistinctCount,
|
||||
StdDev,
|
||||
StdDevP,
|
||||
Var,
|
||||
|
||||
@@ -601,6 +601,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Zobrazit",
|
||||
"Collapse dialog" => "Sbalit dialogové okno",
|
||||
"Expand dialog" => "Rozbalit dialogové okno",
|
||||
"Distinct Count" => "Počet různých",
|
||||
"Summarize by Distinct Count" => "Shrnout podle počtu různých",
|
||||
"A calculated field can't use Distinct Count." => "Počítané pole nemůže používat počet různých.",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Tento sešit obsahuje kontingenční tabulku s hodnotovým polem „Počet různých“. V souboru .xlsx se ukládá jako obyčejný Počet spolu se značkou, kterou čte jen GridCraft, takže Aktualizovat v Excelu z něj udělá obyčejný počet."
|
||||
}
|
||||
"My list has headers" => "Data obsahují záhlaví",
|
||||
"Sort by" => "Seřadit podle",
|
||||
"Then by" => "Potom podle",
|
||||
|
||||
@@ -521,6 +521,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Anzeigen",
|
||||
"Collapse dialog" => "Dialogfeld reduzieren",
|
||||
"Expand dialog" => "Dialogfeld erweitern",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Diese Arbeitsmappe enthält eine PivotTable mit einem Wertfeld „Distinkte Anzahl“. In der .xlsx-Datei wird sie als normale Anzahl mit einer Markierung gespeichert, die nur GridCraft liest; Aktualisieren in Excel macht daraus eine normale Anzahl."
|
||||
}
|
||||
"Distinct Count" => "Distinkte Anzahl",
|
||||
"Summarize by Distinct Count" => "Nach Distinkter Anzahl zusammenfassen",
|
||||
"A calculated field can't use Distinct Count." => "Ein berechnetes Feld kann „Distinkte Anzahl“ nicht verwenden.",
|
||||
"My list has headers" => "Daten haben Überschriften",
|
||||
"Sort by" => "Sortieren nach",
|
||||
"Then by" => "Anschließend nach",
|
||||
|
||||
@@ -435,6 +435,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Move to Values" => "Μετακίνηση στις τιμές",
|
||||
"Summarize by Sum" => "Σύνοψη με άθροισμα",
|
||||
"Summarize by Count" => "Σύνοψη με πλήθος",
|
||||
"Summarize by Distinct Count" => "Σύνοψη με πλήθος διακριτών",
|
||||
"Summarize by Average" => "Σύνοψη με μέσο όρο",
|
||||
"Summarize by Max" => "Σύνοψη με μέγιστο",
|
||||
"Summarize by Min" => "Σύνοψη με ελάχιστο",
|
||||
@@ -1030,6 +1031,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Εμφάνιση",
|
||||
"Collapse dialog" => "Σύμπτυξη παραθύρου διαλόγου",
|
||||
"Expand dialog" => "Ανάπτυξη παραθύρου διαλόγου",
|
||||
"Distinct Count" => "Πλήθος διακριτών",
|
||||
"A calculated field can't use Distinct Count." => "Ένα υπολογιζόμενο πεδίο δεν μπορεί να χρησιμοποιήσει πλήθος διακριτών.",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Αυτό το βιβλίο εργασίας έχει μια συγκεντρωτική λίστα με πεδίο τιμών «Πλήθος διακριτών». Στο αρχείο .xlsx αποθηκεύεται ως απλό Πλήθος μαζί με έναν δείκτη που διαβάζει μόνο το GridCraft, οπότε η Ανανέωση στο Excel το μετατρέπει σε απλό πλήθος."
|
||||
}
|
||||
"Numerical Count" => "Αριθμητικό πλήθος",
|
||||
"Minimum" => "Ελάχιστο",
|
||||
"Maximum" => "Μέγιστο",
|
||||
|
||||
@@ -480,6 +480,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Move to Values" => "Mover a valores",
|
||||
"Summarize by Sum" => "Resumir por suma",
|
||||
"Summarize by Count" => "Resumir por cuenta",
|
||||
"Summarize by Distinct Count" => "Resumir por recuento distinto",
|
||||
"Summarize by Average" => "Resumir por promedio",
|
||||
"Summarize by Max" => "Resumir por máximo",
|
||||
"Summarize by Min" => "Resumir por mínimo",
|
||||
@@ -527,6 +528,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Mostrar",
|
||||
"Collapse dialog" => "Contraer diálogo",
|
||||
"Expand dialog" => "Expandir diálogo",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Este libro tiene una tabla dinámica con un campo de valor «Recuento distinto». En el archivo .xlsx se guarda como un Recuento normal con una marca que solo lee GridCraft; Actualizar en Excel lo convierte en un recuento normal."
|
||||
}
|
||||
"Distinct Count" => "Recuento distinto",
|
||||
"A calculated field can't use Distinct Count." => "Un campo calculado no puede usar «Recuento distinto».",
|
||||
"My list has headers" => "Mis datos tienen encabezados",
|
||||
"Sort by" => "Ordenar por",
|
||||
"Then by" => "Luego por",
|
||||
|
||||
@@ -487,6 +487,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Afficher",
|
||||
"Collapse dialog" => "Réduire la boîte de dialogue",
|
||||
"Expand dialog" => "Développer la boîte de dialogue",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Ce classeur contient un tableau croisé dynamique avec un champ de valeur « Nombre distinct ». Dans le fichier .xlsx, il est enregistré comme un simple Nombre, avec un marqueur que seul GridCraft lit ; Actualiser dans Excel le transforme en simple nombre."
|
||||
}
|
||||
"Distinct Count" => "Nombre distinct",
|
||||
"Summarize by Distinct Count" => "Synthétiser par nombre distinct",
|
||||
"A calculated field can't use Distinct Count." => "Un champ calculé ne peut pas utiliser « Nombre distinct ».",
|
||||
"My list has headers" => "Mes données ont des en-têtes",
|
||||
"Sort by" => "Trier par",
|
||||
"Then by" => "Puis par",
|
||||
|
||||
@@ -687,6 +687,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Description (optional):" => "Descrizione (facoltativa):",
|
||||
"Fits inside the selected cell and moves with its content." => "Si adatta alla cella selezionata e si sposta insieme al suo contenuto.",
|
||||
"Choose a PNG or JPEG no larger than 16 MB." => "Scegli un file PNG o JPEG di dimensioni non superiori a 16 MB.",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Questa cartella di lavoro contiene una tabella pivot con un campo valore «Conteggio distinto». Nel file .xlsx è salvato come Conteggio normale con un indicatore che legge solo GridCraft; Aggiorna in Excel lo trasforma in un conteggio normale."
|
||||
}
|
||||
"About" => "Informazioni",
|
||||
"Contributors" => "Collaboratori",
|
||||
"Models" => "Modelli",
|
||||
@@ -1010,6 +1013,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Move to Values" => "Sposta in Valori",
|
||||
"Summarize by Sum" => "Riepiloga per somma",
|
||||
"Summarize by Count" => "Riepiloga per conteggio",
|
||||
"Summarize by Distinct Count" => "Riepiloga per conteggio distinto",
|
||||
"Summarize by Average" => "Riepiloga per media",
|
||||
"Summarize by Max" => "Riepiloga per massimo",
|
||||
"Summarize by Min" => "Riepiloga per minimo",
|
||||
@@ -1036,6 +1040,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Mostra",
|
||||
"Collapse dialog" => "Comprimi finestra di dialogo",
|
||||
"Expand dialog" => "Espandi finestra di dialogo",
|
||||
"Distinct Count" => "Conteggio distinto",
|
||||
"A calculated field can't use Distinct Count." => "Un campo calcolato non può usare «Conteggio distinto».",
|
||||
"Numerical Count" => "Conteggio numeri",
|
||||
"Minimum" => "Minimo",
|
||||
"Maximum" => "Massimo",
|
||||
|
||||
@@ -703,6 +703,13 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
|
||||
("Description (optional):", "説明 (省略可能):"),
|
||||
("Fits inside the selected cell and moves with its content.", "選択したセル内に収まり、内容と一緒に移動します。"),
|
||||
("Choose a PNG or JPEG no larger than 16 MB.", "16 MB 以下の PNG または JPEG を選択してください。"),
|
||||
(
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count.",
|
||||
"このブックには、値フィールドが「重複を除いた個数」のピボットテーブルがあります。.xlsx ファイルでは通常の個数と GridCraft だけが読み取るマーカーとして保存されるため、Excel で更新すると通常の個数に戻ります。",
|
||||
),
|
||||
("Distinct Count", "重複を除いた個数"),
|
||||
("Summarize by Distinct Count", "重複を除いた個数で集計"),
|
||||
("A calculated field can't use Distinct Count.", "集計フィールドでは「重複を除いた個数」を使用できません。"),
|
||||
("About", "バージョン情報"),
|
||||
("Contributors", "貢献者"),
|
||||
("Models", "モデル"),
|
||||
|
||||
@@ -491,6 +491,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "표시",
|
||||
"Collapse dialog" => "대화 상자 축소",
|
||||
"Expand dialog" => "대화 상자 확장",
|
||||
"Distinct Count" => "고유 개수",
|
||||
"Summarize by Distinct Count" => "고유 개수로 요약",
|
||||
"A calculated field can't use Distinct Count." => "계산 필드에는 고유 개수를 사용할 수 없습니다.",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"이 통합 문서에는 값 필드가 '고유 개수'인 피벗 테이블이 있습니다. .xlsx 파일에는 일반 개수와 GridCraft만 읽는 표식으로 저장되므로, Excel에서 새로 고치면 일반 개수로 바뀝니다."
|
||||
}
|
||||
"My list has headers" => "내 데이터에 머리글 표시",
|
||||
"Sort by" => "정렬 기준",
|
||||
"Then by" => "다음 기준",
|
||||
|
||||
@@ -562,6 +562,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Weergeven",
|
||||
"Collapse dialog" => "Dialoogvenster samenvouwen",
|
||||
"Expand dialog" => "Dialoogvenster uitvouwen",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Deze werkmap bevat een draaitabel met een waardeveld ‘Uniek aantal’. In het .xlsx-bestand wordt het opgeslagen als een gewoon Aantal met een markering die alleen GridCraft leest; Vernieuwen in Excel maakt er een gewoon aantal van."
|
||||
}
|
||||
"Distinct Count" => "Uniek aantal",
|
||||
"Summarize by Distinct Count" => "Samenvatten op Uniek aantal",
|
||||
"A calculated field can't use Distinct Count." => "Een berekend veld kan ‘Uniek aantal’ niet gebruiken.",
|
||||
"My list has headers" => "Mijn gegevens bevatten kopteksten",
|
||||
"Sort by" => "Sorteren op",
|
||||
"Then by" => "Vervolgens op",
|
||||
|
||||
@@ -998,6 +998,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Move to Values" => "Przenieś do wartości",
|
||||
"Summarize by Sum" => "Podsumuj według: Suma",
|
||||
"Summarize by Count" => "Podsumuj według: Licznik",
|
||||
"Summarize by Distinct Count" => "Podsumuj według: Licznik unikatowych",
|
||||
"Summarize by Average" => "Podsumuj według: Średnia",
|
||||
"Summarize by Max" => "Podsumuj według: Maksimum",
|
||||
"Summarize by Min" => "Podsumuj według: Minimum",
|
||||
@@ -1024,6 +1025,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Pokaż",
|
||||
"Collapse dialog" => "Zwiń okno dialogowe",
|
||||
"Expand dialog" => "Rozwiń okno dialogowe",
|
||||
"Distinct Count" => "Licznik unikatowych",
|
||||
"A calculated field can't use Distinct Count." => "Pole obliczeniowe nie może używać licznika unikatowych.",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Ten skoroszyt zawiera tabelę przestawną z polem wartości „Licznik unikatowych”. W pliku .xlsx jest ona zapisana jako zwykły Licznik wraz ze znacznikiem, który odczytuje tylko GridCraft, więc Odśwież w programie Excel zamienia ją w zwykły licznik."
|
||||
}
|
||||
"Numerical Count" => "Liczba wartości liczbowych",
|
||||
"Minimum" => "Minimum",
|
||||
"Maximum" => "Maksimum",
|
||||
|
||||
@@ -712,6 +712,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Description (optional):" => "Descrição (opcional):",
|
||||
"Fits inside the selected cell and moves with its content." => "Ajusta-se dentro da célula selecionada e move-se com o conteúdo dela.",
|
||||
"Choose a PNG or JPEG no larger than 16 MB." => "Escolha um PNG ou JPEG de no máximo 16 MB.",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Esta pasta de trabalho tem uma tabela dinâmica com um campo de valor «Contagem distinta». No arquivo .xlsx ela é salva como uma Contagem comum, com um marcador que só o GridCraft lê; Atualizar no Excel a transforma em contagem comum."
|
||||
}
|
||||
"About" => "Sobre",
|
||||
"Contributors" => "Colaboradores",
|
||||
"Models" => "Modelos",
|
||||
@@ -1042,6 +1045,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Mostrar",
|
||||
"Collapse dialog" => "Recolher caixa de diálogo",
|
||||
"Expand dialog" => "Expandir caixa de diálogo",
|
||||
"Distinct Count" => "Contagem distinta",
|
||||
"Summarize by Distinct Count" => "Resumir por contagem distinta",
|
||||
"A calculated field can't use Distinct Count." => "Um campo calculado não pode usar «Contagem distinta».",
|
||||
"Numerical Count" => "Contagem Numérica",
|
||||
"Minimum" => "Mínimo",
|
||||
"Maximum" => "Máximo",
|
||||
|
||||
@@ -1014,6 +1014,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show as Running Total" => "Afișare ca total cumulat",
|
||||
"Summarize by Average" => "Rezumare după medie",
|
||||
"Summarize by Count" => "Rezumare după numărare",
|
||||
"Summarize by Distinct Count" => "Rezumare după numărare distinctă",
|
||||
"Summarize by Max" => "Rezumare după maxim",
|
||||
"Summarize by Min" => "Rezumare după minim",
|
||||
"Summarize by Sum" => "Rezumare după sumă",
|
||||
@@ -1086,6 +1087,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Afișare",
|
||||
"Collapse dialog" => "Restrângere casetă de dialog",
|
||||
"Expand dialog" => "Extindere casetă de dialog",
|
||||
"Distinct Count" => "Numărare distinctă",
|
||||
"A calculated field can't use Distinct Count." => "Un câmp calculat nu poate folosi numărarea distinctă.",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Acest registru de lucru conține un tabel pivot cu un câmp de valori „Numărare distinctă”. În fișierul .xlsx este salvat ca o Numărare simplă, împreună cu un marcaj pe care îl citește doar GridCraft, așa că Reîmprospătare în Excel îl transformă într-o numărare simplă."
|
||||
}
|
||||
"Numerical Count" => "Numărare numerică",
|
||||
"Minimum" => "Minim",
|
||||
"Maximum" => "Maxim",
|
||||
|
||||
@@ -1062,6 +1062,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Показать",
|
||||
"Collapse dialog" => "Свернуть диалоговое окно",
|
||||
"Expand dialog" => "Развернуть диалоговое окно",
|
||||
"Distinct Count" => "Число уникальных",
|
||||
"Summarize by Distinct Count" => "Итоги по числу уникальных",
|
||||
"A calculated field can't use Distinct Count." => "Вычисляемое поле не может использовать число уникальных.",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"В этой книге есть сводная таблица с полем значений «Число уникальных». В файле .xlsx оно сохраняется как обычное Количество вместе с меткой, которую читает только GridCraft, поэтому команда Обновить в Excel превращает его в обычное количество."
|
||||
}
|
||||
"My list has headers" => "Мои данные содержат заголовки",
|
||||
"Sort by" => "Сортировать по",
|
||||
"Then by" => "Затем по",
|
||||
|
||||
@@ -482,6 +482,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Prikaži",
|
||||
"Collapse dialog" => "Skupi dijalog",
|
||||
"Expand dialog" => "Proširi dijalog",
|
||||
"Distinct Count" => "Broj različitih",
|
||||
"Summarize by Distinct Count" => "Sažmi po broju različitih",
|
||||
"A calculated field can't use Distinct Count." => "Izračunato polje ne može koristiti broj različitih.",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Ova radna sveska ima zaokretnu tabelu sa poljem vrednosti „Broj različitih“. U .xlsx datoteci čuva se kao običan Broj uz oznaku koju čita samo GridCraft, pa ga Osveži u Excelu pretvara u običan broj."
|
||||
}
|
||||
"My list has headers" => "Moji podaci imaju zaglavlja",
|
||||
"Sort by" => "Sortiraj po",
|
||||
"Then by" => "Zatim po",
|
||||
|
||||
@@ -452,6 +452,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Göster",
|
||||
"Collapse dialog" => "İletişim kutusunu daralt",
|
||||
"Expand dialog" => "İletişim kutusunu genişlet",
|
||||
"Distinct Count" => "Benzersiz Sayı",
|
||||
"Summarize by Distinct Count" => "Benzersiz Sayıya göre özetle",
|
||||
"A calculated field can't use Distinct Count." => "Hesaplanmış alan Benzersiz Sayı kullanamaz.",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Bu çalışma kitabında değer alanı “Benzersiz Sayı” olan bir PivotTable var. .xlsx dosyasında düz bir Sayı olarak ve yalnızca GridCraft'in okuduğu bir işaretle saklanır; bu yüzden Excel'de Yenile onu düz bir sayıya dönüştürür."
|
||||
}
|
||||
"My list has headers" => "Verilerimde üst bilgi var",
|
||||
"Sort by" => "Sıralama ölçütü",
|
||||
"Then by" => "Sonra",
|
||||
|
||||
@@ -1002,6 +1002,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Move to Values" => "Move to Values",
|
||||
"Summarize by Sum" => "Summarize by Sum",
|
||||
"Summarize by Count" => "Summarize by Count",
|
||||
"Summarize by Distinct Count" => "Підсумувати за кількістю унікальних",
|
||||
"Summarize by Average" => "Summarize by Average",
|
||||
"Summarize by Max" => "Summarize by Max",
|
||||
"Summarize by Min" => "Summarize by Min",
|
||||
@@ -1028,6 +1029,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Показати",
|
||||
"Collapse dialog" => "Згорнути діалогове вікно",
|
||||
"Expand dialog" => "Розгорнути діалогове вікно",
|
||||
"Distinct Count" => "Кількість унікальних",
|
||||
"A calculated field can't use Distinct Count." => "Обчислюване поле не може використовувати кількість унікальних.",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Ця книга містить зведену таблицю з полем значень «Кількість унікальних». У файлі .xlsx воно зберігається як звичайна Кількість разом із міткою, яку читає лише GridCraft, тому Оновити в Excel перетворює його на звичайну кількість."
|
||||
}
|
||||
"Numerical Count" => "Кількість чисел",
|
||||
"Minimum" => "Мінімум",
|
||||
"Maximum" => "Максимум",
|
||||
|
||||
@@ -452,6 +452,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Hiện",
|
||||
"Collapse dialog" => "Thu gọn hộp thoại",
|
||||
"Expand dialog" => "Mở rộng hộp thoại",
|
||||
"Distinct Count" => "Đếm riêng biệt",
|
||||
"Summarize by Distinct Count" => "Tóm tắt theo Đếm riêng biệt",
|
||||
"A calculated field can't use Distinct Count." => "Trường tính toán không thể dùng Đếm riêng biệt.",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"Sổ làm việc này có PivotTable với trường giá trị “Đếm riêng biệt”. Trong tệp .xlsx, trường này được lưu dưới dạng Đếm thông thường cùng một dấu hiệu mà chỉ GridCraft đọc, nên Làm mới trong Excel sẽ biến nó thành đếm thông thường."
|
||||
}
|
||||
"My list has headers" => "Dữ liệu của tôi có tiêu đề",
|
||||
"Sort by" => "Sắp xếp theo",
|
||||
"Then by" => "Sau đó theo",
|
||||
|
||||
@@ -483,6 +483,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "显示",
|
||||
"Collapse dialog" => "折叠对话框",
|
||||
"Expand dialog" => "展开对话框",
|
||||
"Distinct Count" => "非重复计数",
|
||||
"Summarize by Distinct Count" => "按非重复计数汇总",
|
||||
"A calculated field can't use Distinct Count." => "计算字段不能使用非重复计数。",
|
||||
"This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => {
|
||||
"此工作簿中有一个值字段为“非重复计数”的数据透视表。在 .xlsx 文件中,它被保存为普通计数,并附带只有 GridCraft 能读取的标记,因此在 Excel 中刷新会将其变为普通计数。"
|
||||
}
|
||||
"My list has headers" => "数据包含标题",
|
||||
"Sort by" => "主要关键字",
|
||||
"Then by" => "次要关键字",
|
||||
|
||||
@@ -113,13 +113,25 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
|
||||
}
|
||||
if *key == "values" {
|
||||
ui.separator();
|
||||
// A calculated field is evaluated on the summed fields, so it has no Distinct Count.
|
||||
let calculated = info["values"]
|
||||
.as_array()
|
||||
.and_then(|vs| vs.iter().find(|x| x["name"].as_str() == Some(f.as_str())))
|
||||
.and_then(|x| x["field"].as_str())
|
||||
.is_some_and(|src| {
|
||||
fields.iter().any(|c| c["calculated"].as_bool() == Some(true) && c["name"].as_str() == Some(src))
|
||||
});
|
||||
for (func, l) in [
|
||||
("sum", "Summarize by Sum"),
|
||||
("count", "Summarize by Count"),
|
||||
("distinctCount", "Summarize by Distinct Count"),
|
||||
("average", "Summarize by Average"),
|
||||
("max", "Summarize by Max"),
|
||||
("min", "Summarize by Min"),
|
||||
] {
|
||||
if calculated && func == "distinctCount" {
|
||||
continue;
|
||||
}
|
||||
if ui.button(lang.tr(l)).clicked() {
|
||||
app.run_or_alert("pivot.valueSettings", json!({"pivot": name, "field": f, "func": func}));
|
||||
}
|
||||
|
||||
@@ -7,6 +7,14 @@
|
||||
//! grouping, `fieldGroup` group items) so the table's `<items>` can refer to them. The report
|
||||
//! cells the engine wrote stay on the sheet as plain cells.
|
||||
//!
|
||||
//! Distinct Count: SpreadsheetML's subtotal list has no distinct count (Excel has one only for
|
||||
//! PivotTables on its Data Model, whose binary model part we don't write). Such a value field is
|
||||
//! written as `subtotal="count"` with a GridCraft `extLst` marker ([`EXT_GC_DATA_FIELD`]) that
|
||||
//! GridCraft reads back as Distinct Count; other readers ignore the unknown extension. The cache
|
||||
//! of a PivotTable with a Distinct Count field is written without `refreshOnLoad`, so Excel opens
|
||||
//! it showing the distinct counts already on the sheet. A Refresh in Excel recomputes the field as
|
||||
//! Count.
|
||||
//!
|
||||
//! Reading: the cache's source and field names plus the table's areas, functions, show-values-as,
|
||||
//! layout flags, grand totals and style become a model [`PivotTable`]. Anything we don't model
|
||||
//! (OLAP sources, calculated fields, numeric grouping…) becomes a warning.
|
||||
@@ -48,6 +56,10 @@ const MAX_FIELDS: usize = 16_384;
|
||||
const EXT_X14_DATA_FIELD: &str = "{E15A36E0-9728-4e99-A89B-3F7291B0FE68}";
|
||||
const EXT_X14_PIVOT_TABLE: &str = "{962EF5D1-5CA2-4c93-8EF4-DBF5C05439D2}";
|
||||
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).
|
||||
const EXT_GC_DATA_FIELD: &str = "{80B1AD42-0C9F-45FF-B109-D57FB0F4F0B4}";
|
||||
const NS_GC: &str = "https://github.com/storytold/gridcraft/ns/pivot/2026";
|
||||
|
||||
const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||
|
||||
@@ -78,6 +90,10 @@ fn func_name(f: PivotFunc) -> &'static str {
|
||||
PivotFunc::Min => "min",
|
||||
PivotFunc::Product => "product",
|
||||
PivotFunc::CountNumbers => "countNums",
|
||||
// The file format's subtotal list has no distinct count (Excel keeps it in a Data Model
|
||||
// extension), so the nearest function is written, with a GridCraft extension that marks
|
||||
// the field as Distinct Count (see the module documentation).
|
||||
PivotFunc::DistinctCount => "count",
|
||||
PivotFunc::StdDev => "stdDev",
|
||||
PivotFunc::StdDevP => "stdDevp",
|
||||
PivotFunc::Var => "var",
|
||||
@@ -111,6 +127,7 @@ fn func_caption(f: PivotFunc) -> &'static str {
|
||||
PivotFunc::Min => "Min",
|
||||
PivotFunc::Product => "Product",
|
||||
PivotFunc::CountNumbers => "Count",
|
||||
PivotFunc::DistinctCount => "Distinct Count",
|
||||
PivotFunc::StdDev => "StdDev",
|
||||
PivotFunc::StdDevP => "StdDevp",
|
||||
PivotFunc::Var => "Var",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::{
|
||||
CellRef, Ctx, DateSystem, 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,
|
||||
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,
|
||||
};
|
||||
|
||||
// ================================================================ reading
|
||||
@@ -368,12 +369,15 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
PivotFunc::Sum
|
||||
}),
|
||||
};
|
||||
let ext = d
|
||||
.child("extLst")
|
||||
.into_iter()
|
||||
.flat_map(|l| l.kids("ext"))
|
||||
.filter_map(|e| e.child("dataField"))
|
||||
.find_map(|e| e.attr("pivotShowAs").map(str::to_string));
|
||||
let exts = || d.child("extLst").into_iter().flat_map(|l| l.kids("ext"));
|
||||
// GridCraft's marker for a Distinct Count written as Count; ignored when the subtotal
|
||||
// was changed to something else since.
|
||||
let distinct = exts()
|
||||
.filter(|e| e.attr("uri") == Some(EXT_GC_DATA_FIELD))
|
||||
.filter_map(|e| e.child("summary"))
|
||||
.any(|e| e.attr("func") == Some("distinctCount"));
|
||||
let func = if distinct && func == PivotFunc::Count { PivotFunc::DistinctCount } else { func };
|
||||
let ext = exts().filter_map(|e| e.child("dataField")).find_map(|e| e.attr("pivotShowAs").map(str::to_string));
|
||||
let show_as = match (ext.as_deref(), d.attr("showDataAs")) {
|
||||
(Some("rankDescending"), _) => PivotShowAs::Rank,
|
||||
(Some(other), _) => {
|
||||
|
||||
@@ -133,7 +133,11 @@ impl PivotWriter {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
out.part(&cache_part, Some(CT_PIVOT_CACHE_DEF), cache_xml(&cache, rec_rid.as_deref(), wb.date_system).into_bytes());
|
||||
// A refresh on open would recompute a Distinct Count field as Count (the file format has
|
||||
// no distinct count), so such a PivotTable opens showing the values on the sheet.
|
||||
let refresh_on_load = !pt.values.iter().any(|v| v.func == PivotFunc::DistinctCount);
|
||||
let xml = cache_xml(&cache, rec_rid.as_deref(), wb.date_system, refresh_on_load);
|
||||
out.part(&cache_part, Some(CT_PIVOT_CACHE_DEF), xml.into_bytes());
|
||||
self.caches.push((n, format!("pivotCache/pivotCacheDefinition{n}.xml")));
|
||||
self.tables += 1;
|
||||
let t = self.tables;
|
||||
@@ -519,7 +523,7 @@ fn item_xml(v: &Value, sys: DateSystem, date: bool) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn cache_xml(c: &Cache, records_rid: Option<&str>, sys: DateSystem) -> String {
|
||||
fn cache_xml(c: &Cache, records_rid: Option<&str>, sys: DateSystem, refresh_on_load: bool) -> String {
|
||||
let mut s = format!("{XML_DECL}<pivotCacheDefinition xmlns=\"{NS_MAIN}\" xmlns:r=\"{NS_REL}\"");
|
||||
match (records_rid, &c.records) {
|
||||
(Some(rid), Some((count, _))) => {
|
||||
@@ -527,7 +531,10 @@ fn cache_xml(c: &Cache, records_rid: Option<&str>, sys: DateSystem) -> String {
|
||||
}
|
||||
_ => s.push_str(" saveData=\"0\""),
|
||||
}
|
||||
s.push_str(" refreshOnLoad=\"1\" refreshedBy=\"GridCraft\" createdVersion=\"6\" refreshedVersion=\"6\" minRefreshableVersion=\"3\">");
|
||||
if refresh_on_load {
|
||||
s.push_str(" refreshOnLoad=\"1\"");
|
||||
}
|
||||
s.push_str(" refreshedBy=\"GridCraft\" createdVersion=\"6\" refreshedVersion=\"6\" minRefreshableVersion=\"3\">");
|
||||
let _ = write!(s, "<cacheSource type=\"worksheet\">{}</cacheSource>", c.source_xml);
|
||||
let _ = write!(s, "<cacheFields count=\"{}\">", c.fields.len());
|
||||
for f in &c.fields {
|
||||
@@ -875,13 +882,17 @@ fn write_data_fields(s: &mut String, c: &Cache, layout: &PivotTableLayout<'_>, f
|
||||
if let Some(id) = value.number_format.as_deref().and_then(fmt_id) {
|
||||
let _ = write!(s, " numFmtId=\"{id}\"");
|
||||
}
|
||||
let mut ext = String::new();
|
||||
if value.show_as == PivotShowAs::Rank {
|
||||
let _ = write!(
|
||||
s,
|
||||
"><extLst><ext uri=\"{EXT_X14_DATA_FIELD}\" xmlns:x14=\"{NS_X14}\"><x14:dataField pivotShowAs=\"rankDescending\"/></ext></extLst></dataField>"
|
||||
);
|
||||
} else {
|
||||
let _ = write!(ext, "<ext uri=\"{EXT_X14_DATA_FIELD}\" xmlns:x14=\"{NS_X14}\"><x14:dataField pivotShowAs=\"rankDescending\"/></ext>");
|
||||
}
|
||||
if value.func == PivotFunc::DistinctCount {
|
||||
let _ = write!(ext, "<ext uri=\"{EXT_GC_DATA_FIELD}\" xmlns:gc=\"{NS_GC}\"><gc:summary func=\"distinctCount\"/></ext>");
|
||||
}
|
||||
if ext.is_empty() {
|
||||
s.push_str("/>");
|
||||
} else {
|
||||
let _ = write!(s, "><extLst>{ext}</extLst></dataField>");
|
||||
}
|
||||
}
|
||||
s.push_str("</dataFields>");
|
||||
|
||||
@@ -869,3 +869,77 @@ fn two_value_fields_without_columns_hide_the_values_row() {
|
||||
assert!(t.contains("firstHeaderRow=\"1\""), "{t}");
|
||||
assert!(!t.contains("hideValuesRow"), "{t}");
|
||||
}
|
||||
|
||||
/// The "Trend" pivot of [`workbook`] with `values` as its value fields, written; returns the file
|
||||
/// and its PivotTable and cache parts.
|
||||
fn trend_with(values: impl FnOnce(&PivotValue) -> Vec<PivotValue>) -> (Vec<u8>, String, String) {
|
||||
let mut wb = workbook();
|
||||
let pivot = wb.sheet_mut(1).unwrap().pivots.iter_mut().find(|p| p.name == "Trend").unwrap();
|
||||
pivot.values = values(&pivot.values[0]);
|
||||
let bytes = write_xlsx(&wb).unwrap();
|
||||
let parts = unzip(&bytes);
|
||||
let (path, table) = parts
|
||||
.iter()
|
||||
.filter(|(path, _)| path.starts_with("xl/pivotTables/pivotTable"))
|
||||
.map(|(path, xml)| (path.clone(), String::from_utf8_lossy(xml).into_owned()))
|
||||
.find(|(_, xml)| xml.contains("name=\"Trend\""))
|
||||
.unwrap();
|
||||
let n = path.trim_start_matches("xl/pivotTables/pivotTable").trim_end_matches(".xml");
|
||||
let cache_part = format!("xl/pivotCache/pivotCacheDefinition{n}.xml");
|
||||
let rels = String::from_utf8_lossy(&parts[&format!("xl/pivotTables/_rels/pivotTable{n}.xml.rels")]).into_owned();
|
||||
assert!(rels.contains(&format!("../pivotCache/pivotCacheDefinition{n}.xml")), "{rels}");
|
||||
let cache = String::from_utf8_lossy(&parts[&cache_part]).into_owned();
|
||||
(bytes, table, cache)
|
||||
}
|
||||
|
||||
fn trend_values(bytes: &[u8]) -> Vec<PivotValue> {
|
||||
let (back, report) = read_xlsx(bytes).unwrap();
|
||||
assert!(report.warnings.iter().all(|w| !w.to_lowercase().contains("pivot")), "{:?}", report.warnings);
|
||||
back.sheet(1).unwrap().pivots.iter().find(|p| p.name == "Trend").unwrap().values.clone()
|
||||
}
|
||||
|
||||
const GC_DISTINCT: &str = "<ext uri=\"{80B1AD42-0C9F-45FF-B109-D57FB0F4F0B4}\" xmlns:gc=\"https://github.com/storytold/gridcraft/ns/pivot/2026\"><gc:summary func=\"distinctCount\"/></ext>";
|
||||
|
||||
#[test]
|
||||
fn distinct_count_round_trips_through_a_gridcraft_extension() {
|
||||
// The file format's subtotal list has no distinct count: the field is written as Count, which
|
||||
// other readers use, with a GridCraft marker that brings Distinct Count back on open.
|
||||
let (bytes, table, cache) =
|
||||
trend_with(|v| vec![PivotValue { func: PivotFunc::DistinctCount, name: "Distinct Count of Sales".into(), ..v.clone() }]);
|
||||
assert!(table.contains("<dataField name=\"Distinct Count of Sales\" fld=\"4\" subtotal=\"count\""), "{table}");
|
||||
assert!(table.contains(&format!("<extLst>{GC_DISTINCT}</extLst></dataField>")), "{table}");
|
||||
// A refresh on open would recompute it as Count in Excel, over the values on the sheet.
|
||||
assert!(!cache.contains("refreshOnLoad"), "{cache}");
|
||||
let values = trend_values(&bytes);
|
||||
assert_eq!((values[0].func, values[0].name.as_str()), (PivotFunc::DistinctCount, "Distinct Count of Sales"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rank_and_distinct_count_write_one_extension_each() {
|
||||
let (bytes, table, _) = trend_with(|v| {
|
||||
vec![PivotValue { func: PivotFunc::DistinctCount, show_as: PivotShowAs::Rank, name: "Rank of Distinct Sales".into(), ..v.clone() }]
|
||||
});
|
||||
let rank = "<ext uri=\"{E15A36E0-9728-4e99-A89B-3F7291B0FE68}\" xmlns:x14=\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main\"><x14:dataField pivotShowAs=\"rankDescending\"/></ext>";
|
||||
assert!(table.contains(&format!("<extLst>{rank}{GC_DISTINCT}</extLst></dataField>")), "{table}");
|
||||
let values = trend_values(&bytes);
|
||||
assert_eq!((values[0].func, values[0].show_as), (PivotFunc::DistinctCount, PivotShowAs::Rank));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_without_the_gridcraft_extension_reads_as_count() {
|
||||
// Plain `subtotal="count"`, as Excel writes it, stays Count; so does a stale marker on a field
|
||||
// whose function was changed to something else.
|
||||
let (bytes, table, cache) = trend_with(|v| vec![PivotValue { func: PivotFunc::Count, name: "Count of Sales".into(), ..v.clone() }]);
|
||||
assert!(!table.contains("extLst"), "{table}");
|
||||
assert!(cache.contains("refreshOnLoad=\"1\""), "{cache}");
|
||||
assert_eq!(trend_values(&bytes)[0].func, PivotFunc::Count);
|
||||
let marked = |subtotal: &str| {
|
||||
format!(
|
||||
r#"<pivotTableDefinition name="P" cacheId="1"><location ref="C1:D4"/><pivotFields><pivotField/><pivotField dataField="1"/></pivotFields><dataFields><dataField name="V" fld="1"{subtotal}><extLst>{GC_DISTINCT}</extLst></dataField></dataFields></pivotTableDefinition>"#
|
||||
)
|
||||
};
|
||||
let func = |table: &str| read_xlsx(&with_pivot(table, Some(GOOD_CACHE))).unwrap().0.sheet(0).unwrap().pivots[0].values[0].func;
|
||||
assert_eq!(func(&marked(" subtotal=\"count\"")), PivotFunc::DistinctCount);
|
||||
assert_eq!(func(&marked("")), PivotFunc::Sum);
|
||||
assert_eq!(func(&marked(" subtotal=\"max\"")), PivotFunc::Max);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user