mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-30 10:13:56 +01:00
XLSX: keep self-contained workbook and sheet extLst entries on save
Workbook extLst entries on an allowlist of single attribute-only elements are kept in source order with calcFeatures: x15 and x14 workbookPr, xlwcv:version and the Excel for Mac mx:ArchID. On sheets, the Excel for Mac mx:PLV is kept and written after the extensions the sheet writer emits, skipping any URI it already wrote. Entries are rebuilt from the parsed element with the schema's attributes only. Extensions that point at other content (slicers, timelines, data model, Google Sheets custom data) stay dropped and are named in an open warning. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d9d09f0baa
commit
f066fe994e
11 files changed
+435
-21
No files matched your search
+3
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and whole-row/column formatting) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** trivial (progress log: XLSX self-contained extLst entries kept on save) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
|
||||
GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX
|
||||
is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web.
|
||||
@@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
|
||||
| Date | What landed |
|
||||
|---|---|
|
||||
| 2026-10-14 | XLSX self-contained `extLst` entries are kept on save: x15 and x14 workbook properties, the workbook compatibility version and Excel for Mac entries, alongside calcFeatures; extensions that point at other content (slicers, timelines, data model, Google Sheets data) stay dropped and are named in an open warning |
|
||||
| 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) |
|
||||
| 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) |
|
||||
| 2026-10-12 | Number formats: a fraction denominator with 65,536 zeros no longer crashes; format codes are capped at 255 characters like Excel (longer codes display as General, `TEXT` gives `#VALUE!`) (#807) |
|
||||
@@ -193,6 +194,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-14 | trivial | Progress log: XLSX self-contained extLst entries kept on save |
|
||||
| 2026-10-12 | minor | Rows auto-fit oversized fonts on open and whole-row/column formatting (#833); progress log row |
|
||||
| 2026-10-12 | minor | Progress log: multi-area row/column delete (#758) |
|
||||
| 2026-10-12 | trivial | Progress log: XLSX chart sheets kept on save (#727) |
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
//! Self-contained extensions (`<extLst><ext>`) of the workbook and its sheets, kept on save.
|
||||
//!
|
||||
//! An extension is kept only when its URI is on an allowlist of entries that are one element
|
||||
//! holding attributes and nothing else: no children, no text, no relationship ids, no references
|
||||
//! to cells, names or parts GridCraft renumbers. They are rebuilt from the parsed element with the
|
||||
//! schema's attributes only, in source order. Extensions that point at other content (slicer
|
||||
//! caches and lists, timelines, the data model, PivotTable caches, Google Sheets custom data with
|
||||
//! its `r:id`) are left out: GridCraft rewrites or drops what they point at. Extensions GridCraft
|
||||
//! models itself (x14 conditional formats, data validations, sparklines) are read into the model
|
||||
//! and written by the sheet writer, never kept here. Every other extension is dropped and counted
|
||||
//! in a read warning.
|
||||
//!
|
||||
//! Kept extensions go into the owner's [`Preserved`] as elements of slot `"ext"`: the workbook's
|
||||
//! are written by `write.rs`, a sheet's after the extensions the sheet writer emits, skipping any
|
||||
//! URI it already wrote.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::Arc;
|
||||
|
||||
use gridcraft_model::{Preserved, PreservedXml, Sheet};
|
||||
|
||||
use crate::read::Ctx;
|
||||
use crate::xml::{El, esc_attr};
|
||||
|
||||
/// One allowlisted extension: its URI, the single element it holds and that element's attributes.
|
||||
struct Allowed {
|
||||
uri: &'static str,
|
||||
prefix: &'static str,
|
||||
ns: &'static str,
|
||||
el: &'static str,
|
||||
attrs: &'static [&'static str],
|
||||
}
|
||||
|
||||
const NS_X14: &str = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main";
|
||||
const NS_X15: &str = "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main";
|
||||
const NS_XLWCV: &str = "http://schemas.microsoft.com/office/spreadsheetml/2024/workbookCompatibilityVersion";
|
||||
/// Excel for Mac 2011 extensions; older files use the namespace itself as the URI.
|
||||
const NS_MX: &str = "http://schemas.microsoft.com/office/mac/excel/2008/main";
|
||||
|
||||
/// The workbook extension listing the calculation features the saved values were computed with.
|
||||
/// Excel needs it, with `<fileVersion>`, to trust the saved values (#799).
|
||||
pub(crate) const CALC_FEATURES_URI: &str = "{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}";
|
||||
const NS_CALC_FEATURES: &str = "http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures";
|
||||
|
||||
/// Kept workbook extensions.
|
||||
const WORKBOOK: &[Allowed] = &[
|
||||
// x15:workbookPr (CT_WorkbookPr in the 2010/11 schema).
|
||||
Allowed { uri: "{140A7094-0E35-4892-8432-C4D2E57EDEB5}", prefix: "x15", ns: NS_X15, el: "workbookPr", attrs: &["chartTrackingRefBase"] },
|
||||
// x14:workbookPr (CT_WorkbookPr in the 2009/9 schema).
|
||||
Allowed {
|
||||
uri: "{79F54976-1DA5-4618-B147-4CDE4B953A38}",
|
||||
prefix: "x14",
|
||||
ns: NS_X14,
|
||||
el: "workbookPr",
|
||||
attrs: &["defaultImageDpi", "discardImageEditData", "accuracyVersion"],
|
||||
},
|
||||
// The workbook compatibility version Excel 365 stamps.
|
||||
Allowed { uri: "{D14903EA-33C4-47F7-8F05-3474C54BE107}", prefix: "xlwcv", ns: NS_XLWCV, el: "version", attrs: &["setVersion"] },
|
||||
// Excel for Mac architecture flags.
|
||||
Allowed { uri: "{7523E5D3-25F3-A5E0-1632-64F254C22452}", prefix: "mx", ns: NS_MX, el: "ArchID", attrs: &["Flags"] },
|
||||
Allowed { uri: NS_MX, prefix: "mx", ns: NS_MX, el: "ArchID", attrs: &["Flags"] },
|
||||
];
|
||||
|
||||
/// Kept sheet extensions.
|
||||
const SHEET: &[Allowed] = &[
|
||||
// Excel for Mac page layout view settings.
|
||||
Allowed { uri: "{64002731-A6B0-56B0-2670-7721B7C09600}", prefix: "mx", ns: NS_MX, el: "PLV", attrs: &["Mode", "OnePage", "WScale"] },
|
||||
Allowed { uri: NS_MX, prefix: "mx", ns: NS_MX, el: "PLV", attrs: &["Mode", "OnePage", "WScale"] },
|
||||
];
|
||||
|
||||
/// Sheet extension elements the sheet reader models (x14 conditional formats, data validations,
|
||||
/// sparklines).
|
||||
const SHEET_MODELLED: &[&str] = &["conditionalFormattings", "dataValidations", "sparklineGroups"];
|
||||
|
||||
/// Longest attribute value kept (the kept attributes are flags and small numbers).
|
||||
const MAX_VALUE: usize = 32;
|
||||
/// Most dropped URIs named in one warning.
|
||||
const MAX_NAMED: usize = 5;
|
||||
|
||||
/// The `uri` attribute of `ext`, trimmed.
|
||||
fn uri(ext: &El) -> &str {
|
||||
ext.attr("uri").unwrap_or("").trim()
|
||||
}
|
||||
|
||||
/// `ext` rebuilt from `table` when it is allowlisted and self-contained.
|
||||
fn rebuild(ext: &El, table: &[Allowed]) -> Option<String> {
|
||||
let u = uri(ext);
|
||||
let a = table.iter().find(|a| a.uri.eq_ignore_ascii_case(u))?;
|
||||
// Exactly one element, the expected one, holding attributes only.
|
||||
let [el] = ext.children.as_slice() else { return None };
|
||||
if el.name != a.el || !el.children.is_empty() || !el.text.trim().is_empty() || !ext.text.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut x = format!("<ext uri=\"{}\" xmlns:{p}=\"{}\"><{p}:{}", a.uri, a.ns, a.el, p = a.prefix);
|
||||
for name in a.attrs {
|
||||
if let Some(v) = el.attr(name).map(str::trim)
|
||||
&& !v.is_empty()
|
||||
&& v.len() <= MAX_VALUE
|
||||
&& v.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-')
|
||||
{
|
||||
let _ = write!(x, " {name}=\"{}\"", esc_attr(v));
|
||||
}
|
||||
}
|
||||
x.push_str("/></ext>");
|
||||
Some(x)
|
||||
}
|
||||
|
||||
/// The calcFeatures extension rebuilt: the feature names only.
|
||||
fn calc_features(ext: &El) -> Option<String> {
|
||||
let c = ext.child("calcFeatures")?;
|
||||
let mut x = format!("<ext uri=\"{CALC_FEATURES_URI}\" xmlns:xcalcf=\"{NS_CALC_FEATURES}\"><xcalcf:calcFeatures>");
|
||||
for name in c.kids("feature").filter_map(|f| f.attr("name")) {
|
||||
let _ = write!(x, "<xcalcf:feature name=\"{}\"/>", esc_attr(name));
|
||||
}
|
||||
x.push_str("</xcalcf:calcFeatures></ext>");
|
||||
Some(x)
|
||||
}
|
||||
|
||||
/// Adds `uri` to the dropped list once.
|
||||
fn dropped(list: &mut Vec<String>, uri: &str) {
|
||||
let u = if uri.is_empty() { "(no URI)".to_string() } else { uri.to_string() };
|
||||
if !list.iter().any(|d| d.eq_ignore_ascii_case(&u)) {
|
||||
list.push(u);
|
||||
}
|
||||
}
|
||||
|
||||
/// The read warning naming the dropped extension URIs of `owner` ("the workbook", "sheet \"A\"").
|
||||
fn warn_dropped(cx: &mut Ctx<'_>, owner: &str, list: &[String]) {
|
||||
if list.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut named = list.iter().take(MAX_NAMED).cloned().collect::<Vec<_>>().join(", ");
|
||||
if list.len() > MAX_NAMED {
|
||||
let _ = write!(named, " and {} more", list.len() - MAX_NAMED);
|
||||
}
|
||||
let n = list.len();
|
||||
cx.warn(format!(
|
||||
"{owner}: {n} Excel extension{} GridCraft does not model {} dropped ({named})",
|
||||
if n == 1 { "" } else { "s" },
|
||||
if n == 1 { "was" } else { "were" }
|
||||
));
|
||||
}
|
||||
|
||||
/// Keeps the workbook's calcFeatures and allowlisted extensions from `ext_lst` (the workbook's
|
||||
/// `<extLst>`), in source order, as elements of slot `"ext"` of `p`; warns about the others.
|
||||
pub(crate) fn keep_workbook(cx: &mut Ctx<'_>, ext_lst: Option<&El>, p: &mut Preserved) {
|
||||
let Some(list) = ext_lst else { return };
|
||||
let mut kept: Vec<String> = vec![];
|
||||
let mut lost = vec![];
|
||||
for ext in list.kids("ext") {
|
||||
let u = uri(ext);
|
||||
if kept.iter().any(|k| k.eq_ignore_ascii_case(u)) {
|
||||
continue;
|
||||
}
|
||||
let x = if u.eq_ignore_ascii_case(CALC_FEATURES_URI) { calc_features(ext) } else { rebuild(ext, WORKBOOK) };
|
||||
match x {
|
||||
Some(x) => {
|
||||
kept.push(u.to_string());
|
||||
p.elements.push(PreservedXml { slot: "ext".into(), xml: x });
|
||||
}
|
||||
None => dropped(&mut lost, u),
|
||||
}
|
||||
}
|
||||
warn_dropped(cx, "the workbook", &lost);
|
||||
}
|
||||
|
||||
/// While a sheet is read: keeps the allowlisted extension `ext` of its `<extLst>` until
|
||||
/// [`keep_sheet`] attaches it, or counts it as dropped. Modelled extensions are left to the
|
||||
/// sheet reader.
|
||||
pub(crate) fn read_sheet_ext(cx: &mut Ctx<'_>, ext: &El) {
|
||||
if ext.children.iter().any(|c| SHEET_MODELLED.contains(&c.name.as_str())) {
|
||||
return;
|
||||
}
|
||||
let u = uri(ext);
|
||||
if cx.sheet_exts.iter().any(|(k, _)| k.eq_ignore_ascii_case(u)) {
|
||||
return;
|
||||
}
|
||||
match rebuild(ext, SHEET) {
|
||||
Some(x) => cx.sheet_exts.push((u.to_string(), x)),
|
||||
None => dropped(&mut cx.sheet_exts_dropped, u),
|
||||
}
|
||||
}
|
||||
|
||||
/// After a sheet is read: adds the extensions [`read_sheet_ext`] kept to `preserved` (the sheet's
|
||||
/// other kept content), when unmodelled content is kept at all (`keep`), and warns about the
|
||||
/// dropped ones.
|
||||
pub(crate) fn keep_sheet(cx: &mut Ctx<'_>, name: &str, preserved: Option<Arc<Preserved>>, keep: bool) -> Option<Arc<Preserved>> {
|
||||
let exts = std::mem::take(&mut cx.sheet_exts);
|
||||
let mut lost = std::mem::take(&mut cx.sheet_exts_dropped);
|
||||
if !keep {
|
||||
for (u, _) in &exts {
|
||||
dropped(&mut lost, u);
|
||||
}
|
||||
}
|
||||
warn_dropped(cx, &format!("sheet \"{name}\""), &lost);
|
||||
if !keep || exts.is_empty() {
|
||||
return preserved;
|
||||
}
|
||||
let mut p = preserved.map(Arc::unwrap_or_clone).unwrap_or_default();
|
||||
p.elements.extend(exts.into_iter().map(|(_, xml)| PreservedXml { slot: "ext".into(), xml }));
|
||||
Some(Arc::new(p))
|
||||
}
|
||||
|
||||
/// The kept extensions of `sheet`, minus those whose URI is in `written` (the `<ext>` elements the
|
||||
/// sheet writer already emitted).
|
||||
pub(crate) fn sheet_exts(sheet: &Sheet, written: &str) -> String {
|
||||
let Some(p) = sheet.preserved.as_deref() else { return String::new() };
|
||||
let lower = written.to_ascii_lowercase();
|
||||
let mut s = String::new();
|
||||
for e in p.elements.iter().filter(|e| e.slot == "ext") {
|
||||
let uri = e.xml.split('"').nth(1).unwrap_or("");
|
||||
if uri.is_empty() || !lower.contains(&format!("uri=\"{}\"", uri.to_ascii_lowercase())) {
|
||||
s.push_str(&e.xml);
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::xml::parse;
|
||||
|
||||
fn ext(x: &str) -> El {
|
||||
parse(x.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebuilds_allowlisted_entries_only() {
|
||||
let x15 =
|
||||
ext(r#"<ext uri="{140a7094-0e35-4892-8432-c4d2e57edeb5}" xmlns:x15="x"><x15:workbookPr chartTrackingRefBase="1" other="2"/></ext>"#);
|
||||
assert_eq!(
|
||||
rebuild(&x15, WORKBOOK).as_deref(),
|
||||
Some(
|
||||
format!(
|
||||
r#"<ext uri="{{140A7094-0E35-4892-8432-C4D2E57EDEB5}}" xmlns:x15="{NS_X15}"><x15:workbookPr chartTrackingRefBase="1"/></ext>"#
|
||||
)
|
||||
.as_str()
|
||||
)
|
||||
);
|
||||
// A known URI with unexpected content: children, text, another element, or nothing.
|
||||
for bad in [
|
||||
r#"<ext uri="{140A7094-0E35-4892-8432-C4D2E57EDEB5}"><x15:workbookPr><x:y/></x15:workbookPr></ext>"#,
|
||||
r#"<ext uri="{140A7094-0E35-4892-8432-C4D2E57EDEB5}"><x15:workbookPr>text</x15:workbookPr></ext>"#,
|
||||
r#"<ext uri="{140A7094-0E35-4892-8432-C4D2E57EDEB5}"><x15:other/></ext>"#,
|
||||
r#"<ext uri="{140A7094-0E35-4892-8432-C4D2E57EDEB5}"><x15:workbookPr/><x15:workbookPr/></ext>"#,
|
||||
r#"<ext uri="{140A7094-0E35-4892-8432-C4D2E57EDEB5}"/>"#,
|
||||
] {
|
||||
assert_eq!(rebuild(&ext(bad), WORKBOOK), None, "{bad}");
|
||||
}
|
||||
// Not allowlisted: the data model and slicer caches point at other parts.
|
||||
for uri in ["{FCE2AD5D-F65C-4FA6-A056-5C36A1767C68}", "{BBE1A952-AA13-448e-AADC-164F8A28A991}", "GOOGLESHEETSCUSTOMDATAVERSION2"] {
|
||||
assert_eq!(rebuild(&ext(&format!(r#"<ext uri="{uri}"><x:workbookPr/></ext>"#)), WORKBOOK), None);
|
||||
}
|
||||
// Sheet entries are not workbook entries.
|
||||
let plv = ext(r#"<ext uri="{64002731-A6B0-56B0-2670-7721B7C09600}"><mx:PLV Mode="1" OnePage="0" WScale="0"/></ext>"#);
|
||||
assert_eq!(rebuild(&plv, WORKBOOK), None);
|
||||
assert!(rebuild(&plv, SHEET).unwrap().contains(r#"<mx:PLV Mode="1" OnePage="0" WScale="0"/>"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_that_are_not_flags_or_numbers_are_left_out() {
|
||||
let e =
|
||||
ext(r#"<ext uri="{79F54976-1DA5-4618-B147-4CDE4B953A38}"><x14:workbookPr defaultImageDpi=""><x" accuracyVersion="1"/></ext>"#);
|
||||
assert_eq!(
|
||||
rebuild(&e, WORKBOOK).as_deref(),
|
||||
Some(
|
||||
format!(r#"<ext uri="{{79F54976-1DA5-4618-B147-4CDE4B953A38}}" xmlns:x14="{NS_X14}"><x14:workbookPr accuracyVersion="1"/></ext>"#)
|
||||
.as_str()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn written_uris_are_not_repeated() {
|
||||
let mut sheet = Sheet::new("A".to_string());
|
||||
let plv = rebuild(&ext(r#"<ext uri="{64002731-A6B0-56B0-2670-7721B7C09600}"><mx:PLV Mode="0"/></ext>"#), SHEET).unwrap();
|
||||
sheet.preserved = Some(Arc::new(Preserved { elements: vec![PreservedXml { slot: "ext".into(), xml: plv.clone() }], ..Default::default() }));
|
||||
assert_eq!(sheet_exts(&sheet, ""), plv);
|
||||
assert_eq!(sheet_exts(&sheet, r#"<ext uri="{64002731-a6b0-56b0-2670-7721b7c09600}">"#), "");
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ mod chartex;
|
||||
mod crypto;
|
||||
mod csv;
|
||||
mod drawing;
|
||||
mod extlist;
|
||||
mod feature_bags;
|
||||
mod fmla;
|
||||
mod ods;
|
||||
|
||||
@@ -75,6 +75,13 @@ fn kept_total() -> usize {
|
||||
}
|
||||
}
|
||||
|
||||
impl KeptReader {
|
||||
/// Whether unmodelled content is kept for this package (not for Strict Open XML files).
|
||||
pub fn keeps(&self) -> bool {
|
||||
self.on
|
||||
}
|
||||
}
|
||||
|
||||
const NS_REL_STRICT: &str = "http://purl.oclc.org/ooxml/officeDocument/relationships";
|
||||
const CT_VML: &str = "application/vnd.openxmlformats-officedocument.vmlDrawing";
|
||||
|
||||
@@ -88,9 +95,6 @@ const SHEET_ROOTS: &[&str] = &["queryTable", "tableSingleCells"];
|
||||
const SHEET_ELEMENT_KINDS: &[&str] = &["oleObject", "ctrlProp", "control", "image", "package", "printerSettings"];
|
||||
/// Attributes of `<fileVersion>` (CT_FileVersion).
|
||||
const FILE_VERSION_ATTRS: &[&str] = &["appName", "lastEdited", "lowestEdited", "rupBuild", "codeName"];
|
||||
/// The workbook extension listing the calculation features the saved values were computed with.
|
||||
const CALC_FEATURES_URI: &str = "{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}";
|
||||
const NS_CALC_FEATURES: &str = "http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures";
|
||||
/// Kept sheet elements, in schema order (all after `<legacyDrawing>`, before `<tableParts>`).
|
||||
const SHEET_SLOTS: &[&str] = &["picture", "oleObjects", "controls"];
|
||||
|
||||
@@ -445,18 +449,8 @@ impl KeptReader {
|
||||
x.push_str("/>");
|
||||
p.elements.push(PreservedXml { slot: "fileVersion".into(), xml: x });
|
||||
}
|
||||
let calc_features = wb_xml
|
||||
.child("extLst")
|
||||
.and_then(|l| l.kids("ext").find(|e| e.attr("uri").is_some_and(|u| u.eq_ignore_ascii_case(CALC_FEATURES_URI))))
|
||||
.and_then(|e| e.child("calcFeatures"));
|
||||
if let Some(c) = calc_features {
|
||||
let mut x = format!("<ext uri=\"{CALC_FEATURES_URI}\" xmlns:xcalcf=\"{NS_CALC_FEATURES}\"><xcalcf:calcFeatures>");
|
||||
for name in c.kids("feature").filter_map(|f| f.attr("name")) {
|
||||
let _ = write!(x, "<xcalcf:feature name=\"{}\"/>", esc_attr(name));
|
||||
}
|
||||
x.push_str("</xcalcf:calcFeatures></ext>");
|
||||
p.elements.push(PreservedXml { slot: "ext".into(), xml: x });
|
||||
}
|
||||
// calcFeatures and the self-contained extensions (x14/x15 workbookPr, Mac entries).
|
||||
crate::extlist::keep_workbook(cx, wb_xml.child("extLst"), &mut p);
|
||||
(!p.is_empty()).then(|| Arc::new(p))
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,10 @@ pub struct Ctx<'a> {
|
||||
pub cell_pictures: Vec<Option<Arc<CellPicture>>>,
|
||||
/// 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)>,
|
||||
/// Kept extensions of the current sheet's `<extLst>` (URI, rebuilt XML), until attached.
|
||||
pub sheet_exts: Vec<(String, String)>,
|
||||
/// URIs of the current sheet's extensions that were dropped.
|
||||
pub sheet_exts_dropped: Vec<String>,
|
||||
}
|
||||
|
||||
impl Ctx<'_> {
|
||||
@@ -82,6 +86,8 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> {
|
||||
num_fmts: Default::default(),
|
||||
cell_pictures: vec![],
|
||||
cf_ext_ids: vec![],
|
||||
sheet_exts: vec![],
|
||||
sheet_exts_dropped: 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());
|
||||
@@ -238,6 +244,8 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> {
|
||||
Some("veryHidden") => Visibility::VeryHidden,
|
||||
_ => Visibility::Visible,
|
||||
};
|
||||
// Self-contained sheet extensions (Excel for Mac page layout settings).
|
||||
sheet.preserved = crate::extlist::keep_sheet(&mut cx, &name, sheet.preserved.take(), kept.keeps());
|
||||
file_to_model.push(Some(wb.sheets.len()));
|
||||
wb.sheets.push(Arc::new(sheet));
|
||||
}
|
||||
|
||||
@@ -952,6 +952,7 @@ fn read_threaded(cx: &Ctx<'_>, x: &El, sheet: &mut Sheet) {
|
||||
/// Worksheet extensions: x14 data validations and sparklines.
|
||||
fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) {
|
||||
for ext in e.kids("ext") {
|
||||
crate::extlist::read_sheet_ext(cx, ext);
|
||||
for c in &ext.children {
|
||||
match c.name.as_str() {
|
||||
"dataValidations" => {
|
||||
|
||||
@@ -584,9 +584,13 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> (
|
||||
.filter(|(_, cf)| !cf.ranges.is_empty() && matches!(cf.rule, CfRule::DataBar { gradient: false, .. }))
|
||||
.map(|(i, cf)| (cf, prio.get(i).copied().unwrap_or(1)))
|
||||
.collect();
|
||||
if !solid_bars.is_empty() || !sheet.sparklines.is_empty() {
|
||||
// Then the self-contained extensions kept from the source file.
|
||||
let has_kept_exts = !crate::extlist::sheet_exts(sheet, "").is_empty();
|
||||
let has_exts = !solid_bars.is_empty() || !sheet.sparklines.is_empty() || has_kept_exts;
|
||||
if has_exts {
|
||||
s.push_str("<extLst>");
|
||||
}
|
||||
let exts_start = s.len();
|
||||
if !solid_bars.is_empty() {
|
||||
let _ = write!(
|
||||
s,
|
||||
@@ -622,7 +626,9 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> (
|
||||
}
|
||||
s.push_str("</x14:sparklineGroups></ext>");
|
||||
}
|
||||
if !solid_bars.is_empty() || !sheet.sparklines.is_empty() {
|
||||
if has_exts {
|
||||
let kept_exts = crate::extlist::sheet_exts(sheet, s.get(exts_start..).unwrap_or(""));
|
||||
s.push_str(&kept_exts);
|
||||
s.push_str("</extLst>");
|
||||
}
|
||||
s.push_str("</worksheet>");
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Workbook and sheet extensions (`<extLst>`) kept on save. Packages are built in code.
|
||||
|
||||
use std::io::Read;
|
||||
|
||||
use super::{CT, ROOT_RELS, make_zip};
|
||||
use crate::{read_xlsx, write_xlsx};
|
||||
|
||||
const NS_MAIN: &str = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
|
||||
const NS_R: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
const NS_X14: &str = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main";
|
||||
const NS_X15: &str = "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main";
|
||||
const NS_MX: &str = "http://schemas.microsoft.com/office/mac/excel/2008/main";
|
||||
|
||||
const CALC: &str = r#"<ext uri="{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}" xmlns:xcalcf="http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures"><xcalcf:calcFeatures><xcalcf:feature name="microsoft.com:RD"/></xcalcf:calcFeatures></ext>"#;
|
||||
const X14_WB: &str = r#"<ext uri="{79F54976-1DA5-4618-B147-4CDE4B953A38}" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"><x14:workbookPr defaultImageDpi="220"/></ext>"#;
|
||||
const X15_WB: &str = r#"<ext uri="{140A7094-0E35-4892-8432-C4D2E57EDEB5}" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"><x15:workbookPr chartTrackingRefBase="1"/></ext>"#;
|
||||
const XLWCV: &str = r#"<ext uri="{D14903EA-33C4-47F7-8F05-3474C54BE107}" xmlns:xlwcv="http://schemas.microsoft.com/office/spreadsheetml/2024/workbookCompatibilityVersion"><xlwcv:version setVersion="1"/></ext>"#;
|
||||
const ARCH_ID: &str = r#"<ext uri="{7523E5D3-25F3-A5E0-1632-64F254C22452}" xmlns:mx="http://schemas.microsoft.com/office/mac/excel/2008/main"><mx:ArchID Flags="2"/></ext>"#;
|
||||
const PLV: &str = r#"<ext uri="{64002731-A6B0-56B0-2670-7721B7C09600}" xmlns:mx="http://schemas.microsoft.com/office/mac/excel/2008/main"><mx:PLV Mode="1" OnePage="0" WScale="0"/></ext>"#;
|
||||
|
||||
/// A workbook whose `<extLst>` holds the kept extensions, interleaved with ones that point at
|
||||
/// other content (the data model, Google Sheets custom data); sheet "A" has a sparkline, Mac page
|
||||
/// layout settings and a web extension reference.
|
||||
fn package() -> Vec<u8> {
|
||||
let workbook = format!(
|
||||
r#"<?xml version="1.0"?><workbook xmlns="{NS_MAIN}" xmlns:r="{NS_R}"><fileVersion appName="xl" lastEdited="7" lowestEdited="7" rupBuild="27328"/><workbookPr/><sheets><sheet name="A" sheetId="1" r:id="rId1"/></sheets><calcPr calcId="191029"/><extLst>{X14_WB}<ext uri="{{FCE2AD5D-F65C-4FA6-A056-5C36A1767C68}}" xmlns:x15="{NS_X15}"><x15:dataModel><x15:modelTables><x15:modelTable id="T" name="T" connection="C"/></x15:modelTables></x15:dataModel></ext>{X15_WB}{CALC}<ext uri="GOOGLESHEETSCUSTOMDATAVERSION2"><go:sheetsCustomData xmlns:go="http://customooxmlschemas.google.com/" r:id="rId9" roundtripDataChecksum="x"/></ext>{XLWCV}{ARCH_ID}</extLst></workbook>"#
|
||||
);
|
||||
let sheet = format!(
|
||||
r#"<?xml version="1.0"?><worksheet xmlns="{NS_MAIN}" xmlns:r="{NS_R}"><sheetData><row r="1"><c r="A1"><v>1</v></c><c r="B1"><v>2</v></c></row></sheetData><extLst><ext uri="{{05C60535-1F16-4fd2-B633-F4F36F0B64E0}}" xmlns:x14="{NS_X14}"><x14:sparklineGroups xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main"><x14:sparklineGroup><x14:colorSeries rgb="FF376092"/><x14:sparklines><x14:sparkline><xm:f>A!A1:B1</xm:f><xm:sqref>C1</xm:sqref></x14:sparkline></x14:sparklines></x14:sparklineGroup></x14:sparklineGroups></ext><ext uri="{{64002731-A6B0-56B0-2670-7721B7C09600}}" xmlns:mx="{NS_MX}"><mx:PLV Mode="1" OnePage="0" WScale="0"/></ext><ext uri="{{F7C9EE02-42E1-4005-9D12-6889AFFD525C}}" xmlns:x15="{NS_X15}"><x15:webExtensions><x15:webExtension appRef="{{00000000-0000-0000-0000-000000000000}}"/></x15:webExtensions></ext></extLst></worksheet>"#
|
||||
);
|
||||
let rels = format!(
|
||||
r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="{NS_R}/worksheet" Target="worksheets/sheet1.xml"/></Relationships>"#
|
||||
);
|
||||
make_zip(&[
|
||||
("[Content_Types].xml", CT.as_bytes()),
|
||||
("_rels/.rels", ROOT_RELS.as_bytes()),
|
||||
("xl/workbook.xml", workbook.as_bytes()),
|
||||
("xl/_rels/workbook.xml.rels", rels.as_bytes()),
|
||||
("xl/worksheets/sheet1.xml", sheet.as_bytes()),
|
||||
])
|
||||
}
|
||||
|
||||
fn part(bytes: &[u8], name: &str) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name(name).unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The `<extLst>…</extLst>` of a part.
|
||||
fn ext_lst(xml: &str) -> &str {
|
||||
let a = xml.find("<extLst>").unwrap_or_else(|| panic!("no extLst: {xml}"));
|
||||
let b = xml.find("</extLst>").unwrap();
|
||||
&xml[a..b + "</extLst>".len()]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn self_contained_extensions_survive_saves_in_source_order() {
|
||||
let (wb, report) = read_xlsx(&package()).unwrap();
|
||||
let w = report.warnings.iter().find(|w| w.starts_with("the workbook:")).unwrap_or_else(|| panic!("{:?}", report.warnings));
|
||||
assert!(
|
||||
w.contains("2 Excel extensions") && w.contains("{FCE2AD5D-F65C-4FA6-A056-5C36A1767C68}") && w.contains("GOOGLESHEETSCUSTOMDATAVERSION2"),
|
||||
"{w}"
|
||||
);
|
||||
let s = report.warnings.iter().find(|w| w.starts_with("sheet \"A\":")).unwrap_or_else(|| panic!("{:?}", report.warnings));
|
||||
assert!(s.contains("1 Excel extension ") && s.contains("{F7C9EE02-42E1-4005-9D12-6889AFFD525C}"), "{s}");
|
||||
// Twice: what was kept on the first save is read back and kept again.
|
||||
let first = write_xlsx(&wb).unwrap();
|
||||
let (again, report) = read_xlsx(&first).unwrap();
|
||||
assert!(!report.warnings.iter().any(|w| w.contains("Excel extension")), "{:?}", report.warnings);
|
||||
for saved in [first, write_xlsx(&again).unwrap()] {
|
||||
let book = part(&saved, "xl/workbook.xml");
|
||||
assert_eq!(ext_lst(&book), format!("<extLst>{X14_WB}{X15_WB}{CALC}{XLWCV}{ARCH_ID}</extLst>"));
|
||||
assert!(book.ends_with("</extLst></workbook>"), "{book}");
|
||||
let sheet = part(&saved, "xl/worksheets/sheet1.xml");
|
||||
let list = ext_lst(&sheet);
|
||||
// The sparkline written by the sheet writer once, then the kept page layout settings once.
|
||||
assert_eq!(list.matches("{05C60535-1F16-4fd2-B633-F4F36F0B64E0}").count(), 1, "{list}");
|
||||
assert_eq!(list.matches("{64002731-A6B0-56B0-2670-7721B7C09600}").count(), 1, "{list}");
|
||||
assert!(list.ends_with(&format!("{PLV}</extLst>")), "{list}");
|
||||
assert!(!list.contains("webExtension"), "{list}");
|
||||
crate::xml::parse(sheet.as_bytes()).unwrap();
|
||||
crate::xml::parse(book.as_bytes()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sheet_with_only_kept_extensions_gets_an_ext_list() {
|
||||
let sheet = format!(r#"<?xml version="1.0"?><worksheet xmlns="{NS_MAIN}"><sheetData/><extLst>{PLV}</extLst></worksheet>"#);
|
||||
let rels = format!(
|
||||
r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="{NS_R}/worksheet" Target="worksheets/sheet1.xml"/></Relationships>"#
|
||||
);
|
||||
let workbook = format!(
|
||||
r#"<?xml version="1.0"?><workbook xmlns="{NS_MAIN}" xmlns:r="{NS_R}"><sheets><sheet name="A" sheetId="1" r:id="rId1"/></sheets></workbook>"#
|
||||
);
|
||||
let bytes = make_zip(&[
|
||||
("[Content_Types].xml", CT.as_bytes()),
|
||||
("_rels/.rels", ROOT_RELS.as_bytes()),
|
||||
("xl/workbook.xml", workbook.as_bytes()),
|
||||
("xl/_rels/workbook.xml.rels", rels.as_bytes()),
|
||||
("xl/worksheets/sheet1.xml", sheet.as_bytes()),
|
||||
]);
|
||||
let (wb, report) = read_xlsx(&bytes).unwrap();
|
||||
assert!(!report.warnings.iter().any(|w| w.contains("Excel extension")), "{:?}", report.warnings);
|
||||
let saved = write_xlsx(&wb).unwrap();
|
||||
assert!(part(&saved, "xl/worksheets/sheet1.xml").ends_with(&format!("<extLst>{PLV}</extLst></worksheet>")));
|
||||
// No extension on the workbook: none written.
|
||||
assert!(!part(&saved, "xl/workbook.xml").contains("extLst"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_workbook_has_no_ext_lists() {
|
||||
let saved = write_xlsx(&gridcraft_model::Workbook::new()).unwrap();
|
||||
assert!(!part(&saved, "xl/workbook.xml").contains("extLst"));
|
||||
assert!(!part(&saved, "xl/worksheets/sheet1.xml").contains("extLst"));
|
||||
}
|
||||
@@ -4,6 +4,7 @@ mod array_export;
|
||||
mod chart_bool_default;
|
||||
mod csv_tests;
|
||||
mod encrypted_tests;
|
||||
mod extlist;
|
||||
mod fixtures;
|
||||
mod ink_roundtrip;
|
||||
mod literal_category_roundtrip;
|
||||
|
||||
@@ -816,7 +816,9 @@ fn file_version_and_calc_features_survive_a_save() {
|
||||
assert_eq!(root.children.first().map(|e| e.name.as_str()), Some("fileVersion"), "{text}");
|
||||
assert_eq!(root.children.last().map(|e| e.name.as_str()), Some("extLst"), "{text}");
|
||||
assert!(text.contains(r#"<fileVersion appName="xl" lastEdited="7" lowestEdited="7" rupBuild="11008"/>"#), "{text}");
|
||||
assert!(text.contains(&format!("<extLst>{calc_features}</extLst>")), "{text}");
|
||||
// The x15 workbook properties are kept too, in source order (see tests::extlist).
|
||||
let x15 = r#"<ext uri="{140A7094-0E35-4892-8432-C4D2E57EDEB5}" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"><x15:workbookPr chartTrackingRefBase="1"/></ext>"#;
|
||||
assert!(text.contains(&format!("<extLst>{x15}{calc_features}</extLst>")), "{text}");
|
||||
}
|
||||
|
||||
// A workbook that had neither gets neither.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# File-format parity
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** trivial (XLSX chart sheets are kept on save (#727); previously minor: CSV save keeps the separator it was opened with) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** trivial (XLSX self-contained workbook and sheet extensions are kept on save; previously trivial: chart sheets are kept on save (#727)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
|
||||
Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests.
|
||||
Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h**
|
||||
@@ -22,7 +22,7 @@ and repair-free opening remain unverified.
|
||||
|
||||
| Format | Excel | GridCraft read | GridCraft write | Fidelity / notes | Tests |
|
||||
|---|---|---|---|---|---|
|
||||
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
|
||||
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. Self-contained `extLst` entries (`extlist.rs`, an allowlist of single attribute-only elements, rebuilt in source order): the workbook's calcFeatures, x15 and x14 `workbookPr`, `xlwcv:version` and Excel for Mac `mx:ArchID`, and the sheet's Excel for Mac `mx:PLV`. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, other sheet and workbook `extLst` entries we don't model (each dropped URI is named in an open warning), chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
|
||||
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
|
||||
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
|
||||
| `.xlsx` Strict Open XML | R/W | yes | no (writes transitional) | Excel also saves transitional by default | fixtures |
|
||||
@@ -85,6 +85,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-14 | trivial | XLSX self-contained workbook and sheet `extLst` entries are kept on save; the others are named in an open warning |
|
||||
| 2026-10-12 | trivial | XLSX chart sheets are kept on save (#727) |
|
||||
| 2026-10-12 | trivial | CSV and TSV export is capped at 512 MiB and refuses a larger used range with an error (#528) |
|
||||
| 2026-10-12 | minor | `.xls` import reads the calculation settings (CalcMode, CalcIter, CalcCount, CalcDelta, CalcPrecision), so circular models calculate instead of showing `#CIRC!` (#724) |
|
||||
|
||||
Reference in new issue
Block a user