Skip to main content

sheet_xlsx/
lib.rs

1//! XLSX codec — workbook, worksheets, shared strings, styles, calc chain —
2//! parse and serialize.
3//!
4//! `sheet-xlsx` reads and writes `SpreadsheetML` packages (`.xlsx`) on top of
5//! the estate's [`sheet-core`] data model: [`XlsxWorkbook`] is the package
6//! view (named sheets, shared-string table, style count), and every cell
7//! coordinate is `(row, col)` in the shared 0-based space, with `A1`
8//! conversion borrowed from `sheet_core::refs`.
9//!
10//! # Package layout
11//!
12//! A workbook is a ZIP of XML parts. On write, `sheet-xlsx` emits the
13//! canonical minimal set — `[Content_Types].xml`, `_rels/.rels`,
14//! `xl/workbook.xml`, its relationships, one `xl/worksheets/sheetN.xml` per
15//! sheet, `xl/sharedStrings.xml`, `xl/styles.xml`, and `xl/calcChain.xml`
16//! when any cell carries a formula. On read, parts are located through the
17//! relationship graph (not by hardcoded paths), so renamed or relocated
18//! packages still parse.
19//!
20//! # Faithfulness over cleverness
21//!
22//! The codec is deliberately **lossless for the model it defines**:
23//! round-tripping a workbook through `write_xlsx` → `read_xlsx` reproduces
24//! `XlsxCell` values exactly — including the choice between shared and
25//! inline strings, error literals, cached formula results, and style
26//! indices — which is the property the test suite checks on random
27//! workbooks. Full OOXML (charts, pivot tables, themes, merged cells,
28//! number formats) is out of scope: only the parts listed above are
29//! consumed or emitted, and the reader ignores everything else.
30//!
31//! # Known v0.1 limitations (documented, typed, non-panicking)
32//!
33//! - **Style definitions are not modeled.** Styles are a count of `cellXfs`
34//!   entries; indices survive round-trips, but fonts/fills/borders do not.
35//! - **Shared formulas**: the master cell keeps its formula text; slave
36//!   cells keep their cached values but their translated formulas are not
37//!   reconstructed.
38//! - **Cells with neither value nor formula** (e.g. style-only cells) are
39//!   dropped — absence is blank, matching `sheet-core`.
40//!
41//! # Layer
42//!
43//! L1 substrate: depends on [`sheet-core`] (L1, same layer) plus `zip` and
44//! `quick-xml`; `#![forbid(unsafe_code)]`.
45//!
46//! # Example
47//!
48//! ```
49//! use sheet_xlsx::{read_xlsx, write_xlsx, XlsxCell, SheetData, XlsxValue, XlsxWorkbook};
50//! use std::collections::BTreeMap;
51//!
52//! let mut cells = BTreeMap::new();
53//! cells.insert((0, 0), XlsxCell { value: XlsxValue::Number(41.0), style_index: None, formula: None });
54//! cells.insert((1, 0), XlsxCell {
55//!     value: XlsxValue::FormulaString(String::new()),
56//!     style_index: None,
57//!     formula: Some(String::from("=A1+1")),
58//! });
59//!
60//! let mut wb = XlsxWorkbook::default();
61//! wb.sheets.push(SheetData { name: String::from("Sheet1"), cells });
62//!
63//! let bytes = write_xlsx(&wb).unwrap();
64//! let round = read_xlsx(&bytes).unwrap();
65//! assert_eq!(round.sheets.len(), 1);
66//! assert_eq!(round.sheets[0].cells.get(&(1, 0)).unwrap().formula.as_deref(), Some("=A1+1"));
67//! ```
68
69#![forbid(unsafe_code)]
70
71pub mod calc_chain;
72pub mod error;
73pub mod reader;
74pub mod shared_strings;
75pub mod styles;
76pub mod writer;
77
78pub use calc_chain::{CalcChain, CalcEntry};
79pub use error::XlsxError;
80pub use reader::read_xlsx;
81pub use shared_strings::SharedStrings;
82pub use styles::Styles;
83pub use writer::write_xlsx;
84
85use std::collections::BTreeMap;
86
87/// A parsed XLSX package: named sheets in workbook order, the shared-string
88/// table, and the style-table size.
89#[derive(Debug, Clone, Default, PartialEq)]
90pub struct XlsxWorkbook {
91    /// Worksheets in workbook (`<sheet>` element) order.
92    pub sheets: Vec<SheetData>,
93    /// The shared-string table; [`XlsxValue::SharedString`] indexes into it.
94    pub shared_strings: SharedStrings,
95    /// Style-table metadata (see [`Styles`]).
96    pub styles: Styles,
97}
98
99impl XlsxWorkbook {
100    /// A workbook with one empty sheet named `Sheet1`.
101    #[must_use]
102    pub fn single_sheet() -> Self {
103        XlsxWorkbook {
104            sheets: vec![SheetData::new("Sheet1")],
105            shared_strings: SharedStrings::default(),
106            styles: Styles::default(),
107        }
108    }
109
110    /// Resolves a shared-string index to its text.
111    #[must_use]
112    pub fn shared_text(&self, index: u32) -> Option<&str> {
113        self.shared_strings.get(index)
114    }
115}
116
117/// One worksheet: its name and sparse cell storage. Coordinates are 0-based
118/// `(row, col)`; iteration is row-major (deterministic) via the `BTreeMap`.
119#[derive(Debug, Clone, Default, PartialEq)]
120pub struct SheetData {
121    /// The sheet name as declared in `xl/workbook.xml`.
122    pub name: String,
123    /// Present cells keyed by `(row, col)`.
124    pub cells: BTreeMap<(u32, u32), XlsxCell>,
125}
126
127impl SheetData {
128    /// An empty sheet with the given name.
129    #[must_use]
130    pub fn new(name: impl Into<String>) -> Self {
131        SheetData {
132            name: name.into(),
133            cells: BTreeMap::new(),
134        }
135    }
136}
137
138/// One cell: value, optional style index, optional formula text.
139///
140/// `formula` carries the formula **without** its cached result — the cached
141/// result lives in `value` (e.g. `XlsxValue::Number` for a numeric result,
142/// `XlsxValue::FormulaString` for a string result), exactly as `SpreadsheetML`
143/// stores it.
144#[derive(Debug, Clone, PartialEq)]
145pub struct XlsxCell {
146    /// The cell's (possibly cached) value.
147    pub value: XlsxValue,
148    /// Index into the workbook's style table (`s` attribute), if styled.
149    pub style_index: Option<u32>,
150    /// Formula text without the leading `=`'s result — e.g. `"A1+1"` for
151    /// `=A1+1`. Stored verbatim after the `=`.
152    pub formula: Option<String>,
153}
154
155impl XlsxCell {
156    /// A value-only cell.
157    #[must_use]
158    pub const fn new(value: XlsxValue) -> Self {
159        XlsxCell {
160            value,
161            style_index: None,
162            formula: None,
163        }
164    }
165
166    /// A formula cell with a cached value.
167    #[must_use]
168    pub fn formula(formula: impl Into<String>, cached: XlsxValue) -> Self {
169        XlsxCell {
170            value: cached,
171            style_index: None,
172            formula: Some(formula.into()),
173        }
174    }
175}
176
177/// The value of an [`XlsxCell`], mirroring `SpreadsheetML`'s cell types.
178#[derive(Debug, Clone, PartialEq)]
179pub enum XlsxValue {
180    /// A numeric cell (`t="n"`, the default type).
181    Number(f64),
182    /// A shared-string cell (`t="s"`): an index into the workbook's
183    /// shared-string table.
184    SharedString(u32),
185    /// An inline string (`t="inlineStr"`): text stored in the sheet part
186    /// itself. `write_xlsx` preserves the shared/inline distinction so
187    /// round-trips are exact.
188    InlineString(String),
189    /// A boolean cell (`t="b"`).
190    Boolean(bool),
191    /// An error cell (`t="e"`): the literal as stored (`"#REF!"`, …).
192    Error(String),
193    /// A formula's cached string result (`t="str"`), or a formula cell
194    /// with no cached result (empty string — see the reader docs).
195    FormulaString(String),
196}
197
198impl XlsxValue {
199    /// The text of string-ish values as an owned `String`
200    /// ([`SharedString`](XlsxValue::SharedString) resolves through the
201    /// shared table; inline and formula strings copy from the cell).
202    /// `None` for numbers, booleans, and errors.
203    #[must_use]
204    pub fn text(&self, shared: &SharedStrings) -> Option<String> {
205        match self {
206            XlsxValue::SharedString(i) => shared.get(*i).map(String::from),
207            XlsxValue::InlineString(s) | XlsxValue::FormulaString(s) => Some(s.clone()),
208            XlsxValue::Number(_) | XlsxValue::Boolean(_) | XlsxValue::Error(_) => None,
209        }
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    #![allow(
216        clippy::unwrap_used,
217        clippy::expect_used,
218        clippy::panic,
219        clippy::indexing_slicing
220    )]
221
222    use super::{SharedStrings, SheetData, Styles, XlsxValue, XlsxWorkbook};
223
224    #[test]
225    fn single_sheet_and_defaults() {
226        let wb = XlsxWorkbook::single_sheet();
227        assert_eq!(wb.sheets.len(), 1);
228        assert_eq!(wb.sheets[0].name, "Sheet1");
229        assert!(wb.sheets[0].cells.is_empty());
230        assert!(wb.shared_strings.is_empty());
231        assert_eq!(wb.styles.cell_xfs, 0);
232
233        let empty = XlsxWorkbook::default();
234        assert_eq!(empty.sheets.len(), 0);
235        assert_eq!(SheetData::new("N").name, "N");
236    }
237
238    #[test]
239    fn text_resolution_through_the_shared_table() {
240        let mut shared = SharedStrings::default();
241        let idx = shared.insert("hello");
242        assert_eq!(idx, 0);
243        let wb_idx = XlsxValue::SharedString(idx);
244        assert_eq!(wb_idx.text(&shared), Some(String::from("hello")));
245        assert_eq!(XlsxValue::SharedString(9).text(&shared), None);
246        assert_eq!(
247            XlsxValue::InlineString("s".to_string()).text(&shared),
248            Some(String::from("s"))
249        );
250        assert_eq!(
251            XlsxValue::FormulaString("f".to_string()).text(&shared),
252            Some(String::from("f"))
253        );
254        assert_eq!(XlsxValue::Number(1.0).text(&shared), None);
255        assert_eq!(XlsxValue::Boolean(true).text(&shared), None);
256        assert_eq!(XlsxValue::Error("#REF!".to_string()).text(&shared), None);
257    }
258
259    #[test]
260    fn shared_string_table_semantics() {
261        let mut t = SharedStrings::default();
262        assert!(t.is_empty());
263        let a = t.insert("dup");
264        let b = t.insert("dup");
265        let c = t.insert("other");
266        assert_eq!(a, b, "dedup");
267        assert_eq!(c, 1);
268        assert_eq!(t.len(), 2);
269        assert_eq!(t.get(0), Some("dup"));
270        assert_eq!(t.get(1), Some("other"));
271        assert_eq!(t.get(2), None);
272        let round = XlsxWorkbook::default();
273        let _ = round; // Default derives cleanly with all fields
274        let _ = Styles::default();
275    }
276}