mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-02 02:33:55 -06:00
XLSX: PivotCharts plot their cached points; deleted automatic titles stay off
Excel often saves a PivotChart series with formulas that only approximate
its PivotTable: every formula pointing at the table corner cell, or a block
that takes in the grand total row. Excel draws the chart from the
PivotTable, so the cached points are what it shows; GridCraft evaluated the
formulas and drew empty charts or a stray grand total bar. When a PivotChart
series references don't cover their cached points (numCache, strCache or the
innermost multiLvlStrCache level), the series now plots the cached points
and cached name as array constants. Refreshing the PivotTable rebinds the
chart to live cells as before.
A chart with <c:autoTitleDeleted val="1"/> and no title now opens with its
automatic title off, instead of showing the lone series name ("Series1").
Array-constant series also survive a save: literals are read by index and
ptCount (gaps stay #N/A instead of shifting later points), and written by
parsing the array constant, so text with quotes, commas or semicolons is
kept.
Literal values keep their number format: Series gains number_format, read
from the numLit or numCache formatCode and written as the numLit
formatCode (it was always General). The renderer uses it only for array
constants; references keep using their cells' format. Cached PivotChart
points now label as "$185" or "5.36%", as in Excel.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
84acf6293b
commit
374ab0f127
@@ -236,7 +236,10 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
|
||||
secondary: s.secondary,
|
||||
smooth: s.smooth,
|
||||
trendlines,
|
||||
number_format: ref_format(wb, sheet, &s.values),
|
||||
number_format: match &s.number_format {
|
||||
Some(code) if s.values.trim_start().starts_with('{') => code.clone(),
|
||||
_ => ref_format(wb, sheet, &s.values),
|
||||
},
|
||||
});
|
||||
}
|
||||
let n = series.iter().map(|s| s.values.len()).max().unwrap_or(0);
|
||||
|
||||
@@ -229,6 +229,8 @@ fn resolve_from_workbook() {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
// References use their cells' format, whatever the series says.
|
||||
number_format: Some("0%".into()),
|
||||
},
|
||||
Series {
|
||||
name: None,
|
||||
@@ -240,6 +242,7 @@ fn resolve_from_workbook() {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
},
|
||||
Series {
|
||||
name: Some("Literal".into()),
|
||||
@@ -251,6 +254,7 @@ fn resolve_from_workbook() {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: Some("0.0%".into()),
|
||||
},
|
||||
];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
@@ -270,6 +274,7 @@ fn resolve_from_workbook() {
|
||||
assert!(s1.secondary);
|
||||
assert_eq!(d.series[2].name, "Literal");
|
||||
assert_eq!(d.series[2].values.len(), 4);
|
||||
assert_eq!(d.series[2].number_format, "0.0%");
|
||||
|
||||
// Default categories.
|
||||
c.series.remove(0);
|
||||
@@ -289,6 +294,7 @@ fn resolve_from_workbook() {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
},
|
||||
Series {
|
||||
name: None,
|
||||
@@ -300,6 +306,7 @@ fn resolve_from_workbook() {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
},
|
||||
];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
@@ -316,6 +323,7 @@ fn resolve_from_workbook() {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
}];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
assert_eq!(d.series[0].x.as_ref().map(|x| x.len()), Some(3));
|
||||
@@ -333,6 +341,7 @@ fn resolve_from_workbook() {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
}];
|
||||
let d = resolve(&wb, 7, &c);
|
||||
assert_eq!(d.series.len(), 1);
|
||||
@@ -1003,6 +1012,7 @@ fn pie_points_follow_workbook_theme() {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
}];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
let expected = vec![series_color(&wb.theme, 0), series_color(&wb.theme, 1)];
|
||||
|
||||
@@ -413,6 +413,7 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
kind: (opts.column_chart && c >= 3).then_some(ChartKind::Line),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
})
|
||||
.collect();
|
||||
sheet.charts.push(Chart {
|
||||
|
||||
@@ -605,6 +605,7 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
@@ -620,6 +621,7 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1569,6 +1569,7 @@ pub fn chart_series(sheet: &str, origin: CellRef, out: &Output) -> Vec<Series> {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -110,6 +110,7 @@ fn sales(s: &mut Session) -> bool {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -424,6 +424,10 @@ pub struct Series {
|
||||
/// Trendlines fitted to this series (Excel allows several per series).
|
||||
#[serde(default)]
|
||||
pub trendlines: Vec<Trendline>,
|
||||
/// Number format of literal values (an array constant, such as a PivotChart's cached
|
||||
/// points). Values that reference cells use the cells' format instead.
|
||||
#[serde(default)]
|
||||
pub number_format: Option<String>,
|
||||
}
|
||||
|
||||
/// Regression a trendline fits (`c:trendlineType`).
|
||||
|
||||
+156
-21
@@ -72,18 +72,111 @@ fn data_ref(e: Option<&El>) -> Option<String> {
|
||||
// Literal values become an array constant.
|
||||
for k in ["numLit", "strLit"] {
|
||||
if let Some(l) = e.child(k) {
|
||||
let pts: Vec<String> = l
|
||||
.kids("pt")
|
||||
.filter_map(|p| p.child("v"))
|
||||
.map(|v| if k == "numLit" { v.text.trim().to_string() } else { format!("\"{}\"", v.text.replace('"', "\"\"")) })
|
||||
.collect();
|
||||
return Some(format!("{{{}}}", pts.join(",")));
|
||||
return points_literal(l, l, k == "numLit").map(|(_, lit)| lit);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn read_series(s: &El) -> Series {
|
||||
/// 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<u64> {
|
||||
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;
|
||||
|
||||
/// The points of a cache or literal (`c` holds `ptCount`, `pts` the `<c:pt>`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::<usize>().ok());
|
||||
let count = match c.child_val("ptCount") {
|
||||
Some(v) => v.trim().parse::<u64>().ok()?,
|
||||
None => pts.kids("pt").filter_map(idx).max().map_or(0, |m| m as u64 + 1),
|
||||
};
|
||||
if !(1..=MAX_CACHED_POINTS).contains(&count) {
|
||||
return None;
|
||||
}
|
||||
let mut vals: Vec<Option<&str>> = 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")) {
|
||||
*slot = Some(v.text.as_str());
|
||||
}
|
||||
}
|
||||
let items: Vec<String> = vals
|
||||
.iter()
|
||||
.map(|v| match (v, numeric) {
|
||||
(Some(t), true) => t.trim().parse::<f64>().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(","))))
|
||||
}
|
||||
|
||||
/// 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)
|
||||
} else {
|
||||
let c = r.child("multiLvlStrCache")?;
|
||||
points_literal(c, c.child("lvl")?, false)
|
||||
}
|
||||
}
|
||||
|
||||
/// A PivotChart's `<c:f>` 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<String> {
|
||||
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('"', "\"\"")));
|
||||
}
|
||||
}
|
||||
|
||||
fn read_series(s: &El, pivot: bool) -> Series {
|
||||
let name = s.child("tx").and_then(|tx| {
|
||||
if let Some(f) = tx.path(&["strRef", "f"]) {
|
||||
let t = f.text.trim();
|
||||
@@ -98,7 +191,7 @@ fn read_series(s: &El) -> 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));
|
||||
Series {
|
||||
let mut ser = 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(),
|
||||
@@ -108,7 +201,22 @@ fn read_series(s: &El) -> 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"))
|
||||
.map(|c| c.text.trim())
|
||||
.filter(|c| !c.is_empty() && !c.eq_ignore_ascii_case("General"))
|
||||
.map(str::to_string);
|
||||
}
|
||||
ser
|
||||
}
|
||||
|
||||
const DASHES: [(LineDash, &str); 11] = [
|
||||
@@ -189,10 +297,11 @@ pub fn read_chart(root: &El) -> Option<Chart> {
|
||||
let groups: Vec<(&El, ChartKind)> = plot.children.iter().filter_map(|g| group_kind(g).map(|k| (g, k))).collect();
|
||||
let (first, first_kind) = *groups.first()?;
|
||||
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![];
|
||||
for (gi, (g, k)) in groups.iter().enumerate() {
|
||||
for s in g.kids("ser") {
|
||||
let mut ser = read_series(s);
|
||||
let mut ser = read_series(s, pivot.is_some());
|
||||
if gi > 0 {
|
||||
ser.kind = Some(*k);
|
||||
ser.secondary = axis_ids(g) != first_axes;
|
||||
@@ -226,7 +335,12 @@ pub fn read_chart(root: &El) -> Option<Chart> {
|
||||
id: 0,
|
||||
kind,
|
||||
anchor: Default::default(),
|
||||
title: chart.child("title").and_then(rich_title),
|
||||
// No `<c:title>`: an automatic title (a lone series' name), unless the file deleted it.
|
||||
title: match chart.child("title") {
|
||||
Some(t) => rich_title(t),
|
||||
None if bool_val(chart, "autoTitleDeleted") => Some(String::new()),
|
||||
None => None,
|
||||
},
|
||||
series,
|
||||
legend,
|
||||
data_labels,
|
||||
@@ -236,7 +350,7 @@ 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()),
|
||||
pivot,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -306,16 +420,35 @@ fn is_ref(f: &str) -> bool {
|
||||
matches!(gridcraft_formula::parse(f), Ok(Expr::Ref(_)))
|
||||
}
|
||||
|
||||
fn num_data(tag: &str, f: Option<&str>, wb: &Workbook, si: usize) -> String {
|
||||
/// The items of an array constant (`{1,"a";#N/A,2}`), row-major; nothing for anything else.
|
||||
fn array_items(f: &str) -> Vec<Expr> {
|
||||
match gridcraft_formula::parse(f) {
|
||||
Ok(Expr::Array(rows)) => rows.into_iter().flatten().collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `fmt` is the format code saved with literal values (`numLit`); references save their cells'.
|
||||
fn num_data(tag: &str, f: Option<&str>, fmt: Option<&str>, wb: &Workbook, si: usize) -> String {
|
||||
let f = f.unwrap_or("").trim();
|
||||
if f.is_empty() {
|
||||
return format!("<c:{tag}><c:numLit><c:ptCount val=\"0\"/></c:numLit></c:{tag}>");
|
||||
}
|
||||
if f.starts_with('{') {
|
||||
let vals: Vec<&str> = f.trim_matches(|c| c == '{' || c == '}').split([',', ';']).collect();
|
||||
let mut s = format!("<c:{tag}><c:numLit><c:formatCode>General</c:formatCode><c:ptCount val=\"{}\"/>", vals.len());
|
||||
for (i, v) in vals.iter().enumerate() {
|
||||
if let Ok(n) = v.trim().parse::<f64>() {
|
||||
let items = array_items(f);
|
||||
let fmt = esc(fmt.unwrap_or("General"));
|
||||
let mut s = format!("<c:{tag}><c:numLit><c:formatCode>{fmt}</c:formatCode><c:ptCount val=\"{}\"/>", items.len());
|
||||
for (i, e) in items.iter().enumerate() {
|
||||
let n = match e {
|
||||
Expr::Number(n) => Some(*n),
|
||||
Expr::Unary(gridcraft_formula::UnOp::Neg, x) => match **x {
|
||||
Expr::Number(n) => Some(-n),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
// Anything else (`#N/A`, text) is a gap: its index is left out.
|
||||
if let Some(n) = n {
|
||||
let _ = write!(s, "<c:pt idx=\"{i}\"><c:v>{}</c:v></c:pt>", num(n));
|
||||
}
|
||||
}
|
||||
@@ -441,11 +574,11 @@ fn series_xml(s: &Series, idx: usize, g: G, wb: &Workbook, si: usize) -> String
|
||||
match g {
|
||||
G::Scatter { .. } | G::Bubble => {
|
||||
if let Some(c) = &s.categories {
|
||||
x.push_str(&num_data("xVal", Some(c), wb, si));
|
||||
x.push_str(&num_data("xVal", Some(c), None, wb, si));
|
||||
}
|
||||
x.push_str(&num_data("yVal", Some(&s.values), wb, si));
|
||||
x.push_str(&num_data("yVal", Some(&s.values), s.number_format.as_deref(), wb, si));
|
||||
if g == G::Bubble {
|
||||
x.push_str(&num_data("bubbleSize", s.bubble_sizes.as_deref().or(Some(&s.values)), wb, si));
|
||||
x.push_str(&num_data("bubbleSize", s.bubble_sizes.as_deref().or(Some(&s.values)), None, wb, si));
|
||||
x.push_str("<c:bubble3D val=\"0\"/>");
|
||||
} else {
|
||||
let _ = write!(x, "<c:smooth val=\"{}\"/>", s.smooth as u8);
|
||||
@@ -455,7 +588,7 @@ fn series_xml(s: &Series, idx: usize, g: G, wb: &Workbook, si: usize) -> String
|
||||
if let Some(c) = &s.categories {
|
||||
x.push_str(&str_data("cat", c, wb, si));
|
||||
}
|
||||
x.push_str(&num_data("val", Some(&s.values), wb, si));
|
||||
x.push_str(&num_data("val", Some(&s.values), s.number_format.as_deref(), wb, si));
|
||||
if matches!(g, G::Line { .. }) {
|
||||
let _ = write!(x, "<c:smooth val=\"{}\"/>", s.smooth as u8);
|
||||
}
|
||||
@@ -623,12 +756,14 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart) -> String {
|
||||
let _ = write!(s, "<c:pivotSource><c:name>{}</c:name><c:fmtId val=\"0\"/></c:pivotSource>", esc(link));
|
||||
}
|
||||
s.push_str("<c:chart>");
|
||||
// `None` is the automatic title; an empty title is one that was turned off.
|
||||
match &ch.title {
|
||||
Some(t) if !t.is_empty() => {
|
||||
s.push_str(&title_xml(t));
|
||||
s.push_str("<c:autoTitleDeleted val=\"0\"/>");
|
||||
}
|
||||
_ => s.push_str("<c:autoTitleDeleted val=\"1\"/>"),
|
||||
Some(_) => s.push_str("<c:autoTitleDeleted val=\"1\"/>"),
|
||||
None => s.push_str("<c:autoTitleDeleted val=\"0\"/>"),
|
||||
}
|
||||
s.push_str("<c:plotArea><c:layout/>");
|
||||
let all: Vec<(usize, &Series)> = ch.series.iter().enumerate().collect();
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! Reading charts as Excel saved them: PivotChart series and deleted automatic titles.
|
||||
|
||||
use gridcraft_model::{Chart, ChartKind, Workbook};
|
||||
|
||||
const NS: &str =
|
||||
r#"xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#;
|
||||
|
||||
fn read(xml: &str) -> Chart {
|
||||
crate::chart::read_chart(&crate::xml::parse(xml.as_bytes()).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn str_cache(f: &str, pts: &[&str]) -> String {
|
||||
let p: String = pts.iter().enumerate().map(|(i, v)| format!(r#"<c:pt idx="{i}"><c:v>{v}</c:v></c:pt>"#)).collect();
|
||||
format!(r#"<c:strRef><c:f>{f}</c:f><c:strCache><c:ptCount val="{}"/>{p}</c:strCache></c:strRef>"#, pts.len())
|
||||
}
|
||||
|
||||
/// A numeric cache of `count` points; `pts` are (idx, value), so gaps can be left out.
|
||||
fn num_cache(f: &str, count: usize, pts: &[(usize, &str)]) -> String {
|
||||
let p: String = pts.iter().map(|(i, v)| format!(r#"<c:pt idx="{i}"><c:v>{v}</c:v></c:pt>"#)).collect();
|
||||
format!(r#"<c:numRef><c:f>{f}</c:f><c:numCache><c:formatCode>General</c:formatCode><c:ptCount val="{count}"/>{p}</c:numCache></c:numRef>"#)
|
||||
}
|
||||
|
||||
fn ser(tx: &str, cat: &str, val: &str) -> String {
|
||||
format!("<c:ser><c:idx val=\"0\"/><c:order val=\"0\"/><c:tx>{tx}</c:tx><c:cat>{cat}</c:cat><c:val>{val}</c:val></c:ser>")
|
||||
}
|
||||
|
||||
fn chart_xml(pivot: bool, plot: &str, title: &str) -> String {
|
||||
let src = if pivot { "<c:pivotSource><c:name>[Book.xlsx]Graph!PivotTable1</c:name><c:fmtId val=\"0\"/></c:pivotSource>" } else { "" };
|
||||
format!(
|
||||
r#"<c:chartSpace {NS}>{src}<c:chart>{title}<c:plotArea>{plot}<c:catAx><c:axId val="1"/></c:catAx><c:valAx><c:axId val="2"/></c:valAx></c:plotArea></c:chart></c:chartSpace>"#
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pivot_charts_plot_their_cached_points_when_the_references_do_not_cover_them() {
|
||||
// Excel points every formula of this combo PivotChart at the PivotTable's corner cell and
|
||||
// draws it from the PivotTable; the cached points are what it shows.
|
||||
let cats = ["Truck 1", "Van \"B\"", "Car"];
|
||||
let bar =
|
||||
ser(&str_cache("Graph!$J$2", &["Events"]), &str_cache("Graph!$J$2", &cats), &num_cache("Graph!$J$2", 3, &[(0, "18"), (1, "12"), (2, "5")]));
|
||||
// A point the cache leaves out stays a gap, so later points keep their positions.
|
||||
let line = ser(&str_cache("Graph!$J$2", &["Share"]), &str_cache("Graph!$J$2", &cats), &num_cache("Graph!$J$2", 3, &[(0, "5.3E-2"), (2, "0.5")]));
|
||||
let plot = format!(
|
||||
r#"<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/>{bar}<c:axId val="1"/><c:axId val="2"/></c:barChart><c:lineChart><c:grouping val="standard"/>{line}<c:axId val="1"/><c:axId val="2"/></c:lineChart>"#
|
||||
);
|
||||
let c = read(&chart_xml(true, &plot, ""));
|
||||
assert_eq!(c.pivot.as_deref(), Some("[Book.xlsx]Graph!PivotTable1"));
|
||||
assert_eq!(c.kind, ChartKind::Combo);
|
||||
let s = &c.series;
|
||||
assert_eq!(s[0].name.as_deref(), Some("\"Events\""));
|
||||
assert_eq!(s[0].categories.as_deref(), Some(r#"{"Truck 1","Van ""B""","Car"}"#));
|
||||
assert_eq!(s[0].values, "{18,12,5}");
|
||||
assert_eq!(s[1].name.as_deref(), Some("\"Share\""));
|
||||
assert_eq!(s[1].values, "{0.053,#N/A,0.5}");
|
||||
|
||||
// The block Excel writes takes in the grand total row (4 cells for 3 points): the total is
|
||||
// not plotted.
|
||||
let totals = ser(
|
||||
&str_cache("Summary!$B$4", &["Total"]),
|
||||
&str_cache("Summary!$A$5:$A$8", &cats),
|
||||
&num_cache("Summary!$B$5:$B$8", 3, &[(0, "1010"), (1, "185.14"), (2, "120")]).replace("General", "\"$\"#,##0"),
|
||||
);
|
||||
let c = read(&chart_xml(true, &format!(r#"<c:pieChart>{totals}</c:pieChart>"#), ""));
|
||||
assert_eq!(c.series[0].values, "{1010,185.14,120}");
|
||||
assert_eq!(c.series[0].categories.as_deref(), Some(r#"{"Truck 1","Van ""B""","Car"}"#));
|
||||
// The cached points keep the cache's number format (data labels show "$185"), and so does
|
||||
// a save.
|
||||
assert_eq!(c.series[0].number_format.as_deref(), Some("\"$\"#,##0"));
|
||||
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.
|
||||
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#"<c:pieChart>{live}</c:pieChart>"#), ""));
|
||||
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")]));
|
||||
let c = read(&chart_xml(false, &format!(r#"<c:pieChart>{plain}</c:pieChart>"#), ""));
|
||||
assert_eq!(c.series[0].values, "Graph!$J$2");
|
||||
|
||||
// Saved again, the cached points come back as they were: quotes, gaps and all. (A literal
|
||||
// name is saved as plain text, which names the series the same way.)
|
||||
let c = read(&chart_xml(true, &plot, ""));
|
||||
let back = read(&crate::chart::write_chart(&Workbook::new(), 0, &c));
|
||||
assert_eq!(back.pivot, c.pivot);
|
||||
let parts = |c: &Chart| {
|
||||
c.series
|
||||
.iter()
|
||||
.map(|s| (s.name.as_deref().map(|n| n.trim_matches('"').to_string()), s.categories.clone(), s.values.clone()))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(parts(&back), parts(&c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deleted_automatic_title_stays_deleted() {
|
||||
let one = ser("<c:v>Vehicles</c:v>", &str_cache("S!$A$1:$A$2", &["a", "b"]), &num_cache("S!$B$1:$B$2", 2, &[]));
|
||||
let pie = format!("<c:pieChart>{one}</c:pieChart>");
|
||||
// A lone series names an automatic title unless the file turned it off.
|
||||
assert_eq!(read(&chart_xml(false, &pie, "")).title, None);
|
||||
assert_eq!(read(&chart_xml(false, &pie, r#"<c:autoTitleDeleted val="0"/>"#)).title, None);
|
||||
let deleted = read(&chart_xml(false, &pie, r#"<c:autoTitleDeleted val="1"/>"#));
|
||||
assert_eq!(deleted.title.as_deref(), Some(""));
|
||||
// An explicit title wins over the flag.
|
||||
let t = r#"<c:title><c:tx><c:rich><a:p><a:r><a:t>Risk</a:t></a:r></a:p></c:rich></c:tx></c:title><c:autoTitleDeleted val="1"/>"#;
|
||||
assert_eq!(read(&chart_xml(false, &pie, t)).title.as_deref(), Some("Risk"));
|
||||
|
||||
// Both states survive a save.
|
||||
let wb = Workbook::new();
|
||||
assert_eq!(read(&crate::chart::write_chart(&wb, 0, &deleted)).title.as_deref(), Some(""));
|
||||
let auto = read(&chart_xml(false, &pie, ""));
|
||||
assert_eq!(read(&crate::chart::write_chart(&wb, 0, &auto)).title, None);
|
||||
}
|
||||
@@ -30,6 +30,7 @@ fn literal_category_with_separators_survives_save() {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
})
|
||||
.collect();
|
||||
s.charts.push(Chart {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod array_export;
|
||||
mod chart_bool_default;
|
||||
mod chart_read_tests;
|
||||
mod csv_tests;
|
||||
mod encrypted_tests;
|
||||
mod fixtures;
|
||||
|
||||
@@ -382,6 +382,7 @@ fn sample() -> Workbook {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
}],
|
||||
legend: LegendPos::Bottom,
|
||||
data_labels: true,
|
||||
|
||||
@@ -19,6 +19,7 @@ fn smooth_line_setting_round_trips() {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
};
|
||||
s.charts.push(Chart {
|
||||
id: 1,
|
||||
|
||||
@@ -49,6 +49,7 @@ fn chart(id: u32, kind: ChartKind, trendlines: Vec<Trendline>) -> Chart {
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines,
|
||||
number_format: None,
|
||||
}],
|
||||
legend: LegendPos::Bottom,
|
||||
data_labels: false,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Chart parity
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** trivial (chart sheets are kept on save, still not editable (#727); previously minor: trendlines: model, XLSX round-trip, drawing, Add Chart Element) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (PivotCharts from files plot their cached points; deleted automatic titles stay off) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
|
||||
Excel's chart types and chart elements against GridCraft. Part of
|
||||
[target-app-parity.md](target-app-parity.md). **Breadth ~50%, ready ~30%, 40–60 h** (estimated).
|
||||
@@ -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 |
|
||||
| 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 |
|
||||
| Animation on data change | yes (Windows) | no |
|
||||
|
||||
## XLSX round-trip
|
||||
@@ -80,6 +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-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`) |
|
||||
|
||||
Reference in New Issue
Block a user