Merge pull request #2404 from helenkwok/charts/keep-unedited-chart-xml

XLSX: keep an unedited embedded chart's XML on save (#1668)
This commit is contained in:
FredApps
2026-11-26 22:32:05 +01:00
committed by GitHub
13 changed files with 394 additions and 23 deletions
+2
View File
@@ -171,6 +171,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-24 | PivotTables: right-clicking a value, subtotal or grand total cell offers Show Details in the cell menu, which lists the cell's source records on a new sheet as double-clicking does |
| 2026-10-24 | Sheet tabs: dragging the handle between the tabs and the horizontal scrollbar gives the tabs more or less of the bar, as in Excel; each open workbook keeps its own share |
| 2026-10-24 | Charts: 100% Stacked Area (`insert.chart` `{type: "area", subtype: "stacked100"}`), drawn as each value's share of its category's total; XLSX `percentStacked` area charts open as 100% stacked instead of stacked |
| 2026-10-24 | XLSX charts keep what GridCraft doesn't model on save: an embedded chart that was not edited (moving or resizing aside) is written back from its original chart part, with its style, colour and user-shape parts, while every sheet its formulas name still exists; an edited chart is written from the model as before (#1668) |
| 2026-10-24 | XLSX: a password to modify (`fileSharing`) is kept on save, and opening such a file asks for the password or opens it read-only (never checked against Excel) (#921) |
| 2026-10-23 | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook; several selected areas print one after the other, as in Excel |
| 2026-10-23 | Accounting negatives in text: `$(1,234)`, `$ (5)` and `(5)%` read as negative numbers when typed, coerced by arithmetic or passed to VALUE, like Excel 365; `(-5)`, `((5))`, `$5%` and dates or times in parentheses stay text |
@@ -321,6 +322,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-25 | minor | Progress log: AutoSum over a selected row, and a selection's empty last row and column |
| 2026-10-24 | minor | Macro interface on the Automate tab; progress log row |
| 2026-10-24 | minor | Macro engine and `macro.*` commands; catalog 275 / 291 → 276 / 292 (View › Macros › Record Macro); progress log row |
| 2026-10-24 | trivial | Progress log: unedited embedded charts keep their XML on save (#1668) |
| 2026-10-24 | minor | Progress log: password to modify (#921) |
| 2026-10-23 | minor | Progress log: accounting negatives in number text |
| 2026-10-23 | minor | Progress log: INDEX with one index on a 2-D reference is #REF! |
+1 -1
View File
@@ -22,7 +22,7 @@ pub use cell::{Cell, CellPicture, Formula};
pub use features::*;
pub use macros::*;
pub use password::PasswordHash;
pub use preserved::{Preserved, PreservedPart, PreservedRel, PreservedSheet, PreservedXml};
pub use preserved::{Preserved, PreservedChart, PreservedPart, PreservedRel, PreservedSheet, PreservedXml};
pub use python::{PyCode, PyOutput};
pub use sheet::{DEFAULT_COL_WIDTH, DEFAULT_ROW_HEIGHT, LineIndex, Sheet, SheetUid, SheetViewMode, Visibility, points_to_chars};
pub use store::CellStore;
+27 -3
View File
@@ -1,12 +1,13 @@
//! File content GridCraft does not model, carried through unchanged so that saving a workbook
//! never silently drops it (XLSX pass-through: custom XML, external links, connections, query
//! tables, form controls, OLE objects…).
//! tables, form controls, OLE objects, chart sheets, and the original XML of embedded charts).
//!
//! The data is opaque to everything except the file-format crate: the model only holds it, so a
//! sheet's kept content disappears with the sheet. It is not part of the JSON format.
use std::sync::Arc;
use crate::features::Chart;
use crate::sheet::Visibility;
use crate::style::Style;
@@ -68,9 +69,25 @@ pub struct PreservedSheet {
pub sheet_id: u32,
}
/// An embedded chart (a chart in a sheet's drawing) kept as it was in the source file, so that
/// what the model doesn't hold (fonts, point colours, axis bounds, line dashes…) survives a save.
/// It is written in place of GridCraft's own chart part only while the model's chart still equals
/// [`Self::chart`], apart from its id and position.
#[derive(Clone, Debug, PartialEq)]
pub struct PreservedChart {
/// The id of the model chart read from it.
pub id: u32,
/// The chart as GridCraft read it from the kept part (id 0, default anchor).
pub chart: Chart,
/// Part name of the chart part in the source file (no leading `/`).
pub part: String,
/// The chart part and every part its relationships reach (style, colours, user shapes…).
pub parts: Vec<PreservedPart>,
}
/// Unmodelled content kept for one owner (the workbook, which also holds package-root content,
/// or one sheet).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Preserved {
/// Relationships of the package root (`_rels/.rels`) to kept parts (workbook owner only).
pub package_rels: Vec<PreservedRel>,
@@ -85,6 +102,8 @@ pub struct Preserved {
pub vml: Option<PreservedPart>,
/// Chart sheets, in file order (workbook owner only).
pub sheets: Vec<PreservedSheet>,
/// The original parts of the sheet's embedded charts (sheet owner only).
pub charts: Vec<PreservedChart>,
}
impl Preserved {
@@ -95,9 +114,14 @@ impl Preserved {
&& self.elements.is_empty()
&& self.vml.is_none()
&& self.sheets.is_empty()
&& self.charts.is_empty()
}
/// Total bytes held.
pub fn byte_len(&self) -> usize {
self.parts.iter().chain(self.vml.iter()).fold(0usize, |n, p| n.saturating_add(p.data.len()))
self.parts
.iter()
.chain(self.vml.iter())
.chain(self.charts.iter().flat_map(|c| c.parts.iter()))
.fold(0usize, |n, p| n.saturating_add(p.data.len()))
}
}
+3
View File
@@ -219,6 +219,9 @@ pub fn read_drawing(cx: &mut Ctx<'_>, part: &str, sheet: &mut Sheet) -> Result<(
Some(mut ch) => {
ch.id = cx.next_object_id();
ch.anchor = anchor;
if !chartex {
cx.chart_parts.push((ch.id, target.clone()));
}
sheet.charts.push(ch);
}
None => cx.warn(format!("chart {target} has no supported plot and was skipped")),
+21 -3
View File
@@ -14,7 +14,9 @@
//! workbook and its `<pivotCache>` entry, its `cacheId` unchanged; a cache on a connection only
//! when the connections are kept, and on the Data Model only when the model is kept. The workbook
//! also keeps its `<fileVersion>` and the calcFeatures extension, which Excel needs to trust the
//! saved values.
//! saved values. Chart sheets are kept whole, and each embedded chart GridCraft reads keeps its
//! original chart part with the style, colour and shape parts behind it, together with the chart
//! as it was read.
//!
//! On write, kept parts get fresh part names where needed and new relationship ids; the `r:id`s in
//! kept XML are rewritten to match. Kept content is conservative:
@@ -28,6 +30,9 @@
//! A kept pivot cache no kept PivotTable uses any more is dropped with it.
//! Cell references inside kept parts (a control's linked cell, a query table's range, a cell
//! mapped to an XML element) are kept as they were, not adjusted to inserted or deleted rows.
//! - An embedded chart's original XML is written back only while the model's chart still equals
//! what was read from it (its position aside) and every sheet its formulas name still exists;
//! otherwise GridCraft writes the chart from the model, as it does for charts it created.
//! - Strict Open XML files are not passed through (their namespaces differ from what we write).
//! - Sizes are bounded: per part and per workbook.
@@ -37,7 +42,9 @@ use std::fmt::Write as _;
use std::path::{Component, Path};
use std::sync::Arc;
use gridcraft_model::{Preserved, PreservedPart, PreservedRel, PreservedSheet, PreservedXml, Sheet, Visibility, Workbook};
use gridcraft_model::{
Anchor, Chart, Preserved, PreservedChart, PreservedPart, PreservedRel, PreservedSheet, PreservedXml, Sheet, Visibility, Workbook,
};
use quick_xml::events::attributes::Attribute;
use quick_xml::events::{BytesStart, Event};
use quick_xml::name::QName;
@@ -58,7 +65,9 @@ pub use read::KeptReader;
pub use rebase::{SheetKept, rebase_links};
#[cfg(test)]
pub(crate) use write::sheet_names_in;
pub use write::{KeptOut, SheetIds, WorkbookKept, finish_style_ids, workbook_elements, write_package_rels, write_workbook};
pub use write::{
KeptOut, SheetIds, WorkbookKept, finish_style_ids, kept_chart, workbook_elements, write_kept_chart, write_package_rels, write_workbook,
};
/// Most bytes kept for one workbook.
pub const MAX_KEPT_TOTAL: usize = 256 * 1024 * 1024;
@@ -166,6 +175,10 @@ const REWRITTEN: &[&str] = &[
/// their style, colour and shape parts are kept byte for byte (the chart sheet is not modelled).
const CHART_SHEET_GRAPH: &[&str] = &["chartsheet", "drawing", "chart", "chartex", "chartstyle", "chartcolorstyle", "chartusershapes"];
/// Relationship kinds an embedded chart part reaches that are otherwise rewritten: its style,
/// colour and user-shape parts are kept with it. A drawing or worksheet is never reached.
const CHART_GRAPH: &[&str] = &["chart", "chartstyle", "chartcolorstyle", "chartusershapes"];
/// Part-name prefixes (lower case) GridCraft's writer never produces: kept parts there keep their
/// original names. Anything else is renamed so it can't collide with written parts.
const OWN_DIRS: &[&str] = &[
@@ -197,6 +210,11 @@ fn rewritten(r: &PreservedRel) -> bool {
!r.external && REWRITTEN.contains(&kind(&r.rel_type).to_ascii_lowercase().as_str())
}
/// A chart without its id and position: what a kept chart is compared on.
fn unplaced(ch: &Chart) -> Chart {
Chart { id: 0, anchor: Anchor::default(), ..ch.clone() }
}
fn rels_part_name(part: &str) -> String {
let (dir, file) = package::split_dir(part);
if dir.is_empty() { format!("_rels/{file}.rels") } else { format!("{dir}/_rels/{file}.rels") }
+23
View File
@@ -302,6 +302,29 @@ impl KeptReader {
(!p.is_empty()).then(|| Arc::new(p))
}
/// Keeps the original chart part, and the parts behind it, of each chart read into `sheet`
/// from a chart part (`Ctx::chart_parts`), with the chart as read. A chart that can't be kept
/// (missing or damaged part, size limits) is written from the model on save, as before.
pub fn charts(&mut self, cx: &mut Ctx<'_>, sheet: &mut Sheet) {
let read = std::mem::take(&mut cx.chart_parts);
if !self.on || read.is_empty() {
return;
}
let mut kept = vec![];
for (id, part) in read {
let Some(ch) = sheet.charts.iter().find(|c| c.id == id) else { continue };
let root = PreservedRel { id: String::new(), rel_type: format!("{NS_REL}/chart"), target: part.clone(), external: false };
if let Ok(parts) = self.closure(cx, &root, &HashSet::new(), CHART_GRAPH) {
kept.push(PreservedChart { id, chart: unplaced(ch), part, parts });
}
}
if !kept.is_empty() {
let mut p = sheet.preserved.as_deref().cloned().unwrap_or_default();
p.charts = kept;
sheet.preserved = Some(Arc::new(p));
}
}
/// The caches of the kept PivotTables, each with its `<pivotCache>` entry (original `cacheId`
/// and relationship id).
fn keep_pivot_caches(&mut self, cx: &mut Ctx<'_>, wb_xml: &xml::El, wb_rels: &[PreservedRel], p: &mut Preserved, seen: &mut HashSet<String>) {
+44 -1
View File
@@ -166,7 +166,11 @@ pub(super) fn part_rels_xml(rels: &[PreservedRel], names: &NameMap) -> String {
}
pub(super) fn write_parts(out: &mut Out, parts: &[PreservedPart]) -> NameMap {
let mut names = NameMap::new();
write_parts_named(out, parts, NameMap::new())
}
/// [`write_parts`] with some parts' new names already chosen in `names`.
fn write_parts_named(out: &mut Out, parts: &[PreservedPart], mut names: NameMap) -> NameMap {
for p in parts {
names.entry(normalize(&p.name)).or_insert_with(|| out.kept.claim(&p.name));
}
@@ -308,6 +312,23 @@ fn reachable(p: &Preserved, root: &PreservedRel) -> HashSet<String> {
seen
}
/// The sheet names the formulas of a kept chart-kind part refer to; `None` when its XML doesn't
/// parse. Parts without formulas (styles, colours) give none.
fn plotted_sheets(q: &PreservedPart) -> Option<Vec<String>> {
if !q.content_type.contains("chart") {
return Some(vec![]);
}
let x = xml::parse(&q.data).ok()?;
let mut formulas = vec![];
chart_formulas(&x, &mut formulas);
Some(formulas.iter().flat_map(|f| sheet_names_in(f)).collect())
}
/// Sheet names as Excel compares them: the first 31 characters, ignoring ASCII case.
fn same_sheet(a: &str, b: &str) -> bool {
a.chars().take(31).collect::<String>().eq_ignore_ascii_case(&b.chars().take(31).collect::<String>())
}
/// Every formula (`<c:f>`) of a chart part, depth first.
fn chart_formulas(el: &xml::El, out: &mut Vec<String>) {
if el.name == "f" && !el.text.trim().is_empty() {
@@ -387,6 +408,28 @@ fn chart_sheet_usable(wb: &Workbook, p: &Preserved, s: &PreservedSheet, usable:
})
}
/// The kept original of the embedded chart `ch` of `sheet`, when it can be written in place of
/// GridCraft's chart part: the chart is unchanged since it was read (moving or resizing it only
/// changes the drawing, which GridCraft writes), every sheet the kept formulas name still exists
/// under the same name (a rename or delete would leave them pointing at nothing), and the kept
/// XML still parses. `None` means: write the chart from the model.
pub fn kept_chart<'a>(wb: &Workbook, sheet: &'a Sheet, ch: &Chart) -> Option<&'a PreservedChart> {
let k = sheet.preserved.as_deref()?.charts.iter().find(|k| k.id == ch.id)?;
if unplaced(ch) != k.chart || !k.parts.iter().any(|q| normalize(&q.name) == normalize(&k.part)) {
return None;
}
let names: Vec<Vec<String>> = k.parts.iter().map(plotted_sheets).collect::<Option<_>>()?;
names.iter().flatten().all(|n| wb.sheets.iter().any(|w| same_sheet(&w.name, n))).then_some(k)
}
/// Writes a kept chart (see [`kept_chart`]): the chart part as `name` (the name GridCraft's writer
/// gives that chart), the parts behind it under fresh names. Returns the id of the drawing's new
/// relationship to it.
pub fn write_kept_chart(k: &PreservedChart, name: &str, drawing_rels: &mut Rels, out: &mut Out) -> String {
write_parts_named(out, &k.parts, NameMap::from([(normalize(&k.part), name.to_string())]));
drawing_rels.add("chart", &format!("/{name}"))
}
/// Writes the workbook's kept parts and relationships. Chart sheets that can't be written back
/// (see [`chart_sheet_usable`]) are left out with the parts only they reach.
pub fn write_workbook(wb: &Workbook, wb_rels: &mut Rels, out: &mut Out) -> WorkbookKept {
+5
View File
@@ -50,6 +50,9 @@ pub struct Ctx<'a> {
pub known_function: Option<&'a dyn Fn(&str) -> bool>,
/// The code of the workbook's Python cells, from its Python part.
pub python: crate::python_part::ScriptsIn,
/// The current sheet's charts read from chart parts: (model chart id, chart part name). Their
/// original XML is kept for saving (see `passthrough`).
pub chart_parts: Vec<(u32, String)>,
/// Cell elements read so far, across every sheet (capped by `sheet_read::MAX_CELLS`).
pub cells: u64,
}
@@ -337,6 +340,7 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W
shared_formula_bytes: 0,
known_function,
python: Default::default(),
chart_parts: vec![],
cells: 0,
};
let root_rels = cx.pkg.rels("")?;
@@ -442,6 +446,7 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W
sheet.preserved = kept.sheet(&mut cx, &rel.target, &name, &external_pivots, &read_controls);
sheet.preserved = crate::extlist::keep_sheet(&mut cx, &name, sheet.preserved.take(), kept.keeps());
sheet.file_id = se.attr_u32("sheetId").unwrap_or(0);
kept.charts(&mut cx, &mut sheet);
sheet.visibility = match se.attr("state") {
Some("hidden") => Visibility::Hidden,
Some("veryHidden") => Visibility::VeryHidden,
+1
View File
@@ -1115,6 +1115,7 @@ mod tests {
sheet_exts_dropped: vec![],
known_function: None,
python: Default::default(),
chart_parts: vec![],
cells: 0,
shared_formula_bytes: 0,
legacy_formulas: vec![],
+8 -2
View File
@@ -463,8 +463,14 @@ fn write_sheet_drawing_rel(wb: &Workbook, si: usize, sheet: &Sheet, rels: &mut R
drels.add_uri(crate::chartex::REL_CHARTEX, &format!("../charts/chartEx{n}.xml"))
} else {
let name = format!("xl/charts/chart{}.xml", out.charts);
out.part(&name, Some(CT_CHART), crate::chart::write_chart(wb, si, ch, &out.book_name).into_bytes());
drels.add("chart", &format!("../charts/chart{}.xml", out.charts))
match crate::passthrough::kept_chart(wb, sheet, ch) {
// Unchanged since it was read: the original part, with what the model doesn't hold.
Some(k) => crate::passthrough::write_kept_chart(k, &name, &mut drels, out),
None => {
out.part(&name, Some(CT_CHART), crate::chart::write_chart(wb, si, ch, &out.book_name).into_bytes());
drels.add("chart", &format!("../charts/chart{}.xml", out.charts))
}
}
};
objs.push(Obj::Chart(ch, rid));
}
+237
View File
@@ -1574,3 +1574,240 @@ fn a_sheet_of_modelled_controls_keeps_nothing_for_them() {
assert_eq!(sh.controls.len(), 2);
assert!(sh.preserved.is_none(), "{:?}", sh.preserved);
}
// ------------------------------------------------------------------ embedded charts (#1668)
const NS_A: &str = "http://schemas.openxmlformats.org/drawingml/2006/main";
const CHART_STYLE: &str = r#"<?xml version="1.0"?><cs:chartStyle xmlns:cs="http://schemas.microsoft.com/office/drawing/2012/chartStyle" id="201"><!-- kept style --></cs:chartStyle>"#;
const CHART_COLORS: &str = r#"<?xml version="1.0"?><cs:colorStyle xmlns:cs="http://schemas.microsoft.com/office/drawing/2012/chartStyle" meth="cycle" id="10"><!-- kept colours --></cs:colorStyle>"#;
const CHART_SHAPES: &str =
r#"<?xml version="1.0"?><c:userShapes xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"><!-- kept text box --></c:userShapes>"#;
/// The chart's relationships to its style, colour and user-shape parts.
const CHART_RELS: &[(&str, &str, &str)] = &[
("rId1", crate::chartex::REL_STYLE, "style1.xml"),
("rId2", crate::chartex::REL_COLORS, "colors1.xml"),
("rId3", "chartUserShapes", "../drawings/drawing2.xml"),
];
/// A column chart with what GridCraft's chart model doesn't hold: a title taken from a cell on
/// another sheet, a title and a chart-wide font size, a series line dash, one point's colour, gap
/// width and overlap, axis bounds and an axis number format.
fn formatted_chart_xml() -> String {
format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<c:chartSpace xmlns:c="{NS_C}" xmlns:a="{NS_A}" xmlns:r="{NS_R}"><c:roundedCorners val="0"/><c:chart><c:title><c:tx><c:strRef><c:f>Notes!$A$1</c:f><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>Quarterly</c:v></c:pt></c:strCache></c:strRef></c:tx><c:overlay val="0"/><c:txPr><a:bodyPr/><a:lstStyle/><a:p><a:pPr><a:defRPr sz="1800" b="1"/></a:pPr><a:endParaRPr lang="en-US"/></a:p></c:txPr></c:title><c:autoTitleDeleted val="0"/><c:plotArea><c:layout/><c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:varyColors val="0"/><c:ser><c:idx val="0"/><c:order val="0"/><c:tx><c:strRef><c:f>Data!$B$1</c:f></c:strRef></c:tx><c:spPr><a:solidFill><a:srgbClr val="4472C4"/></a:solidFill><a:ln w="19050"><a:solidFill><a:srgbClr val="203864"/></a:solidFill><a:prstDash val="dash"/></a:ln></c:spPr><c:invertIfNegative val="0"/><c:dPt><c:idx val="1"/><c:invertIfNegative val="0"/><c:bubble3D val="0"/><c:spPr><a:solidFill><a:srgbClr val="C00000"/></a:solidFill></c:spPr></c:dPt><c:cat><c:strRef><c:f>Data!$A$2:$A$4</c:f></c:strRef></c:cat><c:val><c:numRef><c:f>Data!$B$2:$B$4</c:f><c:numCache><c:formatCode>General</c:formatCode><c:ptCount val="3"/><c:pt idx="0"><c:v>10</c:v></c:pt><c:pt idx="1"><c:v>20</c:v></c:pt><c:pt idx="2"><c:v>30</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser><c:gapWidth val="40"/><c:overlap val="-20"/><c:axId val="111"/><c:axId val="222"/></c:barChart><c:catAx><c:axId val="111"/><c:scaling><c:orientation val="minMax"/></c:scaling><c:delete val="0"/><c:axPos val="b"/><c:crossAx val="222"/></c:catAx><c:valAx><c:axId val="222"/><c:scaling><c:orientation val="minMax"/><c:max val="50"/><c:min val="0"/></c:scaling><c:delete val="0"/><c:axPos val="l"/><c:majorGridlines/><c:numFmt formatCode="0.0" sourceLinked="0"/><c:crossAx val="111"/></c:valAx></c:plotArea><c:legend><c:legendPos val="r"/><c:overlay val="0"/></c:legend><c:plotVisOnly val="1"/></c:chart><c:txPr><a:bodyPr/><a:lstStyle/><a:p><a:pPr><a:defRPr sz="1400"/></a:pPr><a:endParaRPr lang="en-US"/></a:p></c:txPr><c:userShapes r:id="rId3"/></c:chartSpace>"#
)
}
/// Sheets "Data" (with the chart in its drawing) and "Notes" (the cell the chart's title shows).
/// `chart_rels` are the chart part's relationships.
fn embedded_chart_package(chart: &str, chart_rels: &[(&str, &str, &str)]) -> Vec<u8> {
let workbook = format!(
r#"<?xml version="1.0"?><workbook xmlns="{NS_MAIN}" xmlns:r="{NS_R}"><sheets><sheet name="Data" sheetId="1" r:id="rId1"/><sheet name="Notes" sheetId="2" r:id="rId2"/></sheets></workbook>"#
);
let content_types = format!(
r#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Override PartName="/xl/workbook.xml" ContentType="{CT_PREFIX}.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="{CT_PREFIX}.spreadsheetml.worksheet+xml"/><Override PartName="/xl/worksheets/sheet2.xml" ContentType="{CT_PREFIX}.spreadsheetml.worksheet+xml"/><Override PartName="/xl/drawings/drawing1.xml" ContentType="{CT_PREFIX}.drawing+xml"/><Override PartName="/xl/drawings/drawing2.xml" ContentType="{CT_PREFIX}.drawingml.chartshapes+xml"/><Override PartName="/xl/charts/chart1.xml" ContentType="{CT_PREFIX}.drawingml.chart+xml"/><Override PartName="/xl/charts/style1.xml" ContentType="{}"/><Override PartName="/xl/charts/colors1.xml" ContentType="{}"/></Types>"#,
crate::chartex::CT_STYLE,
crate::chartex::CT_COLORS
);
let data = format!(
r#"<?xml version="1.0"?><worksheet xmlns="{NS_MAIN}" xmlns:r="{NS_R}"><sheetData><row r="1"><c r="B1" t="inlineStr"><is><t>Sales</t></is></c></row><row r="2"><c r="A2" t="inlineStr"><is><t>Q1</t></is></c><c r="B2"><v>10</v></c></row><row r="3"><c r="A3" t="inlineStr"><is><t>Q2</t></is></c><c r="B3"><v>20</v></c></row><row r="4"><c r="A4" t="inlineStr"><is><t>Q3</t></is></c><c r="B4"><v>30</v></c></row></sheetData><drawing r:id="rId1"/></worksheet>"#
);
let drawing = format!(
r#"<?xml version="1.0"?><xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="{NS_A}" xmlns:r="{NS_R}" xmlns:c="{NS_C}"><xdr:twoCellAnchor><xdr:from><xdr:col>3</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>1</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from><xdr:to><xdr:col>9</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>15</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:to><xdr:graphicFrame macro=""><xdr:nvGraphicFramePr><xdr:cNvPr id="2" name="Chart 1"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm><a:graphic><a:graphicData uri="{NS_C}"><c:chart r:id="rId1"/></a:graphicData></a:graphic></xdr:graphicFrame><xdr:clientData/></xdr:twoCellAnchor></xdr:wsDr>"#
);
make_zip(&[
("[Content_Types].xml", content_types.as_bytes()),
("_rels/.rels", rels(&[("rId1", "officeDocument", "xl/workbook.xml")]).as_bytes()),
("xl/workbook.xml", workbook.as_bytes()),
(
"xl/_rels/workbook.xml.rels",
rels(&[("rId1", "worksheet", "worksheets/sheet1.xml"), ("rId2", "worksheet", "worksheets/sheet2.xml")]).as_bytes(),
),
("xl/worksheets/sheet1.xml", data.as_bytes()),
("xl/worksheets/sheet2.xml", worksheet_xml("Quarterly").as_bytes()),
("xl/worksheets/_rels/sheet1.xml.rels", rels(&[("rId1", "drawing", "../drawings/drawing1.xml")]).as_bytes()),
("xl/drawings/drawing1.xml", drawing.as_bytes()),
("xl/drawings/_rels/drawing1.xml.rels", rels(&[("rId1", "chart", "../charts/chart1.xml")]).as_bytes()),
("xl/charts/chart1.xml", chart.as_bytes()),
("xl/charts/_rels/chart1.xml.rels", rels(chart_rels).as_bytes()),
("xl/charts/style1.xml", CHART_STYLE.as_bytes()),
("xl/charts/colors1.xml", CHART_COLORS.as_bytes()),
("xl/drawings/drawing2.xml", CHART_SHAPES.as_bytes()),
])
}
/// The chart part the first written sheet shows, found through the sheet's drawing.
fn written_chart(u: &Unpacked) -> String {
let (_, sheet) = u.target("xl/workbook.xml", &attr_of(&u.text("xl/workbook.xml"), "sheet", "r:id"));
let drawing = u.rels(&sheet).into_iter().find(|r| r.1.ends_with("/drawing")).unwrap().2;
let charts: Vec<String> = u.rels(&drawing).into_iter().filter(|r| r.1.ends_with("/chart")).map(|r| r.2).collect();
assert_eq!(charts.len(), 1, "{charts:?}");
charts.into_iter().next().unwrap()
}
/// Two charts are the same apart from their id and position.
fn same_chart(a: &gridcraft_model::Chart, b: &gridcraft_model::Chart) -> bool {
gridcraft_model::Chart { id: b.id, anchor: b.anchor, ..a.clone() } == *b
}
#[test]
fn an_unedited_embedded_chart_keeps_its_xml_and_parts_on_save() {
let chart = formatted_chart_xml();
let (wb, rep) = read_xlsx(&embedded_chart_package(&chart, CHART_RELS)).unwrap();
assert!(!rep.warnings.iter().any(|w| w.contains("chart") || w.contains("dropped")), "{:?}", rep.warnings);
assert_eq!(wb.sheet(0).unwrap().charts.len(), 1);
let out = write_xlsx(&wb).unwrap();
let u = Unpacked::new(&out);
u.assert_valid();
// The chart part, byte for byte, and its style, colour and user-shape parts behind the same
// relationship ids.
let part = written_chart(&u);
assert_eq!(u.text(&part), chart);
let crels = u.rels(&part);
for (id, body) in [("rId1", CHART_STYLE), ("rId2", CHART_COLORS), ("rId3", CHART_SHAPES)] {
let r = crels.iter().find(|r| r.0 == id).unwrap_or_else(|| panic!("no {id} in {crels:?}"));
assert_eq!(u.text(&r.2), body, "{id}");
}
// Reading the output gives the same chart, and a second save keeps it again.
let (wb2, rep2) = read_xlsx(&out).unwrap();
assert!(!rep2.warnings.iter().any(|w| w.contains("chart") || w.contains("dropped")), "{:?}", rep2.warnings);
assert!(same_chart(&wb2.sheet(0).unwrap().charts[0], &wb.sheet(0).unwrap().charts[0]));
let again = Unpacked::new(&write_xlsx(&wb2).unwrap());
again.assert_valid();
assert_eq!(again.text(&written_chart(&again)), chart);
}
#[test]
fn a_moved_and_resized_kept_chart_keeps_its_xml() {
let chart = formatted_chart_xml();
let (mut wb, _) = read_xlsx(&embedded_chart_package(&chart, CHART_RELS)).unwrap();
let ch = &mut wb.sheet_mut(0).unwrap().charts[0];
ch.anchor.cell = gridcraft_core::CellRef::new(20, 6);
ch.anchor.width += 120.0;
ch.anchor.height /= 2.0;
let moved = ch.anchor;
let out = write_xlsx(&wb).unwrap();
let u = Unpacked::new(&out);
u.assert_valid();
assert_eq!(u.text(&written_chart(&u)), chart);
// The drawing, which GridCraft writes, has the new position.
let (wb2, _) = read_xlsx(&out).unwrap();
let a = wb2.sheet(0).unwrap().charts[0].anchor;
assert_eq!(a.cell, moved.cell);
assert!((a.width - moved.width).abs() < 1.0 && (a.height - moved.height).abs() < 1.0, "{a:?} vs {moved:?}");
}
#[test]
fn an_edited_kept_chart_is_written_from_the_model() {
use gridcraft_model::{Chart, ChartKind};
type Edit = fn(&mut Chart);
let chart = formatted_chart_xml();
let edits: [(&str, Edit); 4] = [
("title", |c| c.title = Some("Renamed".into())),
("series range", |c| c.series[0].values = "Data!$B$2:$B$3".into()),
("kind", |c| c.kind = ChartKind::Line),
("legend", |c| c.legend = gridcraft_model::LegendPos::Bottom),
];
for (what, edit) in edits {
let (mut wb, _) = read_xlsx(&embedded_chart_package(&chart, CHART_RELS)).unwrap();
edit(&mut wb.sheet_mut(0).unwrap().charts[0]);
let edited = wb.sheet(0).unwrap().charts[0].clone();
let out = write_xlsx(&wb).unwrap();
let u = Unpacked::new(&out);
u.assert_valid();
let written = u.text(&written_chart(&u));
assert!(!written.contains("prstDash") && !written.contains("Notes!"), "{what}: {written}");
assert!(u.find(CHART_STYLE.as_bytes()).is_empty() && u.find(CHART_SHAPES.as_bytes()).is_empty(), "{what}");
let (wb2, _) = read_xlsx(&out).unwrap();
let back = &wb2.sheet(0).unwrap().charts[0];
assert_eq!(
(&back.title, &back.series[0].values, back.kind, back.legend),
(&edited.title, &edited.series[0].values, edited.kind, edited.legend),
"{what}"
);
}
// A deleted chart takes its kept parts with it.
let (mut wb, _) = read_xlsx(&embedded_chart_package(&chart, CHART_RELS)).unwrap();
wb.sheet_mut(0).unwrap().charts.clear();
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
u.assert_valid();
assert!(u.find(chart.as_bytes()).is_empty() && u.find(CHART_STYLE.as_bytes()).is_empty());
}
#[test]
fn a_kept_chart_naming_a_renamed_or_deleted_sheet_is_written_from_the_model() {
let chart = formatted_chart_xml();
// "Data" renamed: the kept series still say Data!…, so the model writes the chart.
let (mut wb, _) = read_xlsx(&embedded_chart_package(&chart, CHART_RELS)).unwrap();
wb.sheet_mut(0).unwrap().name = "Renamed".into();
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
u.assert_valid();
assert_ne!(u.text(&written_chart(&u)), chart);
assert!(u.find(CHART_STYLE.as_bytes()).is_empty());
// "Notes" deleted: only the title, a reference the model doesn't hold, named it.
let (mut wb, _) = read_xlsx(&embedded_chart_package(&chart, CHART_RELS)).unwrap();
wb.sheets.remove(1);
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
u.assert_valid();
assert!(!u.text(&written_chart(&u)).contains("Notes!"));
// A rename undone before saving keeps it.
let (mut wb, _) = read_xlsx(&embedded_chart_package(&chart, CHART_RELS)).unwrap();
wb.sheet_mut(1).unwrap().name = "Other".into();
wb.sheet_mut(1).unwrap().name = "NOTES".into();
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
assert_eq!(u.text(&written_chart(&u)), chart, "sheet names compare as Excel does, ignoring case");
}
#[test]
fn damaged_or_oversized_kept_charts_fall_back_to_the_model() {
let chart = formatted_chart_xml();
let check = |wb: &gridcraft_model::Workbook, what: &str| {
let u = Unpacked::new(&write_xlsx(wb).unwrap());
u.assert_valid();
let written = u.text(&written_chart(&u));
assert!(!written.contains("prstDash"), "{what}: {written}");
assert!(u.find(CHART_STYLE.as_bytes()).is_empty(), "{what}");
};
let kept = |wb: &gridcraft_model::Workbook| wb.sheet(0).unwrap().preserved.as_ref().is_some_and(|p| !p.charts.is_empty());
// A missing style part, and a graph that reaches a worksheet: read as before, nothing kept.
let missing: Vec<(&str, &str, &str)> = vec![("rId1", crate::chartex::REL_STYLE, "style9.xml")];
let worksheet: Vec<(&str, &str, &str)> = vec![("rId1", "worksheet", "../worksheets/sheet2.xml")];
for (what, chart_rels) in [("missing part", missing), ("reaches a worksheet", worksheet)] {
let (wb, _) = read_xlsx(&embedded_chart_package(&chart, &chart_rels)).unwrap();
assert_eq!(wb.sheet(0).unwrap().charts.len(), 1, "{what}");
assert!(!kept(&wb), "{what}");
check(&wb, what);
}
// Over the kept-bytes allowance.
crate::passthrough::KEPT_TOTAL_FOR_TEST.with(|c| c.set(chart.len() / 2));
let read = read_xlsx(&embedded_chart_package(&chart, CHART_RELS));
crate::passthrough::KEPT_TOTAL_FOR_TEST.with(|c| c.set(crate::passthrough::MAX_KEPT_TOTAL));
let (wb, _) = read.unwrap();
assert!(!kept(&wb));
check(&wb, "too large");
// Kept XML that no longer parses, or a kept chart without its chart part: the model writes it.
type Damage = fn(&mut gridcraft_model::PreservedChart);
let damages: [(&str, Damage); 2] = [
("damaged XML", |k| {
let part = k.part.clone();
if let Some(q) = k.parts.iter_mut().find(|q| q.name == part) {
q.data = Arc::from("<c:chart>".repeat(crate::xml::MAX_DEPTH + 1).into_bytes());
}
}),
("no chart part", |k| {
let part = k.part.clone();
k.parts.retain(|q| q.name != part);
}),
];
for (what, damage) in damages {
let (mut wb, _) = read_xlsx(&embedded_chart_package(&chart, CHART_RELS)).unwrap();
assert!(kept(&wb));
let sheet = wb.sheet_mut(0).unwrap();
let mut p = sheet.preserved.as_deref().cloned().unwrap();
damage(&mut p.charts[0]);
sheet.preserved = Some(Arc::new(p));
check(&wb, what);
}
}
+16 -8
View File
@@ -1,6 +1,6 @@
# Chart parity
> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its series names, category labels and values in Excel's colours, and dragging a corner of the values outline changes the plotted block, #4389, #4390; earlier: combo series drawn and saved by their own kind; earlier: chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: doughnut charts: every series is a concentric ring, the first series innermost; hole size and first slice angle kept; rotated slices cover their own sweep; legend names categories; earlier: charts resize from eight handles, chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-16 · **Change:** minor (an unedited embedded chart keeps its original XML on save (#1668); chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: a selected chart outlines its series names, category labels and values in Excel's colours, and dragging a corner of the values outline changes the plotted block, #4389, #4390; earlier: combo series drawn and saved by their own kind; earlier: chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: doughnut charts: every series is a concentric ring, the first series innermost; hole size and first slice angle kept; rotated slices cover their own sweep; legend names categories; earlier: charts resize from eight handles, chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **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).
@@ -82,11 +82,18 @@ Format reference: [Microsoft's DrawingML data table documentation](https://learn
## XLSX round-trip
Charts are read from and written to DrawingML chart parts, but only the fields the model holds
survive: anything else (axis scaling, label options, error bars, per-point formats, chartex
extensions) is lost when GridCraft saves a workbook it opened. That is the main reason charts are
**~30% ready**: a user who opens an Excel workbook with charts and saves it gets simpler charts
back.
Charts are read from and written to DrawingML chart parts. A chart that was not edited keeps its
original chart part on save, with its style, colour and user-shape parts (#1668): everything the
model doesn't hold (axis scaling, label options, error bars, per-point formats, text boxes in the
chart) survives. Moving or resizing a chart is not an edit. The original part is not used, and
the chart is written from the model as before, when the chart was edited (title, series, kind,
legend…), when a sheet its formulas name was renamed or deleted (including references the model
doesn't hold, such as a title taken from a cell), or after a row or column insert that moved its
series. Then only the fields the model holds survive. Not kept: histogram, waterfall and other
chartex charts (their data goes through `_xlchart` defined names GridCraft renumbers on save),
and charts GridCraft can't read. The kept part's cached series values (`c:numCache`) are not
refreshed when cells change (#1677). That is the main reason charts are **~30% ready**: a user who
edits a chart from an Excel workbook still gets a simpler chart back (#1675).
Series data, categories and names may refer to defined names, as dynamic (OFFSET) ranges do:
Excel writes a workbook-scoped name as `[0]!Name` in `<c:f>`. GridCraft reads it as the bare
@@ -128,7 +135,7 @@ column chart draws and saves its forecast series as columns, not lines.
## Work (40–60 h)
1. Preserve unmodelled chart XML on round-trip (keep the original part, patch only edited fields): 6–10 h.
1. Preserve unmodelled chart XML on round-trip: the original part is kept for unedited charts (#1668); patch only edited fields (#1675) and move references the model doesn't hold (#1676): 4–8 h.
2. Axis options, label options, gridlines per axis, legend formatting: 10–15 h.
3. Error bars; Format Trendline pane (trendlines landed): 4–6 h.
4. Per-element Format pane parity, smoothed lines, exploded pie, pie/bar of pie, 100% variants: 8–12 h.
@@ -147,6 +154,7 @@ column chart draws and saves its forecast series as columns, not lines.
| 2026-10-29 | minor | Selected charts highlight their source cells beneath floating objects, so the blue outline no longer crosses the chart; uncovered source cells remain highlighted (#2861) |
| 2026-10-25 | minor | 100% Stacked Line and 100% Stacked Line with Markers: inserted from the ribbon and All Charts, drawn as shares of each category's total, read and written as `percentStacked` |
| 2026-10-24 | minor | 100% Stacked Area: inserted from the ribbon and All Charts, drawn as shares of each category's total, read and written as `percentStacked` |
| 2026-10-24 | minor | An unedited embedded chart keeps its original chart part, with its style, colour and user-shape parts, on save (#1668) |
| 2026-10-18 | trivial | Stale notes: stock/combo, treemap/sunburst, box and waterfall kinds survive XLSX round-trip (PRs #158, #161) |
| 2026-10-18 | minor | Doughnut charts: every series is a ring (first series innermost), hole size and first slice angle modelled, editable and round-tripped; rotated slices split at 12 o'clock without overlap; legend names categories like Excel's default (#1823) |
| 2026-10-16 | trivial | Series that refer to defined names (`[0]!Name`, `Sheet!Name`) resolve instead of showing `#NAME?`, and are saved qualified, as Excel needs (#1686) |
@@ -158,4 +166,4 @@ column chart draws and saves its forecast series as columns, not lines.
| 2026-10-11 | minor | Recommended Charts dialog with previews (#215) |
| 2026-10-11 | minor | Select Data dialog with category axis labels; a blank top-left cell makes the first column the categories (#287) |
| 2026-10-10 | minor | Smooth lines (#62) and Switch Row/Column on file charts (#116) landed; chart resize bug (#190) |
| 2026-10-10 | major | Created from a source audit: 25 kinds (25 of ~60 subtypes), element gaps, round-trip loss |
| 2026-10-10 | major | Created from a source audit: 25 kinds (25 of ~60 subtypes), element gaps, round-trip loss | 
File diff suppressed because one or more lines are too long