Model: workbook text defaults (languages, Asian/complex fonts)

Adds ScriptDefault { language, country, font } and TextDefaults
{ western, asian, complex } with is_empty, and Workbook::text_defaults,
exported from the model crate. An OpenDocument file states these on its
default cell style; Excel has no equivalent, so XLSX ignores them. The
field is kept in GridCraft JSON and skipped when empty, so a workbook
without it serialises exactly as before.
This commit is contained in:
alehel committed 2026-11-14 08:29:24 +01:00
1 parent 632e4a1bc5
commit 989782f1a0
3 files changed
+82 -2

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@ pub use style::{
};
pub use workbook::{
CalcMode, CalcSettings, DefinedName, DocProps, EQUATION_BUDGET_MESSAGE, MAX_EQUATION_LAYOUT_BYTES, PhoneticProps, PhoneticRun, PhoneticString,
ShowObjects, Workbook, WorkbookView,
ScriptDefault, ShowObjects, TextDefaults, Workbook, WorkbookView,
};
/// Font used for new workbooks. Only a name: renderers substitute an available open font
+79
View File
@@ -144,6 +144,44 @@ pub struct DefinedName {
pub hidden: bool,
}
/// The language, country and font a document gives one script's text by default, each `None`
/// when unstated. Codes are as files spell them (`de`/`DE`; ODF's `zxx`/`none` for no language).
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ScriptDefault {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub language: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
/// Asian and complex text only: Western text takes the default style's font.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub font: Option<String>,
}
impl ScriptDefault {
pub fn is_empty(&self) -> bool {
self.language.is_none() && self.country.is_none() && self.font.is_none()
}
}
/// Default language and fonts of Western, Asian (CJK) and complex (right-to-left, Indic) text.
/// An OpenDocument file states them on its default cell style; Excel has no equivalent, so
/// XLSX neither reads nor writes them.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TextDefaults {
#[serde(default, skip_serializing_if = "ScriptDefault::is_empty")]
pub western: ScriptDefault,
#[serde(default, skip_serializing_if = "ScriptDefault::is_empty")]
pub asian: ScriptDefault,
#[serde(default, skip_serializing_if = "ScriptDefault::is_empty")]
pub complex: ScriptDefault,
}
impl TextDefaults {
pub fn is_empty(&self) -> bool {
self.western.is_empty() && self.asian.is_empty() && self.complex.is_empty()
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct DocProps {
pub title: String,
@@ -261,6 +299,10 @@ pub struct Workbook {
/// Shared between snapshots, as nothing changes them.
#[serde(skip)]
pub macros_unread: Arc<Vec<serde_json::Value>>,
/// The language and fonts the document gives text of each script by default (an
/// OpenDocument file's default cell style). Empty unless a file stated them.
#[serde(default, skip_serializing_if = "TextDefaults::is_empty")]
pub text_defaults: TextDefaults,
/// Unmodelled file content kept for saving (package root and workbook level). Not in JSON.
#[serde(skip)]
pub preserved: Option<Arc<crate::preserved::Preserved>>,
@@ -363,6 +405,7 @@ impl Workbook {
macros: crate::macros::Macros::default(),
macros_read: vec![],
macros_unread: Arc::default(),
text_defaults: TextDefaults::default(),
preserved: None,
source_dir: None,
source_path: None,
@@ -593,6 +636,42 @@ mod tests {
Ok(())
}
#[test]
fn text_defaults_round_trip_in_json_and_are_skipped_when_empty() -> Result<(), Box<dyn std::error::Error>> {
let mut wb = Workbook::new();
assert!(wb.text_defaults.is_empty(), "new workbooks state no text defaults");
// A workbook without them serialises exactly as before the field existed.
let json = serde_json::to_string(&wb)?;
let value: serde_json::Value = serde_json::from_str(&json)?;
assert!(value.get("text_defaults").is_none(), "empty text defaults are not written");
// JSON written before the field existed still loads, with empty defaults.
assert!(serde_json::from_str::<Workbook>(&json)?.text_defaults.is_empty());
wb.text_defaults = TextDefaults {
western: ScriptDefault { language: Some("de".into()), country: Some("DE".into()), font: None },
asian: ScriptDefault { language: Some("ja".into()), country: Some("JP".into()), font: Some("Noto Sans CJK JP".into()) },
complex: ScriptDefault { language: None, country: None, font: Some("Noto Naskh Arabic".into()) },
};
assert!(!wb.text_defaults.is_empty());
let json = serde_json::to_string(&wb)?;
assert_eq!(serde_json::from_str::<Workbook>(&json)?.text_defaults, wb.text_defaults);
// Unstated parts stay out of the JSON.
let value: serde_json::Value = serde_json::from_str(&json)?;
let td = value.get("text_defaults").ok_or("text_defaults written")?;
assert!(td["western"].get("font").is_none());
assert!(td["complex"].get("language").is_none());
// Only one script stated: the others are skipped and load back empty.
wb.text_defaults =
TextDefaults { asian: ScriptDefault { font: Some("Noto Serif CJK SC".into()), ..Default::default() }, ..Default::default() };
let json = serde_json::to_string(&wb)?;
let value: serde_json::Value = serde_json::from_str(&json)?;
let td = value.get("text_defaults").ok_or("text_defaults written")?;
assert!(td.get("western").is_none() && td.get("complex").is_none());
assert_eq!(serde_json::from_str::<Workbook>(&json)?.text_defaults, wb.text_defaults);
Ok(())
}
#[test]
fn sheet_names() {
let wb = Workbook::new();
+2 -1
View File
@@ -1,6 +1,6 @@
# File-format parity
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-03 · **Change:** minor (a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-11 · **Change:** trivial (the workbook model holds a document's default text languages and Asian/complex-script fonts, kept in GridCraft JSON, for OpenDocument; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **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**
@@ -76,6 +76,7 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real
| Format | Excel | GridCraft read | GridCraft write | Fidelity / notes | Tests |
|---|---|---|---|---|---|
| 2026-11-11 | trivial | The workbook model holds the document's default language and country of Western, Asian and complex text, and the default Asian and complex fonts (`Workbook::text_defaults`), which an OpenDocument file states on its default cell style. GridCraft JSON keeps them and leaves the field out when nothing is stated, so other workbooks' JSON is unchanged; XLSX has no equivalent and ignores them. The ODS reader and writer that fill and write them come separately |
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **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) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), 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, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **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) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), 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, show objects (`workbookPr showObjects`). **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) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |