diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index 363c83793c..198487c96b 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -3,8 +3,8 @@ use std::fmt::Write as _; -use gridcraft_core::Value; -use gridcraft_formula::{Expr, SheetSel}; +use gridcraft_core::{CellRef, RangeRef, Value}; +use gridcraft_formula::{BinOp, Expr, Reference, SheetSel}; use gridcraft_model::{Chart, ChartKind, Color, LegendPos, LineDash, Series, Trendline, TrendlineKind, Workbook}; use crate::drawing::{dml_color, srgb}; @@ -72,111 +72,207 @@ fn data_ref(e: Option<&El>) -> Option { // Literal values become an array constant. for k in ["numLit", "strLit"] { if let Some(l) = e.child(k) { - return points_literal(l, l, k == "numLit").map(|(_, lit)| lit); + return read_points(l, l).map(|p| literal(&p, k == "numLit")); } } None } -/// Cells a series reference covers: `Sheet!$A$1:$A$9`, or a union `(Sheet!$A$1:$A$3,Sheet!$A$5)`. -fn ref_cells(f: &str) -> Option { - let f = f.trim(); - let inner = f.strip_prefix('(').and_then(|x| x.strip_suffix(')')).unwrap_or(f); - let mut parts = Vec::new(); - let (mut quoted, mut start) = (false, 0); - for (i, c) in inner.char_indices() { - match c { - '\'' => quoted = !quoted, - ',' if !quoted => { - parts.push(inner.get(start..i)?); - start = i + 1; - } - _ => {} - } - } - parts.push(inner.get(start..)?); - let mut total = 0u64; - for p in parts { - let addr = p.rsplit_once('!').map_or(p, |(_, a)| a).trim(); - let r = gridcraft_core::RangeRef::parse(addr)?; - total = total.checked_add(u64::from(r.width()) * u64::from(r.height()))?; - } - Some(total) -} - /// Most cached points a PivotChart series keeps (the chart renderer's own cap). -const MAX_CACHED_POINTS: u64 = 100_000; +const MAX_CACHED_POINTS: usize = 100_000; -/// The points of a cache or literal (`c` holds `ptCount`, `pts` the ``s) as an array -/// constant, with the point count. Missing points become `#N/A` (numbers) or `""` (text) so -/// positions line up. Without a `ptCount`, the highest index sets the count. -fn points_literal(c: &El, pts: &El, numeric: bool) -> Option<(u64, String)> { - let idx = |p: &El| p.attr("idx").and_then(|v| v.trim().parse::().ok()); - let count = match c.child_val("ptCount") { - Some(v) => v.trim().parse::().ok()?, - None => pts.kids("pt").filter_map(idx).max().map_or(0, |m| m as u64 + 1), - }; - if !(1..=MAX_CACHED_POINTS).contains(&count) { +/// The points of a cache or literal (`c` holds `ptCount`, `pts` the ``s), by index; missing +/// points are `None`. Points without a valid `idx` (schema-invalid, but some writers omit it) go +/// in document order. A missing, unreadable or too small `ptCount` gives way to the points present. +fn read_points<'a>(c: &El, pts: &'a El) -> Option>> { + let at = |i: usize, p: &El| p.attr("idx").and_then(|v| v.trim().parse::().ok()).unwrap_or(i); + let placed = || pts.kids("pt").enumerate().map(|(i, p)| (at(i, p), p)).filter(|(i, _)| *i < MAX_CACHED_POINTS); + let highest = placed().map(|(i, _)| i + 1).max().unwrap_or(0); + let count = + c.child_val("ptCount").and_then(|v| v.trim().parse::().ok()).filter(|n| (highest..=MAX_CACHED_POINTS).contains(n)).unwrap_or(highest); + if count == 0 { return None; } - let mut vals: Vec> = vec![None; usize::try_from(count).ok()?]; - for p in pts.kids("pt") { - if let (Some(slot), Some(v)) = (idx(p).and_then(|i| vals.get_mut(i)), p.child("v")) { + let mut vals = vec![None; count]; + for (i, p) in placed() { + if let (Some(slot), Some(v)) = (vals.get_mut(i), p.child("v")) { *slot = Some(v.text.as_str()); } } - let items: Vec = vals + Some(vals) +} + +/// Points as an array constant. Missing points become `#N/A` (numbers) or `""` (text) so +/// positions line up. +fn literal>(points: &[Option], numeric: bool) -> String { + let items: Vec = points .iter() - .map(|v| match (v, numeric) { + .map(|v| match (v.as_ref().map(AsRef::as_ref), numeric) { (Some(t), true) => t.trim().parse::().ok().filter(|n| n.is_finite()).map_or_else(|| "#N/A".to_string(), num), (None, true) => "#N/A".to_string(), (Some(t), false) => format!("\"{}\"", t.replace('"', "\"\"")), (None, false) => "\"\"".to_string(), }) .collect(); - Some((count, format!("{{{}}}", items.join(",")))) + format!("{{{}}}", items.join(",")) } -/// The points cached under a series reference: `numCache`, `strCache`, or the innermost level -/// of a `multiLvlStrCache`. -fn cache_literal(r: &El) -> Option<(u64, String)> { - if let Some(c) = r.child("numCache") { - points_literal(c, c, true) - } else if let Some(c) = r.child("strCache") { - points_literal(c, c, false) +/// The points cached under a PivotChart series reference. +#[derive(Clone, Debug)] +struct CachedPoints { + points: Vec>, + numeric: bool, + /// A `multiLvlStrRef`: one column (or row) of cells per level, the innermost last. The + /// cache holds the innermost level. + multi_level: bool, +} + +/// What a PivotChart series saved with its references, plotted when the referenced cells don't +/// hold it (see [`plot_cached`]). +#[derive(Clone, Debug, Default)] +pub(crate) struct PivotSeriesCache { + name: Option, + categories: Option, + values: Option, + /// The values' `numCache` format code. + number_format: Option, +} + +/// `numCache`, `strCache`, or the innermost level of a `multiLvlStrCache`, under `cat` or `val`. +fn cached_points(e: Option<&El>) -> Option { + let e = e?; + let owned = |p: Vec>| p.into_iter().map(|v| v.map(str::to_string)).collect(); + if let Some(c) = e.path(&["numRef", "numCache"]) { + Some(CachedPoints { points: owned(read_points(c, c)?), numeric: true, multi_level: false }) + } else if let Some(c) = e.path(&["strRef", "strCache"]) { + Some(CachedPoints { points: owned(read_points(c, c)?), numeric: false, multi_level: false }) } else { - let c = r.child("multiLvlStrCache")?; - points_literal(c, c.child("lvl")?, false) + let c = e.path(&["multiLvlStrRef", "multiLvlStrCache"])?; + Some(CachedPoints { points: owned(read_points(c, c.child("lvl")?)?), numeric: false, multi_level: true }) } } +fn pivot_series_cache(s: &El) -> PivotSeriesCache { + PivotSeriesCache { + name: s.path(&["tx", "strRef", "strCache", "pt", "v"]).map(|v| v.text.clone()), + categories: cached_points(s.child("cat")), + values: cached_points(s.child("val")), + number_format: s + .path(&["val", "numRef", "numCache", "formatCode"]) + .map(|c| c.text.trim()) + .filter(|c| !c.is_empty() && !c.eq_ignore_ascii_case("General")) + .map(str::to_string), + } +} + +/// The references of a series formula: one area, or a union `(Sheet!$A$1:$A$3,Sheet!$A$5)`. +fn ref_areas<'e>(e: &'e Expr, out: &mut Vec<&'e Reference>) -> bool { + match e { + Expr::Ref(r) => { + out.push(r); + true + } + Expr::Paren(x) => ref_areas(x, out), + Expr::Binary(BinOp::Union, a, b) => ref_areas(a, out) && ref_areas(b, out), + _ => false, + } +} + +/// Whether a cell shows the cached point: numbers within rounding, text as is. A number cache +/// leaves out cells that hold no number. +fn point_matches(v: &Value, p: Option<&str>, numeric: bool) -> bool { + match (v, p) { + (Value::Number(n), Some(t)) => t.trim().parse::().is_ok_and(|c| c == *n || (c - n).abs() <= 1e-9 * c.abs().max(n.abs())), + (Value::Number(_), None) => false, + (_, None) => numeric || v.is_empty(), + (_, Some(_)) if numeric => false, + (Value::Text(s), Some(t)) => **s == *t, + (Value::Bool(b), Some(t)) => t.eq_ignore_ascii_case(if *b { "TRUE" } else { "FALSE" }), + (Value::Error(e), Some(t)) => e.as_str() == t, + (Value::Empty, Some(t)) => t.is_empty(), + (Value::Array(_), Some(_)) => false, + } +} + +/// Whether the cells a series formula refers to (on sheet `home` when unqualified) hold the +/// cached points, one cell per point. +fn live_matches(wb: &Workbook, home: usize, f: &str, p: &CachedPoints) -> bool { + let Ok(e) = gridcraft_formula::parse(f) else { return false }; + let mut refs = Vec::new(); + if !ref_areas(&e, &mut refs) { + return false; + } + let mut areas = Vec::with_capacity(refs.len()); + for r in refs { + let si = match &r.sheet { + SheetSel::Current => Some(home), + SheetSel::Named(n) => wb.sheet_index(n), + SheetSel::Span(..) => None, + }; + let Some(sheet) = si.and_then(|i| wb.sheet(i)) else { return false }; + areas.push((sheet, r.range())); + } + let n = p.points.len(); + if p.multi_level { + // Only the innermost level is cached: the last column of a block with a row per point, + // or the last row of one with a column per point. + let [(sheet, r)] = areas[..] else { return false }; + let leaf = if r.height() as usize == n { + RangeRef::new(CellRef::new(r.start.row, r.end.col), r.end) + } else if r.width() as usize == n { + RangeRef::new(CellRef::new(r.end.row, r.start.col), r.end) + } else { + return false; + }; + areas = vec![(sheet, leaf)]; + } + if areas.iter().try_fold(0u64, |t, (_, r)| t.checked_add(r.count())) != Some(n as u64) { + return false; + } + areas.iter().flat_map(|(sheet, r)| r.iter().map(|c| sheet.value(c))).zip(&p.points).all(|(v, pt)| point_matches(&v, pt.as_deref(), p.numeric)) +} + /// A PivotChart's `` formulas only approximate its PivotTable: often just the table's corner /// cell, or a block that takes in the grand total row. Excel draws the chart from the PivotTable, -/// and the cached points are what it shows. When a series' categories or values don't cover their -/// cached points, the series plots the cached points (and its cached name) instead; refreshing -/// the PivotTable rebinds the chart to live cells. -fn use_pivot_cache(s: &El, ser: &mut Series) { - let cached = |tag: &str, f: Option<&str>| -> Option { - let e = s.child(tag)?; - let r = ["numRef", "strRef", "multiLvlStrRef"].iter().find_map(|k| e.child(k))?; - let (count, lit) = cache_literal(r)?; - (f.and_then(ref_cells) != Some(count)).then_some(lit) - }; - let categories = cached("cat", ser.categories.as_deref()); - let values = cached("val", Some(ser.values.as_str())); - if categories.is_none() && values.is_none() { - return; - } - ser.categories = categories.or(ser.categories.take()); - if let Some(v) = values { - ser.values = v; - } - if let Some(name) = s.path(&["tx", "strRef", "strCache", "pt", "v"]) { - ser.name = Some(format!("\"{}\"", name.text.replace('"', "\"\""))); +/// and the cached points are what it shows. When the cells a series' categories or values refer +/// to (on sheet `si`) don't hold their cached points, the series plots the cached points (and its +/// cached name) instead; refreshing the PivotTable rebinds the chart to live cells. +pub(crate) fn plot_cached(wb: &Workbook, si: usize, ch: &mut Chart, caches: &[PivotSeriesCache]) { + for (ser, c) in ch.series.iter_mut().zip(caches) { + let stale = |f: Option<&str>, p: &&CachedPoints| !f.is_some_and(|f| live_matches(wb, si, f, p)); + let categories = c.categories.as_ref().filter(|p| stale(ser.categories.as_deref(), p)).map(|p| literal(&p.points, p.numeric)); + let values = c.values.as_ref().filter(|p| stale(Some(&ser.values), p)).map(|p| literal(&p.points, p.numeric)); + if categories.is_none() && values.is_none() { + continue; + } + if categories.is_some() { + ser.categories = categories; + } + if let Some(v) = values { + ser.values = v; + ser.number_format.clone_from(&c.number_format); + } + if let Some(name) = &c.name { + ser.name = Some(format!("\"{}\"", name.replace('"', "\"\""))); + } } } -fn read_series(s: &El, pivot: bool) -> Series { +/// [`plot_cached`] for the PivotCharts read from a workbook (by chart id), once every sheet's +/// cells are in. +pub(crate) fn plot_pivot_caches(wb: &mut Workbook, pending: &[(u32, Vec)]) { + for (id, caches) in pending { + let at = wb.sheets.iter().enumerate().find_map(|(si, sh)| sh.charts.iter().position(|c| c.id == *id).map(|ci| (si, ci))); + let Some((si, ci)) = at else { continue }; + let Some(mut ch) = wb.sheet(si).and_then(|sh| sh.charts.get(ci)).cloned() else { continue }; + plot_cached(wb, si, &mut ch, caches); + if let Some(slot) = wb.sheet_mut(si).and_then(|sh| sh.charts.get_mut(ci)) { + *slot = ch; + } + } +} + +fn read_series(s: &El) -> Series { let name = s.child("tx").and_then(|tx| { if let Some(f) = tx.path(&["strRef", "f"]) { let t = f.text.trim(); @@ -191,7 +287,8 @@ fn read_series(s: &El, pivot: bool) -> Series { .and_then(dml_color) .or_else(|| sp.and_then(|p| p.path(&["ln", "solidFill"])).and_then(dml_color)) .or_else(|| s.path(&["marker", "spPr", "solidFill"]).and_then(dml_color)); - let mut ser = Series { + let values = s.child("val").or_else(|| s.child("yVal")); + Series { name, categories: data_ref(s.child("cat")).or_else(|| data_ref(s.child("xVal"))), values: data_ref(s.child("val")).or_else(|| data_ref(s.child("yVal"))).unwrap_or_default(), @@ -201,22 +298,14 @@ fn read_series(s: &El, pivot: bool) -> Series { kind: None, smooth: bool_val(s, "smooth"), trendlines: s.kids("trendline").filter_map(read_trendline).collect(), - number_format: None, - }; - if pivot { - use_pivot_cache(s, &mut ser); - } - // Literal values (a `numLit`, or the cached points above) keep the format code saved with them. - if ser.values.starts_with('{') { - let v = s.child("val").or_else(|| s.child("yVal")); - ser.number_format = v - .and_then(|v| v.child("numLit").or_else(|| v.path(&["numRef", "numCache"]))) - .and_then(|c| c.child("formatCode")) + // Literal values keep the format code saved with them. + number_format: values + .filter(|v| v.child("numRef").is_none()) + .and_then(|v| v.path(&["numLit", "formatCode"])) .map(|c| c.text.trim()) .filter(|c| !c.is_empty() && !c.eq_ignore_ascii_case("General")) - .map(str::to_string); + .map(str::to_string), } - ser } const DASHES: [(LineDash, &str); 11] = [ @@ -291,7 +380,9 @@ fn axis_ids(g: &El) -> Vec { g.kids("axId").filter_map(|a| a.attr("val")).map(str::to_string).collect() } -pub fn read_chart(root: &El) -> Option { +/// A chart part, with the cached points of each series when it is a PivotChart (empty otherwise), +/// for [`plot_cached`] once the workbook's cells are read. +pub(crate) fn read_chart(root: &El) -> Option<(Chart, Vec)> { let chart = root.child("chart")?; let plot = chart.child("plotArea")?; let groups: Vec<(&El, ChartKind)> = plot.children.iter().filter_map(|g| group_kind(g).map(|k| (g, k))).collect(); @@ -299,14 +390,18 @@ pub fn read_chart(root: &El) -> Option { let first_axes = axis_ids(first); let pivot = root.path(&["pivotSource", "name"]).map(|n| n.text.trim().to_string()).filter(|n| !n.is_empty()); let mut series = vec![]; + let mut caches = vec![]; for (gi, (g, k)) in groups.iter().enumerate() { for s in g.kids("ser") { - let mut ser = read_series(s, pivot.is_some()); + let mut ser = read_series(s); if gi > 0 { ser.kind = Some(*k); ser.secondary = axis_ids(g) != first_axes; } series.push(ser); + if pivot.is_some() { + caches.push(pivot_series_cache(s)); + } } } let kind = if groups.len() > 1 { ChartKind::Combo } else { first_kind }; @@ -331,7 +426,7 @@ pub fn read_chart(root: &El) -> Option { _ => LegendPos::Right, }, }; - Some(Chart { + let ch = Chart { id: 0, kind, anchor: Default::default(), @@ -351,7 +446,8 @@ pub fn read_chart(root: &El) -> Option { source: None, by_rows: false, pivot, - }) + }; + Some((ch, caches)) } // ---------------------------------------------------------------- writing diff --git a/crates/xlsx/src/drawing.rs b/crates/xlsx/src/drawing.rs index 6dbd17e7e2..9460fe1be3 100644 --- a/crates/xlsx/src/drawing.rs +++ b/crates/xlsx/src/drawing.rs @@ -166,10 +166,18 @@ pub fn read_drawing(cx: &mut Ctx<'_>, part: &str, sheet: &mut Sheet) -> Result<( let target = rel.target.clone(); if let Some(cx_xml) = cx.optional_xml(&target)? { let chartex = uri.contains("chartex"); - match if chartex { crate::chartex::read_chartex(&cx_xml) } else { crate::chart::read_chart(&cx_xml) } { - Some(mut ch) => { + let read = if chartex { + crate::chartex::read_chartex(&cx_xml).map(|c| (c, Vec::new())) + } else { + crate::chart::read_chart(&cx_xml) + }; + match read { + Some((mut ch, caches)) => { ch.id = cx.next_object_id(); ch.anchor = anchor; + if !caches.is_empty() { + cx.pivot_charts.push((ch.id, caches)); + } sheet.charts.push(ch); } None => cx.warn(format!("chart {target} has no supported plot and was skipped")), diff --git a/crates/xlsx/src/read.rs b/crates/xlsx/src/read.rs index 1a479081c2..7b991d8b06 100644 --- a/crates/xlsx/src/read.rs +++ b/crates/xlsx/src/read.rs @@ -30,6 +30,9 @@ pub struct Ctx<'a> { pub cell_pictures: Vec>>, /// x14 conditional-format ids of the current sheet's data bars, with the index of the rule in `cond_formats`. pub cf_ext_ids: Vec<(String, usize)>, + /// PivotCharts (by chart id) and their series' cached points, checked against the cells once + /// every sheet is read. + pub pivot_charts: Vec<(u32, Vec)>, } impl Ctx<'_> { @@ -82,6 +85,7 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { num_fmts: Default::default(), cell_pictures: vec![], cf_ext_ids: vec![], + pivot_charts: vec![], }; let root_rels = cx.pkg.rels("")?; let wb_part = find_rel(&root_rels, "officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "xl/workbook.xml".into()); @@ -246,6 +250,8 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { wb.sheets.push(Arc::new(Sheet::new("Sheet1"))); } wb.active_sheet = file_to_model.get(active_tab).copied().flatten().unwrap_or(0); + // PivotChart series whose references don't hold their cached points plot the cache. + crate::chart::plot_pivot_caches(&mut wb, &cx.pivot_charts); // Defined names. Chartex parts refer to their data through hidden `_xlchart.*` names. let mut chart_names: Vec<(String, String)> = vec![]; diff --git a/crates/xlsx/src/tests/chart_bool_default.rs b/crates/xlsx/src/tests/chart_bool_default.rs index e9a074cbe9..f484544864 100644 --- a/crates/xlsx/src/tests/chart_bool_default.rs +++ b/crates/xlsx/src/tests/chart_bool_default.rs @@ -13,7 +13,7 @@ fn flags(ser: &str, group: &str) -> (bool, bool) { " ); let root = parse(xml.as_bytes()).unwrap(); - let ch = read_chart(&root).unwrap(); + let (ch, _) = read_chart(&root).unwrap(); (ch.series[0].smooth, ch.data_labels) } diff --git a/crates/xlsx/src/tests/chart_read_tests.rs b/crates/xlsx/src/tests/chart_read_tests.rs index c4c694a160..3a139738a4 100644 --- a/crates/xlsx/src/tests/chart_read_tests.rs +++ b/crates/xlsx/src/tests/chart_read_tests.rs @@ -1,12 +1,34 @@ //! Reading charts as Excel saved them: PivotChart series and deleted automatic titles. -use gridcraft_model::{Chart, ChartKind, Workbook}; +use std::sync::Arc; + +use gridcraft_core::{CellRef, Value}; +use gridcraft_model::{Chart, ChartKind, Sheet, Workbook}; const NS: &str = r#"xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#; +/// Reads a chart part as part of `wb` (sheet 0): PivotChart series whose cells don't hold their +/// cached points plot the cache. +fn read_in(wb: &Workbook, xml: &str) -> Chart { + let (mut c, caches) = crate::chart::read_chart(&crate::xml::parse(xml.as_bytes()).unwrap()).unwrap(); + crate::chart::plot_cached(wb, 0, &mut c, &caches); + c +} + fn read(xml: &str) -> Chart { - crate::chart::read_chart(&crate::xml::parse(xml.as_bytes()).unwrap()).unwrap() + read_in(&Workbook::new(), xml) +} + +/// A workbook with one sheet holding `cells` (A1 address, value). +fn book(name: &str, cells: &[(&str, Value)]) -> Workbook { + let mut sheet = Sheet::new(name); + for (a, v) in cells { + sheet.set_value(CellRef::parse(a).unwrap(), v.clone()); + } + let mut wb = Workbook::new(); + wb.sheets = vec![Arc::new(sheet)]; + wb } fn str_cache(f: &str, pts: &[&str]) -> String { @@ -69,9 +91,11 @@ fn pivot_charts_plot_their_cached_points_when_the_references_do_not_cover_them() let back = read(&crate::chart::write_chart(&Workbook::new(), 0, &c)); assert_eq!(back.series[0].number_format, c.series[0].number_format); - // References that cover the cached points stay live, and so do an ordinary chart's. + // References whose cells hold the cached points stay live, and so do an ordinary chart's. let live = ser(&str_cache("Summary!$B$4", &["Total"]), &str_cache("Summary!$A$5:$A$7", &cats), &num_cache("Summary!$B$5:$B$7", 3, &[(0, "1")])); - let c = read(&chart_xml(true, &format!(r#"{live}"#), "")); + let mut cells = vec![("B4", Value::text("Total")), ("B5", Value::Number(1.0))]; + cells.extend(["A5", "A6", "A7"].into_iter().zip(cats).map(|(a, t)| (a, Value::text(t)))); + let c = read_in(&book("Summary", &cells), &chart_xml(true, &format!(r#"{live}"#), "")); assert_eq!((c.series[0].name.as_deref(), c.series[0].values.as_str()), (Some("Summary!$B$4"), "Summary!$B$5:$B$7")); assert_eq!(c.series[0].number_format, None, "live references use their cells' format"); let plain = ser(&str_cache("Graph!$J$2", &["Events"]), &str_cache("Graph!$J$2", &cats), &num_cache("Graph!$J$2", 3, &[(0, "18")])); @@ -92,6 +116,86 @@ fn pivot_charts_plot_their_cached_points_when_the_references_do_not_cover_them() assert_eq!(parts(&back), parts(&c)); } +#[test] +fn a_one_point_pivot_chart_at_the_corner_cell_plots_its_cache() { + // A PivotTable with one row item: every formula points at the corner cell, which holds the + // table's header, and each cache has one point, like the cell count. Excel plots the cache. + let bar = ser(&str_cache("Data!$J$2", &["Events"]), &str_cache("Data!$J$2", &["Truck 1"]), &num_cache("Data!$J$2", 1, &[(0, "18")])); + let chart = chart_xml(true, &format!(r#"{bar}"#), ""); + let drawing = r#"0040"#; + let rel = |kind: &str, target: &str| { + format!( + r#""# + ) + }; + let (srels, drels) = (rel("drawing", "../drawings/drawing1.xml"), rel("chart", "../charts/chart1.xml")); + let body = r#"Sum of Events"#; + let parts = [ + ("xl/worksheets/_rels/sheet1.xml.rels", srels.as_str()), + ("xl/drawings/drawing1.xml", drawing), + ("xl/drawings/_rels/drawing1.xml.rels", drels.as_str()), + ("xl/charts/chart1.xml", chart.as_str()), + ]; + let (wb, _) = crate::read_xlsx(&super::minimal(body, &parts, "", "")).unwrap(); + let s = &wb.sheets[0].charts[0].series[0]; + assert_eq!((s.name.as_deref(), s.categories.as_deref(), s.values.as_str()), (Some("\"Events\""), Some(r#"{"Truck 1"}"#), "{18}")); +} + +#[test] +fn multi_level_pivot_categories_stay_live_when_their_cells_hold_the_cache() { + // Two levels of row labels in A4:B7, the outer one (country) on the left; the cache keeps + // the innermost level first. + let cities = ["Ottawa", "Toronto", "Boston", "NYC"]; + let leaf: String = cities.iter().enumerate().map(|(i, v)| format!(r#"{v}"#)).collect(); + let outer = r#"CanadaUSA"#; + let cat = format!( + r#"Graph!$A$4:$B$7{leaf}{outer}"# + ); + let val = num_cache("Graph!$C$4:$C$7", 4, &[(0, "1"), (1, "2"), (2, "3"), (3, "4")]); + let xml = chart_xml( + true, + &format!( + r#"{}"#, + ser(&str_cache("Graph!$C$3", &["Total"]), &cat, &val) + ), + "", + ); + let mut cells = vec![("A4", Value::text("Canada")), ("A6", Value::text("USA")), ("C3", Value::text("Total"))]; + for (i, city) in cities.iter().enumerate() { + cells.push((["B4", "B5", "B6", "B7"][i], Value::text(*city))); + cells.push((["C4", "C5", "C6", "C7"][i], Value::Number(i as f64 + 1.0))); + } + let wb = book("Graph", &cells); + let c = read_in(&wb, &xml); + let s = &c.series[0]; + assert_eq!((s.name.as_deref(), s.categories.as_deref(), s.values.as_str()), (Some("Graph!$C$3"), Some("Graph!$A$4:$B$7"), "Graph!$C$4:$C$7")); + // A save keeps the reference. + let back = read_in(&wb, &crate::chart::write_chart(&wb, 0, &c)); + assert_eq!(back.series[0].categories.as_deref(), Some("Graph!$A$4:$B$7")); + + // When the innermost level's cells show other labels, the cache is plotted. + cells.push(("B5", Value::text("Montreal"))); + let c = read_in(&book("Graph", &cells), &xml); + assert_eq!(c.series[0].categories.as_deref(), Some(r#"{"Ottawa","Toronto","Boston","NYC"}"#)); +} + +#[test] +fn literal_series_keep_their_points_without_a_valid_pt_count() { + // Not valid by the schema, but readable: the points present set the count, and points + // without an index go in document order. + let values = |lit: &str| { + let s = format!("{lit}"); + read(&chart_xml(false, &format!("{s}"), "")).series[0].values.clone() + }; + let pts = r#"12"#; + assert_eq!(values(&format!(r#"{pts}"#)), "{1,2}"); + assert_eq!(values(&format!(r#"{pts}"#)), "{1,2}"); + assert_eq!(values(&format!(r#"{pts}"#)), "{1,2}"); + assert_eq!(values("12"), "{1,2}"); + // A valid count still keeps trailing gaps. + assert_eq!(values(&format!(r#"{pts}"#)), "{1,2,#N/A}"); +} + #[test] fn a_deleted_automatic_title_stays_deleted() { let one = ser("Vehicles", &str_cache("S!$A$1:$A$2", &["a", "b"]), &num_cache("S!$B$1:$B$2", 2, &[])); diff --git a/crates/xlsx/src/tests/trendline_roundtrip.rs b/crates/xlsx/src/tests/trendline_roundtrip.rs index 49a6b07b77..8354db5862 100644 --- a/crates/xlsx/src/tests/trendline_roundtrip.rs +++ b/crates/xlsx/src/tests/trendline_roundtrip.rs @@ -161,7 +161,7 @@ fn excel_style_trendlines_are_read() { // type that is skipped rather than failing the chart. let xml = r#"Data!$B$2:$B$6"#; let root = crate::xml::parse(xml.as_bytes()).unwrap(); - let c = crate::chart::read_chart(&root).unwrap(); + let (c, _) = crate::chart::read_chart(&root).unwrap(); let t = &c.series[0].trendlines; assert_eq!(t.len(), 2); assert_eq!(t[0].kind, TrendlineKind::Polynomial(3)); diff --git a/docs/chart-parity.md b/docs/chart-parity.md index a3340584c7..6c9743800a 100644 --- a/docs/chart-parity.md +++ b/docs/chart-parity.md @@ -55,7 +55,7 @@ open PRs #158, #161, and issue #190. | Recommended Charts | yes | partial (Insert ▸ Recommended) | | Switch Row/Column, Select Data | yes | yes (Switch on charts read from files landed in #116); Select Data dialog: data range, remove series, Horizontal (Category) Axis Labels (#287). No series add/edit or hidden/empty cell options | | Sparklines (line, column, win/loss, markers, axis) | yes | line, column, win/loss | -| PivotCharts | yes | Insert ▸ PivotChart (`insert.pivotChart`): bound to a PivotTable's report, rebuilt on refresh and layout changes, `c:pivotSource` round trip; no field buttons, innermost category level only. Opened from a file, a series whose references don't cover its cached points (Excel often points them at the PivotTable's corner cell, or takes in the grand total row) plots the cached points until the PivotTable is refreshed; data labels and the value axis use the cache's number format, which is kept through a save | +| PivotCharts | yes | Insert ▸ PivotChart (`insert.pivotChart`): bound to a PivotTable's report, rebuilt on refresh and layout changes, `c:pivotSource` round trip; no field buttons, innermost category level only. Opened from a file, a series whose referenced cells don't hold its cached points (Excel often points them at the PivotTable's corner cell, or takes in the grand total row) plots the cached points until the PivotTable is refreshed; data labels and the value axis use the cache's number format, which is kept through a save | | Animation on data change | yes (Windows) | no | ## XLSX round-trip @@ -80,7 +80,7 @@ back. | Date | Change | Summary | |---|---|---| -| 2026-10-13 | minor | XLSX: PivotChart series whose references don't cover their cached points plot the cached points (they drew empty or with the grand total), in the cache's number format; `autoTitleDeleted` keeps a deleted automatic title off; array-constant series keep quoted text, gaps and their number format through a save | +| 2026-10-13 | minor | XLSX: PivotChart series whose referenced cells don't hold their cached points plot the cached points (they drew empty or with the grand total), in the cache's number format; `autoTitleDeleted` keeps a deleted automatic title off; array-constant series keep quoted text, gaps and their number format through a save | | 2026-10-12 | trivial | chart sheets are kept on save, still not editable (#727) | | 2026-10-11 | minor | Trendlines: all six types modelled, round-tripped through `c:trendline`, drawn with forecast and equation/R² labels; `chart.addElement` `trendline` | | 2026-10-11 | minor | PivotCharts (`insert.pivotChart`) |