mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-28 17:30:24 +01:00
ft-3ir.2.1: keep PivotTables on a data connection or the Data Model on XLSX save
A PivotTable whose cache has cacheSource type="external" (a data connection, or the workbook's Data Model: OLAP caches with saveData="0" and no records) was read as unsupported and dropped on save with its cache, and the Data Model part (xl/model/item.data) was never kept. Such PivotTables are now reported by read_pivots and kept by the pass-through layer like those on another workbook: table, cache and records parts unchanged, original cacheId, style ids renumbered. The connection is looked up in xl/connections.xml to tell the Data Model from a plain connection. The Data Model part is kept byte for byte whenever the workbook's connections are kept. A cache on a connection is kept only with the connections, one on the model only with the model; otherwise its PivotTable is left as plain cells with one warning. Checked in Excel with synthetic workbooks: Excel needs the table, cache, connections.xml and the hidden _xlcn. name of a worksheet connection to open the file, and item.data to refresh it; the x15:dataModel workbook extension is not needed and is not kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8732325b58
commit
cdb3c163ec
7 files changed
+406
-36
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-14 · **Change:** trivial (progress log: XLSX PivotTables on another workbook kept on save) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-15 · **Change:** trivial (progress log: XLSX PivotTables on a data connection or the Data Model 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-15 | XLSX PivotTables on a data connection or the Data Model are kept on save (they were dropped), with the Data Model (`xl/model/item.data`) byte for byte; Excel opens the result without repair and refreshes it |
|
||||
| 2026-10-14 | XLSX PivotTables whose source is a range or name in another workbook are kept on save (they were dropped): table, cache and records parts unchanged, style references renumbered; Excel opens the result without repair and refreshes it |
|
||||
| 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) |
|
||||
@@ -194,6 +195,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-15 | trivial | Progress log: XLSX PivotTables on a data connection or the Data Model kept on save |
|
||||
| 2026-10-14 | trivial | Progress log: XLSX PivotTables on another workbook 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) |
|
||||
|
||||
@@ -594,7 +594,7 @@ fn cond_format_list(s: &Sheet) -> Vec<String> {
|
||||
}
|
||||
|
||||
/// The sheet's PivotTables: those modelled, and those kept unchanged for saving (their source is
|
||||
/// in another workbook).
|
||||
/// in another workbook, a data connection or the Data Model).
|
||||
fn pivot_count(s: &Sheet) -> usize {
|
||||
let kept = s.preserved.as_deref().map_or(0, |p| p.rels.iter().filter(|r| !r.external && r.rel_type.ends_with("/pivotTable")).count());
|
||||
s.pivots.len() + kept
|
||||
|
||||
@@ -6,11 +6,14 @@
|
||||
//! their `<externalReferences>`, data connections, XML maps) and each sheet (query tables, cells
|
||||
//! mapped to XML elements, form controls, ActiveX controls, OLE objects, the sheet background and
|
||||
//! printer settings, with the sheet's `<picture>`, `<oleObjects>` and `<controls>` XML, the `r:id`
|
||||
//! of `<pageSetup>` and the legacy VML shapes those controls need). PivotTables whose source is in
|
||||
//! another workbook are kept too: the PivotTable parts with their sheet, the cache definition and
|
||||
//! records parts (with the cache's link to the other workbook's path) with the workbook and its
|
||||
//! `<pivotCache>` entry, its `cacheId` unchanged. The workbook also keeps its
|
||||
//! `<fileVersion>` and the calcFeatures extension, which Excel needs to trust the saved values.
|
||||
//! of `<pageSetup>` and the legacy VML shapes those controls need). The workbook's Data Model
|
||||
//! (`xl/model/item.data`) is kept with its data connections. PivotTables whose source is in
|
||||
//! another workbook, a data connection or the Data Model are kept too: the PivotTable parts with
|
||||
//! their sheet, the cache definition and records parts (with the cache's link to the other
|
||||
//! workbook's path) with the 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.
|
||||
//!
|
||||
//! 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:
|
||||
@@ -41,7 +44,7 @@ use quick_xml::{Reader, Writer};
|
||||
|
||||
use crate::IoError;
|
||||
use crate::package::{self, normalize};
|
||||
use crate::pivot::{CT_PIVOT_CACHE_DEF, CT_PIVOT_TABLE, ExternalPivot};
|
||||
use crate::pivot::{CT_PIVOT_CACHE_DEF, CT_PIVOT_TABLE, ExternalPivot, KeptSource};
|
||||
use crate::read::Ctx;
|
||||
use crate::write::{NS_REL, Out, Rels, XML_DECL};
|
||||
use crate::xml::{self, esc_attr};
|
||||
@@ -103,6 +106,8 @@ const SHEET_SLOTS: &[&str] = &["picture", "oleObjects", "controls"];
|
||||
const PIVOT_TABLE_GRAPH: &[&str] = &["pivotTable", "pivotCacheDefinition"];
|
||||
/// Rewritten kinds a kept pivot cache reaches.
|
||||
const PIVOT_CACHE_GRAPH: &[&str] = &["pivotCacheDefinition", "pivotCacheRecords"];
|
||||
/// The workbook's Data Model part (Power Pivot), kept byte for byte when its connections are.
|
||||
const DATA_MODEL_GRAPH: &[&str] = &["powerPivotData"];
|
||||
|
||||
/// Relationship kinds GridCraft reads and rewrites, or that depend on content it rewrites:
|
||||
/// kept content whose graph reaches one of them is dropped.
|
||||
@@ -168,6 +173,7 @@ const OWN_DIRS: &[&str] = &[
|
||||
"xl/activex/",
|
||||
"xl/webextensions/",
|
||||
"xl/printersettings/",
|
||||
"xl/model/",
|
||||
];
|
||||
|
||||
fn kind(rel_type: &str) -> &str {
|
||||
@@ -242,8 +248,8 @@ pub struct KeptReader {
|
||||
budget: usize,
|
||||
parts_left: usize,
|
||||
/// Cache definition parts of the PivotTables kept with their sheets (source in another
|
||||
/// workbook), kept with the workbook.
|
||||
pivot_caches: Vec<String>,
|
||||
/// workbook, a data connection or the Data Model), kept with the workbook.
|
||||
pivot_caches: Vec<(String, KeptSource)>,
|
||||
}
|
||||
|
||||
impl KeptReader {
|
||||
@@ -409,6 +415,20 @@ impl KeptReader {
|
||||
cx.warn(format!("{} part {} was dropped: {why}", kind(&r.rel_type), r.target));
|
||||
}
|
||||
}
|
||||
// The Data Model: its tables are loaded through the workbook's connections, so it is kept
|
||||
// only with them.
|
||||
let connections = p.rels.iter().any(|r| is_kind(r, &["connections"]));
|
||||
for r in wb_rels.iter().filter(|r| !r.external && is_kind(r, DATA_MODEL_GRAPH)).take(1) {
|
||||
let kept = if connections {
|
||||
self.keep_through(cx, &mut p, std::slice::from_ref(r), &mut seen, DATA_MODEL_GRAPH)
|
||||
} else {
|
||||
Err("the workbook's data connections were not kept".into())
|
||||
};
|
||||
match kept {
|
||||
Ok(()) => cx.warn("the workbook's Data Model is kept for saving as it is; it can't be viewed, edited or refreshed here"),
|
||||
Err(why) => cx.warn(format!("the workbook's Data Model was dropped: {why}")),
|
||||
}
|
||||
}
|
||||
// Chart sheets: the sheet entry (name, state, position) plus the chart sheet part and the
|
||||
// drawing, chart, style and colour parts behind it.
|
||||
for (worksheets, se) in chart_sheet_entries(wb_xml, &wb_rels, file_to_model) {
|
||||
@@ -484,14 +504,33 @@ impl KeptReader {
|
||||
/// 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>) {
|
||||
let caches = std::mem::take(&mut self.pivot_caches);
|
||||
for cache in &caches {
|
||||
// A cache names its connection by id in the kept connections part, and a Data Model cache
|
||||
// reads the kept model: without them Excel refuses the file or can't refresh it.
|
||||
let connections = p.rels.iter().any(|r| is_kind(r, &["connections"]));
|
||||
let model = p.rels.iter().any(|r| is_kind(r, DATA_MODEL_GRAPH));
|
||||
let (mut no_connections, mut no_model) = (0usize, 0usize);
|
||||
for (cache, source) in &caches {
|
||||
match source {
|
||||
KeptSource::Connection | KeptSource::DataModel if !connections => {
|
||||
no_connections += 1;
|
||||
continue;
|
||||
}
|
||||
KeptSource::DataModel if !model => {
|
||||
no_model += 1;
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let entry = wb_xml.child("pivotCaches").into_iter().flat_map(|c| c.kids("pivotCache")).find_map(|c| {
|
||||
let id = c.attr_u32("cacheId")?;
|
||||
let r = wb_rels.iter().find(|r| Some(r.id.as_str()) == c.attr("id") && !r.external && is_kind(r, &["pivotCacheDefinition"]))?;
|
||||
(normalize(&r.target) == normalize(cache)).then(|| (id, r.clone()))
|
||||
});
|
||||
let Some((id, r)) = entry else {
|
||||
cx.warn(format!("the cache {cache} of a PivotTable on another workbook is not in the workbook's list; the PivotTable was dropped"));
|
||||
cx.warn(format!(
|
||||
"the cache {cache} of a PivotTable on {} is not in the workbook's list; the PivotTable was dropped",
|
||||
source.describe()
|
||||
));
|
||||
continue;
|
||||
};
|
||||
match self.keep_through(cx, p, std::slice::from_ref(&r), seen, PIVOT_CACHE_GRAPH) {
|
||||
@@ -499,9 +538,19 @@ impl KeptReader {
|
||||
slot: "pivotCache".into(),
|
||||
xml: format!("<pivotCache xmlns:r=\"{NS_REL}\" cacheId=\"{id}\" r:id=\"{}\"/>", esc_attr(&r.id)),
|
||||
}),
|
||||
Err(why) => cx.warn(format!("the cache of a PivotTable on another workbook was dropped with its PivotTables: {why}")),
|
||||
Err(why) => cx.warn(format!("the cache of a PivotTable on {} was dropped with its PivotTables: {why}", source.describe())),
|
||||
}
|
||||
}
|
||||
if no_connections > 0 {
|
||||
cx.warn(format!(
|
||||
"{no_connections} PivotTable cache(s) on a data connection or the Data Model were dropped with their PivotTables (kept as plain cells): the workbook's data connections were not kept"
|
||||
));
|
||||
}
|
||||
if no_model > 0 {
|
||||
cx.warn(format!(
|
||||
"{no_model} PivotTable cache(s) on the workbook's Data Model were dropped with their PivotTables (kept as plain cells): the Data Model was not kept"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Sheet-level content of the sheet part `part`; `pivots` are its PivotTables whose source is
|
||||
@@ -509,7 +558,9 @@ impl KeptReader {
|
||||
pub fn sheet(&mut self, cx: &mut Ctx<'_>, part: &str, name: &str, pivots: &[ExternalPivot]) -> Option<Arc<Preserved>> {
|
||||
if !self.on {
|
||||
if !pivots.is_empty() {
|
||||
cx.warn(format!("sheet \"{name}\": PivotTables on another workbook are not kept on save in this file"));
|
||||
cx.warn(format!(
|
||||
"sheet \"{name}\": PivotTables on another workbook, a data connection or the Data Model are not kept on save in this file"
|
||||
));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
@@ -539,11 +590,11 @@ impl KeptReader {
|
||||
Ok(()) => {
|
||||
scoped.remove(&normalize(&ep.cache_part));
|
||||
seen = scoped;
|
||||
if !self.pivot_caches.iter().any(|c| normalize(c) == normalize(&ep.cache_part)) {
|
||||
self.pivot_caches.push(ep.cache_part.clone());
|
||||
if !self.pivot_caches.iter().any(|(c, _)| normalize(c) == normalize(&ep.cache_part)) {
|
||||
self.pivot_caches.push((ep.cache_part.clone(), ep.source));
|
||||
}
|
||||
}
|
||||
Err(why) => cx.warn(format!("sheet \"{name}\": a PivotTable on another workbook was dropped: {why}")),
|
||||
Err(why) => cx.warn(format!("sheet \"{name}\": a PivotTable on {} was dropped: {why}", ep.source.describe())),
|
||||
}
|
||||
}
|
||||
(!p.is_empty()).then(|| Arc::new(p))
|
||||
|
||||
+76
-17
@@ -12,9 +12,12 @@
|
||||
//! (OLAP sources, calculated fields, numeric grouping…) becomes a warning.
|
||||
//!
|
||||
//! A PivotTable whose source is a range or name in another workbook (its cache's
|
||||
//! `worksheetSource` has an `r:id` to an `externalLinkPath` relationship) is not modelled:
|
||||
//! GridCraft never opens the other workbook, so it couldn't refresh it. [`read_pivots`] reports
|
||||
//! it instead, and `passthrough` keeps its PivotTable, cache and records parts unchanged.
|
||||
//! `worksheetSource` has an `r:id` to an `externalLinkPath` relationship), a data connection or
|
||||
//! the workbook's Data Model (`cacheSource type="external"` with a `connectionId` in
|
||||
//! `xl/connections.xml`) is not modelled: GridCraft never opens the other workbook, runs the
|
||||
//! connection or loads the model, so it couldn't refresh it. [`read_pivots`] reports it instead,
|
||||
//! and `passthrough` keeps its PivotTable, cache and records parts unchanged (with the Data Model
|
||||
//! for a PivotTable on the model).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write as _;
|
||||
@@ -1079,17 +1082,40 @@ impl FieldIn {
|
||||
struct CacheIn {
|
||||
source: String,
|
||||
fields: Vec<FieldIn>,
|
||||
/// The source is in another workbook: the PivotTables on this cache are kept, not modelled.
|
||||
external: bool,
|
||||
/// Set when the PivotTables on this cache are kept as they are, not modelled.
|
||||
kept: Option<KeptSource>,
|
||||
}
|
||||
|
||||
/// A PivotTable whose source is in another workbook, kept unchanged for saving.
|
||||
/// Where the data of a PivotTable GridCraft keeps unchanged (doesn't model) comes from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum KeptSource {
|
||||
/// A range or name in another workbook.
|
||||
OtherWorkbook,
|
||||
/// A data connection of the workbook (`xl/connections.xml`) other than its Data Model.
|
||||
Connection,
|
||||
/// The workbook's Data Model (Power Pivot), through its model connection.
|
||||
DataModel,
|
||||
}
|
||||
|
||||
impl KeptSource {
|
||||
pub(crate) fn describe(self) -> &'static str {
|
||||
match self {
|
||||
KeptSource::OtherWorkbook => "another workbook",
|
||||
KeptSource::Connection => "a data connection",
|
||||
KeptSource::DataModel => "the workbook's Data Model",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A PivotTable GridCraft doesn't model (its data is in another workbook, a data connection or
|
||||
/// the Data Model), kept unchanged for saving.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ExternalPivot {
|
||||
/// The id of the sheet's relationship to the PivotTable part.
|
||||
pub rel_id: String,
|
||||
/// The pivot cache definition part it uses.
|
||||
pub cache_part: String,
|
||||
pub source: KeptSource,
|
||||
}
|
||||
|
||||
/// The PivotTables of a sheet: those modelled, and those kept as they are.
|
||||
@@ -1105,6 +1131,8 @@ pub struct CachesIn {
|
||||
by_id: HashMap<u32, String>,
|
||||
parsed: HashMap<String, Option<CacheIn>>,
|
||||
next_id: u32,
|
||||
/// The workbook's data connections (`connectionId` → whether it is the Data Model's).
|
||||
connections: HashMap<u32, bool>,
|
||||
}
|
||||
|
||||
impl CachesIn {
|
||||
@@ -1119,10 +1147,28 @@ impl CachesIn {
|
||||
}
|
||||
}
|
||||
}
|
||||
CachesIn { by_id, parsed: HashMap::new(), next_id: 1 }
|
||||
CachesIn { by_id, parsed: HashMap::new(), next_id: 1, connections: HashMap::new() }
|
||||
}
|
||||
|
||||
/// Reads the ids of the workbook's data connections (`xl/connections.xml`), which caches on a
|
||||
/// connection or the Data Model name by `connectionId`.
|
||||
pub fn read_connections(&mut self, cx: &mut Ctx<'_>, wb_rels: &[crate::package::Rel]) {
|
||||
let Some(r) = wb_rels.iter().find(|r| r.kind == "connections" && !r.external) else { return };
|
||||
let Ok(Some(x)) = cx.optional_xml(&r.target) else { return };
|
||||
for c in x.kids("connection").take(MAX_CONNECTIONS) {
|
||||
let Some(id) = c.attr_u32("id") else { continue };
|
||||
// The model connection: `<x15:connection model="1">` in its extension list (Excel
|
||||
// also gives it `<dbPr command="Model">`).
|
||||
let x15_model = c.child("extLst").is_some_and(|l| l.kids("ext").filter_map(|e| e.child("connection")).any(|x| x.flag("model", false)));
|
||||
let dbpr_model = c.attr("type") == Some("5") && c.child("dbPr").and_then(|d| d.attr("command")) == Some("Model");
|
||||
self.connections.insert(id, x15_model || dbpr_model);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Most data connections read from `xl/connections.xml`.
|
||||
const MAX_CONNECTIONS: usize = 100_000;
|
||||
|
||||
fn item_label_el(e: &El, sys: DateSystem) -> String {
|
||||
let v = e.attr("v").unwrap_or("");
|
||||
match e.name.as_str() {
|
||||
@@ -1134,7 +1180,7 @@ fn item_label_el(e: &El, sys: DateSystem) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option<CacheIn> {
|
||||
fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str, connections: &HashMap<u32, bool>) -> Option<CacheIn> {
|
||||
let x = cx.optional_xml(part).ok().flatten()?;
|
||||
if x.name != "pivotCacheDefinition" {
|
||||
cx.warn(format!("{part} is not a pivot cache definition; its PivotTable was kept as plain cells"));
|
||||
@@ -1142,8 +1188,19 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option<CacheIn>
|
||||
}
|
||||
let src = x.child("cacheSource");
|
||||
let ty = src.and_then(|s| s.attr("type")).unwrap_or("worksheet");
|
||||
// A data connection or the Data Model (OLAP): kept as it is when the workbook has that
|
||||
// connection.
|
||||
if ty == "external" {
|
||||
let model = src.and_then(|s| s.attr_u32("connectionId")).and_then(|id| connections.get(&id).copied());
|
||||
let Some(model) = model else {
|
||||
cx.warn("a PivotTable's data connection is not in the workbook; kept as plain cells");
|
||||
return None;
|
||||
};
|
||||
let kept = if model { KeptSource::DataModel } else { KeptSource::Connection };
|
||||
return Some(CacheIn { source: String::new(), fields: vec![], kept: Some(kept) });
|
||||
}
|
||||
if ty != "worksheet" {
|
||||
cx.warn(format!("PivotTables with a {ty} data source are not supported; kept as plain cells"));
|
||||
cx.warn(format!("PivotTables with a data source of type \"{ty}\" are not supported; kept as plain cells"));
|
||||
return None;
|
||||
}
|
||||
let ws = src.and_then(|s| s.child("worksheetSource"));
|
||||
@@ -1154,7 +1211,7 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option<CacheIn>
|
||||
cx.warn("a PivotTable's source is in another workbook that its cache doesn't name; kept as plain cells");
|
||||
return None;
|
||||
}
|
||||
return Some(CacheIn { source: String::new(), fields: vec![], external: true });
|
||||
return Some(CacheIn { source: String::new(), fields: vec![], kept: Some(KeptSource::OtherWorkbook) });
|
||||
}
|
||||
let source = match ws {
|
||||
Some(w) if w.attr("name").is_some_and(|n| !n.trim().is_empty()) => w.attr("name").unwrap_or("").trim().to_string(),
|
||||
@@ -1202,11 +1259,12 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option<CacheIn>
|
||||
cx.warn("a PivotTable's cache has no fields; kept as plain cells");
|
||||
return None;
|
||||
}
|
||||
Some(CacheIn { source, fields, external: false })
|
||||
Some(CacheIn { source, fields, kept: None })
|
||||
}
|
||||
|
||||
/// Reads the PivotTables related to a worksheet part. Those whose source is in another workbook
|
||||
/// are listed in [`SheetPivots::external`] (with a warning), not modelled.
|
||||
/// Reads the PivotTables related to a worksheet part. Those whose source is in another workbook,
|
||||
/// a data connection or the Data Model are listed in [`SheetPivots::external`] (with a warning),
|
||||
/// not modelled.
|
||||
pub fn read_pivots(cx: &mut Ctx<'_>, caches: &mut CachesIn, sheet_part: &str, sheet_name: &str) -> Result<SheetPivots, IoError> {
|
||||
let rels = cx.pkg.rels(sheet_part)?;
|
||||
let mut out = SheetPivots::default();
|
||||
@@ -1230,18 +1288,19 @@ pub fn read_pivots(cx: &mut Ctx<'_>, caches: &mut CachesIn, sheet_part: &str, sh
|
||||
let cache = match caches.parsed.get(&cache_part) {
|
||||
Some(c) => c.clone(),
|
||||
None => {
|
||||
let c = read_cache(cx, &cache_part, sheet_name);
|
||||
let c = read_cache(cx, &cache_part, sheet_name, &caches.connections);
|
||||
caches.parsed.insert(cache_part.clone(), c.clone());
|
||||
c
|
||||
}
|
||||
};
|
||||
let Some(cache) = cache else { continue };
|
||||
if cache.external {
|
||||
if let Some(source) = cache.kept {
|
||||
let name = x.attr("name").unwrap_or("");
|
||||
let from = source.describe();
|
||||
cx.warn(format!(
|
||||
"PivotTable \"{name}\" on sheet \"{sheet_name}\" gets its data from another workbook: it is kept for saving as it is, but can't be edited or refreshed here"
|
||||
"PivotTable \"{name}\" on sheet \"{sheet_name}\" gets its data from {from}: it is kept for saving as it is, but can't be edited or refreshed here"
|
||||
));
|
||||
out.external.push(ExternalPivot { rel_id: rel.id.clone(), cache_part });
|
||||
out.external.push(ExternalPivot { rel_id: rel.id.clone(), cache_part, source });
|
||||
continue;
|
||||
}
|
||||
if let Some(pt) = read_table(cx, &x, &cache, caches.next_id) {
|
||||
|
||||
@@ -199,6 +199,7 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> {
|
||||
// Sheets. `file_to_model[i]` maps the i-th <sheet> to a model sheet index.
|
||||
let mut file_to_model: Vec<Option<usize>> = vec![];
|
||||
let mut pivot_caches = crate::pivot::CachesIn::new(&wb_xml, &wb_rels);
|
||||
pivot_caches.read_connections(&mut cx, &wb_rels);
|
||||
let sheet_els: Vec<El> = wb_xml.child("sheets").map(|s| s.kids("sheet").cloned().collect()).unwrap_or_default();
|
||||
for (i, se) in sheet_els.iter().enumerate() {
|
||||
let name = se.attr("name").unwrap_or("").to_string();
|
||||
|
||||
@@ -1067,3 +1067,259 @@ fn a_kept_pivot_table_whose_cache_is_not_listed_is_dropped() {
|
||||
assert!(written_pivot_tables(&u, "Report").is_empty());
|
||||
assert!(written_pivot_caches(&u).is_empty());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- PivotTables on a data connection or the Data Model
|
||||
|
||||
/// Bytes standing in for the Data Model (Excel's `xl/model/item.data`).
|
||||
const MODEL_DATA: &[u8] = b"\x00\x01model bytes, not really a model\xFE\xFF";
|
||||
/// A larger stand-in, for running out of room to keep it.
|
||||
static BIG_MODEL: [u8; 64 * 1024] = [7; 64 * 1024];
|
||||
const CT_MODEL: &str = "application/vnd.openxmlformats-officedocument.model+data";
|
||||
/// The model connection (id 1, as Excel writes it), a plain OLE DB connection (id 2) and a
|
||||
/// worksheet connection loading a range into the model (id 3).
|
||||
const MODEL_CONNECTIONS: &str = r#"<?xml version="1.0"?><connections xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><connection id="1" keepAlive="1" name="ThisWorkbookDataModel" description="Data Model" type="5" refreshedVersion="8" minRefreshableVersion="5"><dbPr connection="Data Model Connection" command="Model" commandType="1"/><olapPr sendLocale="1" rowDrillCount="1000"/><extLst><ext uri="{DE250136-89BD-433C-8126-D09CA5730AF9}" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"><x15:connection id="" model="1"/></ext></extLst></connection><connection id="2" name="Source" type="5" refreshedVersion="8"><dbPr connection="Provider=Example;Data Source=source.xlsx" command="Data$" commandType="3"/></connection><connection id="3" name="WorksheetConnection_T" type="102" refreshedVersion="8" minRefreshableVersion="5"><extLst><ext uri="{DE250136-89BD-433C-8126-D09CA5730AF9}" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"><x15:connection id="T"><x15:rangePr sourceName="_xlcn.WorksheetConnection_T"/></x15:connection></ext></extLst></connection></connections>"#;
|
||||
const CONN_RECORDS: &str = r#"<?xml version="1.0"?><pivotCacheRecords xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="1"><r><x v="0"/><n v="6"/></r></pivotCacheRecords>"#;
|
||||
|
||||
/// An OLAP cache on the Data Model (no records: `saveData="0"`), on connection `id`.
|
||||
fn model_cache(id: u32) -> String {
|
||||
format!(
|
||||
r#"<?xml version="1.0"?><pivotCacheDefinition xmlns="{NS_MAIN}" xmlns:r="{NS_R}" saveData="0" createdVersion="6" refreshedVersion="8" minRefreshableVersion="3" recordCount="0"><cacheSource type="external" connectionId="{id}"/><cacheFields count="2"><cacheField name="[T].[K].[K]" caption="K" numFmtId="0" level="1"><sharedItems count="1"><s v="x"/></sharedItems></cacheField><cacheField name="[Measures].[Sum of V]" caption="Sum of V" numFmtId="0" hierarchy="1" level="32767"/></cacheFields><cacheHierarchies count="2"><cacheHierarchy uniqueName="[T].[K]" caption="K" attribute="1" defaultMemberUniqueName="[T].[K].[All]" allUniqueName="[T].[K].[All]" dimensionUniqueName="[T]" displayFolder="" count="2" memberValueDatatype="130" unbalanced="0"><fieldsUsage count="2"><fieldUsage x="-1"/><fieldUsage x="0"/></fieldsUsage></cacheHierarchy><cacheHierarchy uniqueName="[Measures].[Sum of V]" caption="Sum of V" measure="1" displayFolder="" measureGroup="T" count="0" oneField="1" hidden="1"><fieldsUsage count="1"><fieldUsage x="1"/></fieldsUsage></cacheHierarchy></cacheHierarchies><kpis count="0"/><dimensions count="2"><dimension measure="1" name="Measures" uniqueName="[Measures]" caption="Measures"/><dimension name="T" uniqueName="[T]" caption="T"/></dimensions><measureGroups count="1"><measureGroup name="T" caption="T"/></measureGroups><maps count="1"><map measureGroup="0" dimension="1"/></maps></pivotCacheDefinition>"#
|
||||
)
|
||||
}
|
||||
|
||||
/// A relational cache on connection `id`, with records.
|
||||
fn conn_cache(id: u32) -> String {
|
||||
format!(
|
||||
r#"<?xml version="1.0"?><pivotCacheDefinition xmlns="{NS_MAIN}" xmlns:r="{NS_R}" r:id="rId1" refreshedVersion="8" recordCount="1"><cacheSource type="external" connectionId="{id}"/><cacheFields count="2"><cacheField name="K" numFmtId="0"><sharedItems count="1"><s v="x"/></sharedItems></cacheField><cacheField name="V" numFmtId="0"><sharedItems containsNumber="1"/></cacheField></cacheFields></pivotCacheDefinition>"#
|
||||
)
|
||||
}
|
||||
|
||||
/// What a data-connection test package holds.
|
||||
#[derive(Clone, Copy)]
|
||||
struct ConnPkg {
|
||||
/// The Data Model part and its workbook relationship.
|
||||
model_part: bool,
|
||||
/// The larger model stand-in.
|
||||
big_model: bool,
|
||||
/// `xl/connections.xml` and its workbook relationship.
|
||||
connections: bool,
|
||||
/// The connections part has a relationship to content GridCraft rewrites (so it can't be kept).
|
||||
connections_blocked: bool,
|
||||
/// The connection the Data Model cache names.
|
||||
model_connection: u32,
|
||||
}
|
||||
|
||||
const CONN_PKG: ConnPkg = ConnPkg { model_part: true, big_model: false, connections: true, connections_blocked: false, model_connection: 1 };
|
||||
|
||||
/// Sheet "Report" with a PivotTable on the Data Model (cache 3) and sheet "More" with one on the
|
||||
/// plain connection (cache 4, with records), plus the hidden name a worksheet connection uses.
|
||||
fn conn_pivot_package(o: ConnPkg) -> Vec<u8> {
|
||||
let workbook = format!(
|
||||
r#"<?xml version="1.0"?><workbook xmlns="{NS_MAIN}" xmlns:r="{NS_R}"><sheets><sheet name="Report" sheetId="1" r:id="rId1"/><sheet name="More" sheetId="2" r:id="rId2"/></sheets><definedNames><definedName name="_xlcn.WorksheetConnection_T" hidden="1">More!$D$1:$E$2</definedName></definedNames><pivotCaches><pivotCache cacheId="3" r:id="rId3"/><pivotCache cacheId="4" r:id="rId7"/></pivotCaches></workbook>"#
|
||||
);
|
||||
let ct = |part: &str, ty: &str| format!(r#"<Override PartName="/{part}" ContentType="{CT_PREFIX}.spreadsheetml.{ty}+xml"/>"#);
|
||||
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"/><Default Extension="data" ContentType="{CT_MODEL}"/>{}{}{}{}{}{}{}{}{}{}</Types>"#,
|
||||
ct("xl/workbook.xml", "sheet.main"),
|
||||
ct("xl/worksheets/sheet1.xml", "worksheet"),
|
||||
ct("xl/worksheets/sheet2.xml", "worksheet"),
|
||||
ct("xl/styles.xml", "styles"),
|
||||
ct("xl/connections.xml", "connections"),
|
||||
ct("xl/pivotTables/pivotTable1.xml", "pivotTable"),
|
||||
ct("xl/pivotTables/pivotTable2.xml", "pivotTable"),
|
||||
ct("xl/pivotCache/pivotCacheDefinition1.xml", "pivotCacheDefinition"),
|
||||
ct("xl/pivotCache/pivotCacheDefinition2.xml", "pivotCacheDefinition"),
|
||||
ct("xl/pivotCache/pivotCacheRecords2.xml", "pivotCacheRecords"),
|
||||
);
|
||||
let sheet = |v: &str| {
|
||||
format!(
|
||||
r#"<?xml version="1.0"?><worksheet xmlns="{NS_MAIN}"><sheetData><row r="4"><c r="A4" t="inlineStr"><is><t>x</t></is></c><c r="B4"><v>{v}</v></c></row></sheetData></worksheet>"#
|
||||
)
|
||||
};
|
||||
let (s1, s2) = (sheet("5"), sheet("6"));
|
||||
let (c1, c2) = (model_cache(o.model_connection), conn_cache(2));
|
||||
let (t1, t2) = (ext_table("OnModel", 3), ext_table("OnConnection", 4));
|
||||
let mut wb_rels = vec![
|
||||
("rId1", "worksheet", "worksheets/sheet1.xml"),
|
||||
("rId2", "worksheet", "worksheets/sheet2.xml"),
|
||||
("rId3", "pivotCacheDefinition", "pivotCache/pivotCacheDefinition1.xml"),
|
||||
("rId4", "styles", "styles.xml"),
|
||||
("rId7", "pivotCacheDefinition", "pivotCache/pivotCacheDefinition2.xml"),
|
||||
];
|
||||
if o.connections {
|
||||
wb_rels.push(("rId5", "connections", "connections.xml"));
|
||||
}
|
||||
if o.model_part {
|
||||
wb_rels.push(("rId6", "powerPivotData", "model/item.data"));
|
||||
}
|
||||
let wb_rels = rels(&wb_rels);
|
||||
let t1_rels = rels(&[("rId1", "pivotCacheDefinition", "../pivotCache/pivotCacheDefinition1.xml")]);
|
||||
let t2_rels = rels(&[("rId1", "pivotCacheDefinition", "../pivotCache/pivotCacheDefinition2.xml")]);
|
||||
let c2_rels = rels(&[("rId1", "pivotCacheRecords", "pivotCacheRecords2.xml")]);
|
||||
let s1_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable1.xml")]);
|
||||
let s2_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable2.xml")]);
|
||||
let conn_rels = rels(&[("rId1", "worksheet", "worksheets/sheet1.xml")]);
|
||||
let mut parts: Vec<(&str, &[u8])> = vec![
|
||||
("[Content_Types].xml", content_types.as_bytes()),
|
||||
("_rels/.rels", super::ROOT_RELS.as_bytes()),
|
||||
("xl/workbook.xml", workbook.as_bytes()),
|
||||
("xl/_rels/workbook.xml.rels", wb_rels.as_bytes()),
|
||||
("xl/styles.xml", EXT_STYLES.as_bytes()),
|
||||
("xl/worksheets/sheet1.xml", s1.as_bytes()),
|
||||
("xl/worksheets/sheet2.xml", s2.as_bytes()),
|
||||
("xl/worksheets/_rels/sheet1.xml.rels", s1_rels.as_bytes()),
|
||||
("xl/worksheets/_rels/sheet2.xml.rels", s2_rels.as_bytes()),
|
||||
("xl/pivotTables/pivotTable1.xml", t1.as_bytes()),
|
||||
("xl/pivotTables/_rels/pivotTable1.xml.rels", t1_rels.as_bytes()),
|
||||
("xl/pivotTables/pivotTable2.xml", t2.as_bytes()),
|
||||
("xl/pivotTables/_rels/pivotTable2.xml.rels", t2_rels.as_bytes()),
|
||||
("xl/pivotCache/pivotCacheDefinition1.xml", c1.as_bytes()),
|
||||
("xl/pivotCache/pivotCacheDefinition2.xml", c2.as_bytes()),
|
||||
("xl/pivotCache/_rels/pivotCacheDefinition2.xml.rels", c2_rels.as_bytes()),
|
||||
("xl/pivotCache/pivotCacheRecords2.xml", CONN_RECORDS.as_bytes()),
|
||||
];
|
||||
if o.connections {
|
||||
parts.push(("xl/connections.xml", MODEL_CONNECTIONS.as_bytes()));
|
||||
}
|
||||
if o.connections_blocked {
|
||||
parts.push(("xl/_rels/connections.xml.rels", conn_rels.as_bytes()));
|
||||
}
|
||||
if o.model_part {
|
||||
parts.push(("xl/model/item.data", if o.big_model { &BIG_MODEL[..] } else { MODEL_DATA }));
|
||||
}
|
||||
make_zip(&parts)
|
||||
}
|
||||
|
||||
/// The content type a written package gives a part.
|
||||
fn content_type_of(u: &Unpacked, part: &str) -> String {
|
||||
let types = xml::parse(u.parts.get("[Content_Types].xml").unwrap()).unwrap();
|
||||
if let Some(o) = types.kids("Override").find(|o| normalize(o.attr("PartName").unwrap()) == normalize(part)) {
|
||||
return o.attr("ContentType").unwrap().to_string();
|
||||
}
|
||||
let ext = part.rsplit('.').next().unwrap().to_ascii_lowercase();
|
||||
types.kids("Default").find(|d| d.attr("Extension").unwrap().eq_ignore_ascii_case(&ext)).unwrap().attr("ContentType").unwrap().to_string()
|
||||
}
|
||||
|
||||
/// Bytes kept by a read workbook.
|
||||
fn kept_bytes(wb: &gridcraft_model::Workbook) -> usize {
|
||||
wb.preserved.as_ref().map_or(0, |p| p.byte_len()) + wb.sheets.iter().filter_map(|s| s.preserved.as_ref()).map(|p| p.byte_len()).sum::<usize>()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pivot_tables_on_the_data_model_and_a_connection_survive_a_save() {
|
||||
let (wb, rep) = read_xlsx(&conn_pivot_package(CONN_PKG)).unwrap();
|
||||
assert!(wb.sheets.iter().all(|s| s.pivots.is_empty()), "not modelled: GridCraft can't refresh them");
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("OnModel") && w.contains("Data Model")), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("OnConnection") && w.contains("a data connection")), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("Data Model is kept")), "{:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("dropped") || w.contains("plain cells")), "{:?}", rep.warnings);
|
||||
// Twice: what the first save kept is read back and kept again.
|
||||
let first = write_xlsx(&wb).unwrap();
|
||||
let (again, rep2) = read_xlsx(&first).unwrap();
|
||||
assert!(!rep2.warnings.iter().any(|w| w.contains("dropped") || w.contains("plain cells")), "{:?}", rep2.warnings);
|
||||
for saved in [first, write_xlsx(&again).unwrap()] {
|
||||
let u = Unpacked::new(&saved);
|
||||
u.assert_valid();
|
||||
// The Data Model: same bytes, name and content type, related from the workbook.
|
||||
assert_eq!(u.parts.get("xl/model/item.data").map(Vec::as_slice), Some(MODEL_DATA));
|
||||
assert_eq!(content_type_of(&u, "xl/model/item.data"), CT_MODEL);
|
||||
let wb_rels = u.rels("xl/workbook.xml");
|
||||
assert!(wb_rels.iter().any(|r| r.1.ends_with("/powerPivotData") && r.2 == "xl/model/item.data"), "{wb_rels:?}");
|
||||
// The connections the caches name by id, and the hidden name a worksheet connection uses.
|
||||
let conn = wb_rels.iter().find(|r| r.1.ends_with("/connections")).unwrap();
|
||||
assert_eq!(u.text(&conn.2), MODEL_CONNECTIONS);
|
||||
assert!(u.text("xl/workbook.xml").contains("_xlcn.WorksheetConnection_T"));
|
||||
let caches = written_pivot_caches(&u);
|
||||
assert_eq!(caches.len(), 2, "{caches:?}");
|
||||
let cache = |id: &str| caches.iter().find(|c| c.0 == id).unwrap_or_else(|| panic!("{caches:?}")).1.clone();
|
||||
assert_eq!(u.text(&cache("3")), model_cache(1));
|
||||
assert!(u.rels(&cache("3")).is_empty());
|
||||
assert_eq!(u.text(&cache("4")), conn_cache(2));
|
||||
let records = u.rels(&cache("4")).into_iter().find(|r| r.1.ends_with("/pivotCacheRecords")).unwrap();
|
||||
assert_eq!(u.text(&records.2), CONN_RECORDS);
|
||||
for (sheet, name, id) in [("Report", "OnModel", "3"), ("More", "OnConnection", "4")] {
|
||||
let t = written_pivot_tables(&u, sheet);
|
||||
assert_eq!(t.len(), 1, "{sheet}");
|
||||
assert_eq!(u.rels(&t[0])[0].2, cache(id), "{sheet}");
|
||||
let x = u.text(&t[0]);
|
||||
assert!(x.contains(&format!(r#"name="{name}" cacheId="{id}""#)), "{x}");
|
||||
let (color, code) = written_style(&u, &attr_of(&x, "format", "dxfId"), &attr_of(&x, "dataField", "numFmtId"));
|
||||
assert_eq!((color.as_str(), code.as_str()), ("FF0000FF", "0.0%"), "{x}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_data_model_is_kept_without_pivot_tables() {
|
||||
let (mut wb, _) = read_xlsx(&conn_pivot_package(CONN_PKG)).unwrap();
|
||||
wb.sheets.iter_mut().for_each(|s| Arc::make_mut(s).preserved = None);
|
||||
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
|
||||
u.assert_valid();
|
||||
assert_eq!(u.parts.get("xl/model/item.data").map(Vec::as_slice), Some(MODEL_DATA));
|
||||
// No kept table uses the caches any more: they go.
|
||||
assert!(written_pivot_caches(&u).is_empty());
|
||||
assert!(u.find(model_cache(1).as_bytes()).is_empty() && u.find(CONN_RECORDS.as_bytes()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_model_pivot_tables_without_the_model_are_kept_as_plain_cells() {
|
||||
// No model part, or no room left to keep it: the PivotTable on the model couldn't be
|
||||
// refreshed and is dropped (its cells stay); the one on a plain connection is kept.
|
||||
for too_large in [false, true] {
|
||||
let pkg = ConnPkg { model_part: too_large, big_model: too_large, ..CONN_PKG };
|
||||
let src = conn_pivot_package(pkg);
|
||||
let (wb, rep) = if too_large {
|
||||
// Room for everything but the model: the caches are kept after it.
|
||||
let all = kept_bytes(&read_xlsx(&src).unwrap().0);
|
||||
crate::passthrough::KEPT_TOTAL_FOR_TEST.with(|c| c.set(all - BIG_MODEL.len()));
|
||||
let read = read_xlsx(&src);
|
||||
crate::passthrough::KEPT_TOTAL_FOR_TEST.with(|c| c.set(crate::passthrough::MAX_KEPT_TOTAL));
|
||||
let r = read.unwrap();
|
||||
assert!(r.1.warnings.iter().any(|w| w.contains("Data Model was dropped") && w.contains("too large")), "{:?}", r.1.warnings);
|
||||
r
|
||||
} else {
|
||||
read_xlsx(&src).unwrap()
|
||||
};
|
||||
let w = &rep.warnings;
|
||||
assert!(
|
||||
w.iter().any(|w| w.contains("1 PivotTable cache(s) on the workbook's Data Model were dropped") && w.contains("plain cells")),
|
||||
"{w:?}"
|
||||
);
|
||||
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
|
||||
u.assert_valid();
|
||||
assert!(!u.parts.contains_key("xl/model/item.data"));
|
||||
assert!(written_pivot_tables(&u, "Report").is_empty());
|
||||
assert!(u.find(model_cache(1).as_bytes()).is_empty());
|
||||
assert!(u.text(&sheet_part(&u, "Report")).contains("<v>5</v>"), "the report cells stay");
|
||||
let caches = written_pivot_caches(&u);
|
||||
assert_eq!(caches.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(), ["4"], "{caches:?}");
|
||||
assert_eq!(written_pivot_tables(&u, "More").len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connection_pivot_tables_need_their_connections() {
|
||||
// No connections part: the caches name connections that aren't there.
|
||||
let (none, rep) = read_xlsx(&conn_pivot_package(ConnPkg { connections: false, ..CONN_PKG })).unwrap();
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("data connection is not in the workbook")), "{:?}", rep.warnings);
|
||||
// A cache naming a connection id the part doesn't have; the other cache is unaffected.
|
||||
let (missing, rep) = read_xlsx(&conn_pivot_package(ConnPkg { model_connection: 9, ..CONN_PKG })).unwrap();
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("data connection is not in the workbook")), "{:?}", rep.warnings);
|
||||
// A connections part that can't be kept: the model and every connection cache go with it.
|
||||
let (blocked, rep) = read_xlsx(&conn_pivot_package(ConnPkg { connections_blocked: true, ..CONN_PKG })).unwrap();
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("Data Model was dropped")), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("2 PivotTable cache(s)") && w.contains("connections were not kept")), "{:?}", rep.warnings);
|
||||
for (wb, all_gone) in [(none, true), (blocked, true), (missing, false)] {
|
||||
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
|
||||
u.assert_valid();
|
||||
assert!(written_pivot_tables(&u, "Report").is_empty());
|
||||
assert!(u.text(&sheet_part(&u, "Report")).contains("<v>5</v>"));
|
||||
if all_gone {
|
||||
assert!(written_pivot_tables(&u, "More").is_empty());
|
||||
assert!(written_pivot_caches(&u).is_empty());
|
||||
assert!(!u.parts.contains_key("xl/model/item.data"));
|
||||
} else {
|
||||
assert_eq!(written_pivot_tables(&u, "More").len(), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
# File-format parity
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (XLSX PivotTables whose source is in another workbook are kept on save; previously trivial: chart sheets are kept on save (#727)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-15 · **Change:** minor (XLSX PivotTables on a data connection or the Data Model, and the Data Model itself, are kept on save; previously minor: PivotTables whose source is in another workbook are kept on save) · **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) on a range, table or name of the same workbook, protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** PivotTables whose source is a range or name in another workbook (their PivotTable, cache definition and records parts and the cache's link to the other workbook's path, with the original `cacheId`; the `dxfId` and `numFmtId` style references are renumbered to the rewritten styles part; they aren't modelled, so they can't be edited or refreshed in GridCraft, their location isn't adjusted when rows or columns are inserted or deleted, and they are dropped with their sheet, a cache no kept PivotTable uses with them; checked in Excel: opens without repair and refreshes from the other workbook), 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) on a range, table or name of the same workbook, protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** PivotTables whose source is a range or name in another workbook, a data connection (`connections.xml`) or the workbook's Data Model (OLAP caches, usually `saveData="0"` with no records) (their PivotTable, cache definition and records parts and the cache's link to the other workbook's path, with the original `cacheId`; the `dxfId` and `numFmtId` style references are renumbered to the rewritten styles part; they aren't modelled, so they can't be edited or refreshed in GridCraft, their location isn't adjusted when rows or columns are inserted or deleted, and they are dropped with their sheet, a cache no kept PivotTable uses with them; a cache on a connection is kept only when the connections are, one on the Data Model only when the model is, otherwise the PivotTable is left as plain cells with a warning; checked in Excel: opens without repair and refreshes, from the other workbook, the connection or the model), the Data Model (`xl/model/item.data`, byte for byte with its data connections, up to 64 MB like any kept part; Excel opens a Data Model PivotTable without it but can't refresh it; the `x15:dataModel` workbook extension is not kept, Excel rebuilds it; a worksheet connection names its table through a hidden `_xlcn.` defined name, and renaming or deleting that table in GridCraft leaves the kept connection stale: Excel refuses a file whose connection names a missing defined name; in one real Power Query model, refreshing a kept PivotTable in Excel re-runs the queries, which the original does not), 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, 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, 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-15 | minor | XLSX: PivotTables on a data connection or the Data Model are kept on save (they were dropped with their caches), with the Data Model part and the connections they name; dropped to plain cells with a warning when the model or connections can't be kept |
|
||||
| 2026-10-14 | minor | XLSX: PivotTables whose source is in another workbook are kept on save (they were dropped with their caches, and the PivotTable was lost); their style references follow the rewritten styles part |
|
||||
| 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) |
|
||||
|
||||
Reference in new issue
Block a user