mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 07:44:40 +00:00
craft-xlsx decodes `.xlsb` cell formulas, including shared, array and dynamic-array formulas, into the text an `.xlsx` file holds for them. Until now they were skipped and only their saved values kept. Part of #778. Ported from storytold/gridcraft#3810, #3818 and #3821 (issue gridcraft#3806), my own series; the commits keep me (kiwi4boy) as their author. The three PRs are one series, each containing the one before. ## Commits 1. **The XLSB function table** (gridcraft#3810): `xlsb/ftab.rs`, [MS-XLSB] 2.5.98.10. It is craft-xls's table up to 379 (0x17B), which matches GridCraft's before the PR, plus the PR's 0x17C–0x1E4 entries (CUBE*, the Analysis ToolPak functions, IFERROR, COUNTIFS, SUMIFS, AVERAGEIF(S)). It is craft-xlsx's own copy, not shared with craft-xls: the formats follow separate specifications and their readers develop separately. They can share one table later once both settle. 2. **Cell formulas** (gridcraft#3818, with its two review fixes): `xlsb/formula.rs` is a BIFF12 decoder, separate from craft-xls's BIFF8 one, because nearly every operand differs. `xlsb/expr.rs` is a copy of craft-xls's expression tree and A1 printer, with `BinOp::precedence` added for grouping. A formula cell's `CellFormula.text` is in the file's spelling (`_xlfn.CONCAT`, `_xlpm.x`, no implicit `@`), and a `BrtCellMeta` before a cell sets `cell_metadata`, as `cm` does. The workbook's sheet links, supporting links and names are read with the workbook part, and `Package` keeps them for its sheets. A new `Limits::binary_formula_text` (128 MiB) bounds decoded text. 3. **Shared, array and dynamic-array formulas** (gridcraft#3821, with its review fixes): `PtgExp` cells, `BrtShrFmla` and `BrtArrFmla`. See the mapping below. 4. **A shared formula stops decoding copies once one is kept as its value**: a fix for CodeRabbit's finding that is still open on gridcraft#3821, so it isn't carried over. 5. **README**: what the decoder gives, what keeps its saved result, and the new limit. 6. **Review fixes**: 468 (0x1D4) is CONVERT. The specification's table has no row for it, but Excel writes CONVERT as `PtgFunc` 0x1D4. A shared formula's tokens are borrowed from the part instead of copied. A formula kept as its value loses its cell metadata. 7. **Review fixes, round 2**: a chain of strings joined with `&` is flattened only up to the decoder's depth bound (256 strings), so a balanced tree of thousands can't become a chain that overflows the stack when printed or dropped. A first cell whose range record never comes loses its cell metadata. 8. **Excel's spelling, from a second Excel round:** - Spaces and line breaks typed in a formula (`PtgAttrSpace`) are kept where `.xlsx` keeps them (`1 + 2`, `SUM( A1, B1 )`), and the text is trimmed as the `.xlsx` reader trims it. - A number is written out in full when that takes at most 21 characters without the sign, and in scientific notation otherwise (`100000000000000000000`, `1E+21`), as Excel writes it. The decoder switched at 1E+15 and 1E-9. - ISO.CEILING, ECMA.CEILING, NETWORKDAYS.INTL and WORKDAY.INTL are called through hidden `_xlfn.` names in `.xlsb`, but `.xlsx` spells them without the prefix. 9. **Macro sheets and spans over chart sheets:** a reference to an XLM macro sheet (`Macro1!$A$1`) is named, since macro sheets have cells. A 3-D span with a chart sheet between its ends is spelled by its ends, as `.xlsx` has it. An end with no cells still keeps the saved result. ## How it maps onto craft-xlsx's model - A formula's text is what the `.xlsx` reader gives for the same formula. GridCraft's reading of that text stays in GridCraft: `fmla::from_file`, the implicit `@` on legacy formulas, its parser check, and Python-cell adoption. - **Shared formulas:** every cell of the group gets `FormulaKind::Shared` with the group's `si` (counted per sheet), and the first cell also gets the range. Unlike `.xlsx`, where the other cells have empty text, each cell here gets its own text, decoded from the shared tokens at that cell. [MS-XLSB] defines it that way, with relative offsets that wrap around the grid. Shifting the first cell's text is not exact; the review of the GridCraft PR found that. `CellFormula.text`'s doc says so. - **Arrays:** the first cell gets `FormulaKind::Array` and its range. The other cells keep their cached values and have no formula, as in `.xlsx`. A dynamic array also has its `cell_metadata`, even across a `BrtValueMeta` written in between. Clearing the other cells, and deciding from `fDynamic` whether to spill, is the consumer's call (gridcraft#3825). - **Kept as values:** a formula that needs something the reader doesn't read keeps only its saved result, with a warning: user defined names (XLSB names aren't read yet), table references, other workbooks, `PY(index, …)` (code stored elsewhere in the package) and data tables. So do malformed tokens or records, and formulas past the allowance. A workbook whose links can't be read opens with values only, as before. ## Changed from the GridCraft PRs - craft-xlsx's own function table, tree and printer, instead of GridCraft's formula crate and the table and helpers shared with its `.xls` decoder. - A single-cell dynamic-array formula is read in commit 2, where #3818 left dynamic arrays to #3821: with `cell_metadata` there is nothing more to decide. - The test of GridCraft's 8,192-character parser limit is replaced by one showing that a shared copy may be longer than its first cell. Tests that saved to `.xlsx` with GridCraft are dropped. The rest of the PRs' tests come along in `tests/xlsb.rs`, with craft-xlsx's model in the expectations. - `Limits` gets a new public field, `binary_formula_text`. Code that builds `Limits` with `..Limits::default()` is unaffected. ## Checked against Excel Excel saved the same workbook (`make_probe.ps1` in the GridCraft work: refs, 3-D refs, names, shared, CSE and dynamic arrays, newer functions, LET, a table, an external link, unions and intersections, array constants) as `.xlsb` and as `.xlsx`. Read through craft-xlsx, all 33 formulas this decodes from the `.xlsb` match the `.xlsx`: same text, kind, range and shared index, with the same cell metadata. The other 5 use tables, an external link or defined names, and keep their values with those warnings. A second, wider round (commits 8 and 9) saved three more workbooks both ways: - 487 functions Excel accepts on a worksheet: every name in the function table except 113 macro-sheet-only commands, and about 120 newer `_xlfn.` functions, LET, LAMBDA and its helpers, GROUPBY, the REGEX functions, `TRIMRANGE` and `A1:.A5`, IMAGE, RTD, CUBEVALUE and an add-in function; - operators and precedence, unary and percent chains, unions, intersections, whole rows and columns, 3-D references and spans, quoted and cell-like sheet names, array constants, edge-magnitude numbers, a 255-character string, unicode, errors and missing arguments, legacy and dynamic-array `@`, references to a deleted sheet, column and row; - 246 shared-formula cells, including relative references that wrap at the grid's edges, legacy array formulas, spills, spill references and a data table; - 60 formulas typed with spaces and line breaks, and 62 number literals around Excel's switch to scientific notation. Before commit 8, 725 formulas matched and 20 differed. Now 744 of the 745 match, with the same text, kind, range and cell metadata, and every non-first shared-formula cell matches Excel's own `Range.Formula`. The other one is a deleted column on a sheet named like a cell (`'S3'!#REF!`). That is #1330's: it prints the sheet before `#REF!`, which this PR doesn't. The spacing and number workbooks match in full. Two inline LAMBDA calls, an add-in call and a data table keep their saved results, as described above. ## Ran locally (own target directory) - `cargo fmt -p craft-xlsx --check`: clean - `cargo clippy -p craft-xlsx --all-targets --all-features -- -D warnings`: clean (and `cargo clippy --workspace --all-targets -- -D warnings` after commit 9) - `cargo test -p craft-xlsx --all-features`: 74 pass, 0 fail (after commit 7); 76 after commit 9. No other workspace crate depends on craft-xlsx. - The new tests fail without their commit's code: 5 of 6 for commit 3 (the sixth checks that unreadable shared formulas keep their values, which commit 2 already does), and 1 for commit 4. The tests for commits 8 and 9 fail without them. ## For the coordinator Once this is merged, gridcraft#3810, #3818 and #3821 can be closed, each with a note like "Ported to craft-xlsx in storytold/craft-libs#1166; GridCraft gets it when it switches to craft-xlsx." GridCraft's remainder is the mapping. That means `from_file` and the implicit `@` (as for `.xlsx`), Python cells, clearing array cells, spilling dynamic arrays, the `xlsb-import.md` / `gaps.md` / `file-format-parity.md` notes and the engine's use of `read_xlsb_with`. I'll redo those against the switch. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Binary Excel workbooks now display decoded formula text in familiar spreadsheet notation, including shared and array formulas. * Shared-formula cells show formula text adjusted to their own cell references. Array-formula follower cells do not display separate formula text. * **Bug Fixes** * When formulas cannot be decoded or exceed supported limits, cells retain their saved results; a warning may be provided. * **Documentation** * Clarified formula display behavior and documented limits on formula text, token length, nesting depth, and array constants. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
180 lines
8.2 KiB
Rust
180 lines
8.2 KiB
Rust
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
|
//! Excel workbooks: `.xlsx`/`.xlsm` (SpreadsheetML, ECMA-376 Part 1, transitional and strict) and
|
|
//! `.xlsb` (the same package with binary parts, [MS-XLSB]). Clean-room, from the specifications
|
|
//! and observed files.
|
|
//!
|
|
//! This is the part layer: a [`Package`] opens the OPC container (`craft-opc`) and reads
|
|
//!
|
|
//! - the workbook part: sheets, the date system, defined names ([`Workbook`]);
|
|
//! - shared strings with their rich-text runs and phonetic readings ([`StringItem`]);
|
|
//! - the styles tables as the file has them ([`Styles`]): number formats, fonts, fills, borders,
|
|
//! cell formats, named styles and differential formats, by index;
|
|
//! - one worksheet at a time as a stream of [`Row`]s of [`Cell`]s, so a sheet of any length is
|
|
//! read without holding it; what is left of the part (properties, columns, merged cells,
|
|
//! validation, and so on) comes back as a tree ([`SheetPart`]).
|
|
//!
|
|
//! Parts are read with fixed prefixes ([`ns`]): the SpreadsheetML main namespace has none
|
|
//! (`sheetData`), the others have theirs whatever the file used (`r:id`, `x14:sparklineGroups`,
|
|
//! `mc:AlternateContent`), so a tree kept from a part can be written back with [`ns::declare`].
|
|
//!
|
|
//! Nothing is interpreted beyond the format: a cell holds a shared-string index and a format
|
|
//! index, a width is in the file's units, a formula is the file's text. Every other part
|
|
//! (drawings, charts, pivot caches, macros) is reachable through [`Package::opc`], so a caller
|
|
//! can read it or carry it through unchanged.
|
|
//!
|
|
//! A binary workbook gives the same [`Workbook`], [`StringItem`]s, [`Row`]s and merged cells:
|
|
//! saved values only, since formulas there are token streams that are not decoded and styles are
|
|
//! not read.
|
|
//!
|
|
//! Reading SpreadsheetML is lenient: a damaged optional part is skipped and named in
|
|
//! [`Package::warnings`]; only an unreadable package or workbook part is an error. Reading a
|
|
//! binary workbook is strict: a record that does not parse fails the read, because skipping it
|
|
//! would lose data silently. Input is hostile: [`Limits`] bounds the package, the XML and the
|
|
//! binary records, cells outside the grid are dropped, and nothing indexes by a number from the
|
|
//! file.
|
|
//!
|
|
//! ```
|
|
//! # fn main() -> Result<(), craft_xlsx::Error> {
|
|
//! # let bytes = craft_xlsx::testing::workbook(&[("Prices", r#"<row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1"><v>2.5</v></c></row>"#)], &["Tea"]);
|
|
//! let mut package = craft_xlsx::Package::open(&bytes, &craft_xlsx::Limits::default())?;
|
|
//! let workbook = package.workbook()?;
|
|
//! let strings = package.shared_strings()?;
|
|
//! let mut values = Vec::new();
|
|
//! package.sheet(&workbook.sheets[0], |row| {
|
|
//! values.extend(row.cells.iter().map(|c| c.value.resolve(&strings, workbook.date_1904)));
|
|
//! Ok(())
|
|
//! })?;
|
|
//! assert_eq!(values, [craft_xlsx::Value::text("Tea"), craft_xlsx::Value::Number(2.5)]);
|
|
//! # Ok(())
|
|
//! # }
|
|
//! ```
|
|
|
|
mod document;
|
|
mod drawing;
|
|
#[macro_use]
|
|
mod features;
|
|
pub mod ns;
|
|
mod package;
|
|
mod pivot;
|
|
mod richdata;
|
|
mod sheet;
|
|
mod strings;
|
|
mod styles;
|
|
#[doc(hidden)]
|
|
pub mod testing;
|
|
mod workbook;
|
|
mod write;
|
|
mod xlsb;
|
|
|
|
pub use craft_drawingml;
|
|
pub use craft_sheet::{
|
|
BorderStyle, CellError, CellRef, DEFAULT_PALETTE, HAlign, MAX_COLS, MAX_ROWS, Pattern, Range, Script, Underline, VAlign, Value, Visibility,
|
|
builtin_format, builtin_format_id, quote_sheet, sheet_needs_quotes,
|
|
};
|
|
pub use document::{Document, DrawingPart, KeptPart, PivotCachePart, PivotTablePart, TablePart, Worksheet, XlsxKind};
|
|
pub use drawing::{Anchor, Drawing, Item, Marker, ObjectKind, Placement};
|
|
pub use features::{
|
|
Break, CfRule, Cfvo, ColorScale, Comment, Comments, ConditionalFormatting, DataBar, DataValidation, DataValidations, Features, HeaderFooter,
|
|
Hyperlink, IconSet, NoteShape, PageMargins, PageSetup, Pane, Print, PrintOptions, Selection, SheetView, Table, TableColumn, TableStyleInfo,
|
|
notes_vml, parse_sqref, range_ref,
|
|
};
|
|
pub use package::{Package, is_xlsb};
|
|
pub use pivot::{
|
|
CacheField, CacheItem, CacheRecord, CacheSource, CacheValue, DataField, FieldGroup, Location, PageField, PivotCacheDefinition, PivotField,
|
|
PivotItem, PivotTableDefinition, PivotTableStyleInfo, RangePr, SharedItems, WorksheetSource, records_xml,
|
|
};
|
|
pub use richdata::{CellPicture, MAX_PICTURE, MAX_PICTURES_TOTAL, MAX_RECORDS};
|
|
pub use sheet::{Cell, CellFormula, CellValue, Column, FormulaKind, Row, SheetPart, iso_date_serial};
|
|
pub use strings::{PhoneticProps, PhoneticRun, StringItem, TextRun, decode_xstring, encode_xstring, rich_text, t_el};
|
|
pub use styles::{
|
|
Alignment, Border, BorderEdge, CellStyle, Color, ColorSource, Dxf, Fill, Font, FontScheme, GradientFill, PatternFill, Protection, Styles, Xf,
|
|
};
|
|
pub use workbook::{DefinedName, PivotCacheEntry, SheetEntry, SheetKind, Workbook};
|
|
pub use write::num;
|
|
|
|
/// Why a workbook could not be read.
|
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
|
pub enum Error {
|
|
/// The bytes are not a ZIP package, or an entry is damaged.
|
|
#[error("the file is not a valid zip package: {0}")]
|
|
Zip(String),
|
|
/// A part that must be read holds XML that cannot be.
|
|
#[error("the file contains invalid XML: {0}")]
|
|
Xml(String),
|
|
/// The package is not a workbook, or a binary part is damaged.
|
|
#[error("the file is not a valid spreadsheet: {0}")]
|
|
Invalid(String),
|
|
/// More than [`Limits`] or a fixed cap allows.
|
|
#[error("the file is too large: {0}")]
|
|
TooLarge(String),
|
|
}
|
|
|
|
impl From<craft_opc::Error> for Error {
|
|
fn from(e: craft_opc::Error) -> Self {
|
|
match e {
|
|
e if e.is_limit() => Error::TooLarge(e.to_string()),
|
|
craft_opc::Error::Zip(m) => Error::Zip(m),
|
|
craft_opc::Error::Xml { .. } => Error::Xml(e.to_string()),
|
|
e => Error::Invalid(e.to_string()),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<craft_xml::Error> for Error {
|
|
fn from(e: craft_xml::Error) -> Self {
|
|
if e.is_limit() { Error::TooLarge(e.to_string()) } else { Error::Xml(e.to_string()) }
|
|
}
|
|
}
|
|
|
|
/// What a read refuses to exceed. The defaults suit a spreadsheet application; a caller that
|
|
/// only wants a table of values can lower them.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub struct Limits {
|
|
/// The ZIP package: entries, bytes per part and bytes in all.
|
|
pub package: craft_opc::Limits,
|
|
/// One XML part. Rows and shared strings are streamed, so `max_nodes` bounds one row or one
|
|
/// string and what is left of a part, not a sheet's length.
|
|
pub xml: craft_xml::Limits,
|
|
/// Records read from a binary workbook, every part together. Records are skipped or decoded
|
|
/// without being kept, so this bounds parse time, not memory. Excel writes four records per
|
|
/// row besides the cells, and one per formatted empty cell, so a sheet needs many more
|
|
/// records than cells.
|
|
pub binary_records: usize,
|
|
/// Cells with a value read from a binary workbook, over all its sheets; also the most
|
|
/// shared-string items.
|
|
pub binary_cells: usize,
|
|
/// Bytes of decoded text (shared and inline strings) in a binary workbook, over all its parts.
|
|
pub binary_text: usize,
|
|
/// Bytes of decoded formula text in a binary workbook, over all its sheets. A cell formula
|
|
/// may hold 16 KB of tokens, so without a total a million cells of long formulas would cost
|
|
/// gigabytes; past it, formulas keep their saved results (the file still opens).
|
|
pub binary_formula_text: usize,
|
|
}
|
|
|
|
impl Default for Limits {
|
|
fn default() -> Self {
|
|
Limits {
|
|
package: craft_opc::Limits::new(200_000, 512 << 20, 1 << 30),
|
|
xml: craft_xml::Limits { max_input: 512 << 20, ..craft_xml::Limits::DEFAULT },
|
|
// The limits of `craft-xls`.
|
|
binary_records: 40_000_000,
|
|
binary_cells: 4_000_000,
|
|
binary_text: 256 << 20,
|
|
binary_formula_text: 128 << 20,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// What a read skipped or repaired, each distinct message once and at most 1000 of them.
|
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
|
pub(crate) struct Warnings(pub(crate) Vec<String>);
|
|
|
|
impl Warnings {
|
|
pub(crate) fn warn(&mut self, m: impl Into<String>) {
|
|
let m = m.into();
|
|
if self.0.len() < 1000 && !self.0.contains(&m) {
|
|
self.0.push(m);
|
|
}
|
|
}
|
|
}
|