Skip to main content

sheet_io/
lib.rs

1// sheet_io -- XLSX and CSV import and export: workbooks and delimited text as typed tables
2// (JFDiagrammer JD18, FEATURES.md IM-05 / IM-10, decision F6: "CSV und .xlsx in P2 mit XLSX-Leser
3// in JFLib"; the writers JD19, EX-12 shape reports and EX-16 data export as CSV / .xlsx)
4//
5//   xlsx::Workbook::open(bytes, Limits) -> Workbook     the workbook part, its relationships,
6//        the shared strings and the styles (which number formats are dates); not the sheets yet
7//   wb.sheets() / names() / date1904()                   sheets with state and kind, defined
8//        names (global and sheet-local, _xlnm.* included) and tables (ListObjects) as names
9//   wb.sheet(i) -> Grid                                  one worksheet, sparse: stored values
10//        (a formula's cached result, formulas are never evaluated)
11//   wb.table(&area, header) / wb.sheet_table(i, header) -> Table   a rectangle as a table
12//   csv::read(bytes, &Options) -> Csv                    RFC 4180 and what Excel writes: the
13//        encoding (BOM, UTF-8, else Windows-1252) and the delimiter (; , TAB |) detected
14//   csv::to_table(&csv, header, infer, cells) -> Table   with numbers, booleans and dates typed
15//   xlsx::write(&BookOut, &WriteOptions) -> Vec<u8>      typed rows as a workbook Excel opens
16//        without repair (xlsx_write.rs): shared strings, dates with Excel's number formats, a
17//        bold and frozen header, column widths, a filter; Excel's limits as errors
18//   csv::write(rows, &WriteOptions) / csv::write_table -> Vec<u8>   delimiter, line end,
19//        encoding (UTF-8 with or without BOM, UTF-16, Windows-1252), decimal comma, a guard
20//        against formula injection
21//   Value, CellError, CellRef / parse_ref / col_name, Area / parse_area, civil / serial
22//
23// What is written reads back with the readers here as it was written (the tests check it), with
24// the exceptions each writer names: Excel's newer errors and dates it cannot show become texts,
25// NaN and infinities #NUM!; CSV has no types at all.  Writing is deterministic (no time stamps,
26// the same rows give the same bytes) and bounded (xlsx::WriteOptions, csv::WriteOptions::max_bytes).
27//
28// Why a crate of its own: one crate per foreign format family, like dxf, gltf and pdf.  Not
29// doc_io: that is jfWord's document model, and every user of a spreadsheet reader would pull in
30// doc_core, doc_layout and text.  Not archive: that holds containers (ZIP, OPC), not their
31// content.  Not base: base::encoding is strict Unicode by design ("no guessed legacy code
32// pages"), while CSV files from Excel come in Windows-1252.  CSV sits next to XLSX because both
33// deliver the same typed Table.
34//
35// Every file is untrusted input: the ZIP container is bounded before anything is inflated
36// (archive::Limits, the compression ratio included), the XML reader (formats::xml::Reader) takes
37// no DTD and no entity but the five predefined ones and bounds the nesting, rows, columns, cells,
38// shared strings and their bytes, sheets and names are bounded, no size a file advertises
39// (<dimension>, count, uniqueCount) sizes an allocation, cells are stored sparsely, nothing
40// recurses, a CSV table pads its rows only within a count of cells.  A broken file is an error,
41// never a panic.
42#![no_std]
43#![forbid(unsafe_code)]
44
45extern crate alloc;
46
47use alloc::collections::BTreeMap;
48use alloc::format;
49use alloc::string::{String, ToString};
50use alloc::vec::Vec;
51
52pub mod csv;
53pub mod xlsx;
54mod xlsx_write;
55mod xml;
56
57/// A calendar date and wall time (datetime's), what `civil` and `serial` convert.
58pub use datetime::Civil;
59
60/// Excel's rows per sheet: the last row of a whole-column reference (`A:C`)
61pub const MAX_ROWS: u32 = 1_048_576;
62/// Excel's columns per sheet (A to XFD): the last column of a whole-row reference (`1:3`)
63pub const MAX_COLS: u32 = 16_384;
64
65/// A cell value with its type.
66///
67/// `Date` holds an OLE Automation date, as Visio and Excel's 1900 date system use it: days since
68/// 1899-12-30, the fraction is the time of day (values are taken as linear, also below zero).
69/// Values from 0 to below 1 are a time of day without a date.  The XLSX reader converts the
70/// 1904 date system and Excel's fake 1900-02-29 (see `xlsx`).
71#[derive(Clone, Debug, PartialEq, Default)]
72pub enum Value {
73    /// no value (an empty cell, a formula without a cached result)
74    #[default]
75    Empty,
76    /// a number
77    Number(f64),
78    /// a text
79    Text(String),
80    /// TRUE or FALSE
81    Bool(bool),
82    /// a date and time as an OLE Automation date (days since 1899-12-30)
83    Date(f64),
84    /// an error value of a cell (#N/A, #DIV/0! ...)
85    Error(CellError),
86}
87
88impl Value {
89    /// The display form: numbers as the shortest text that reads back (`base::f64_format`,
90    /// `-0` as `0`), dates as ISO 8601 (`2026-11-23`, `2026-11-23 14:05:00`, a time of day alone
91    /// as `14:05:00`, milliseconds only when there are some: `14:05:00.250`), booleans as
92    /// `TRUE` / `FALSE`, errors as Excel writes them (`#N/A`), Empty as "".
93    pub fn text(&self) -> String {
94        match self {
95            Value::Empty => String::new(),
96            Value::Number(v) => number_text(*v),
97            Value::Text(s) => s.clone(),
98            Value::Bool(b) => String::from(if *b { "TRUE" } else { "FALSE" }),
99            Value::Date(v) => date_text(*v),
100            Value::Error(e) => String::from(e.text()),
101        }
102    }
103    /// Whether this is `Empty`.
104    pub fn is_empty(&self) -> bool {
105        matches!(self, Value::Empty)
106    }
107    /// The number of a Number or a Date (its serial), else None.
108    pub fn number(&self) -> Option<f64> {
109        match self {
110            Value::Number(v) | Value::Date(v) => Some(*v),
111            _ => None,
112        }
113    }
114}
115
116pub(crate) fn number_text(v: f64) -> String {
117    if v == 0.0 { String::from("0") } else { base::f64_format(v) }
118}
119
120fn date_text(v: f64) -> String {
121    let Some(c) = civil(v) else { return number_text(v) };
122    let mut time = format!("{:02}:{:02}:{:02}", c.hour, c.minute, c.second);
123    if c.nanos != 0 {
124        time.push_str(&format!(".{:03}", c.nanos / 1_000_000));
125    }
126    if v >= 0.0 && (c.year, c.month, c.day) == (1899, 12, 30) {
127        return time;
128    }
129    let date = format!("{:04}-{:02}-{:02}", c.year, c.month, c.day);
130    if c.hour == 0 && c.minute == 0 && c.second == 0 && c.nanos == 0 { date } else { format!("{date} {time}") }
131}
132
133// days since 1970-01-01 of 1899-12-30, the day 0 of OLE dates
134const OLE_EPOCH: i64 = -25_569;
135
136/// The date and time of an OLE Automation date (days since 1899-12-30, the fraction the time of
137/// day), rounded to the millisecond; None for NaN, infinities and values beyond 10^8 days.
138pub fn civil(serial: f64) -> Option<Civil> {
139    if !serial.is_finite() || serial.abs() > 1.0e8 {
140        return None;
141    }
142    let x = serial * 86_400_000.0;
143    let ms = if x >= 0.0 { (x + 0.5) as i64 } else { -((-x + 0.5) as i64) };
144    let days = ms.div_euclid(86_400_000);
145    let rem = ms.rem_euclid(86_400_000);
146    let (year, month, day) = datetime::civil_from_days(days + OLE_EPOCH);
147    Some(Civil {
148        year,
149        month,
150        day,
151        hour: (rem / 3_600_000) as u8,
152        minute: (rem / 60_000 % 60) as u8,
153        second: (rem / 1000 % 60) as u8,
154        nanos: (rem % 1000) as u32 * 1_000_000,
155    })
156}
157
158/// The OLE Automation date of a date and time (days since 1899-12-30, the fraction the time of
159/// day); `civil` reads it back.
160pub fn serial(c: &Civil) -> f64 {
161    let days = datetime::days_from_civil(c.year, c.month, c.day) - OLE_EPOCH;
162    let secs = c.hour as f64 * 3600.0 + c.minute as f64 * 60.0 + c.second as f64 + c.nanos as f64 / 1.0e9;
163    days as f64 + secs / 86_400.0
164}
165
166// the OLE day of a valid date, None for an invalid one
167pub(crate) fn ole_day(y: i32, m: u8, d: u8) -> Option<f64> {
168    if !(1..=12).contains(&m) || d == 0 || d > datetime::days_in_month(y, m) {
169        return None;
170    }
171    Some((datetime::days_from_civil(y, m, d) - OLE_EPOCH) as f64)
172}
173
174// "HH:MM", "HH:MM:SS", "HH:MM:SS.fff" (hours 0..23, a second of 60 refused) -> fraction of a day
175pub(crate) fn parse_time(s: &str) -> Option<f64> {
176    let b = s.as_bytes();
177    let two = |i: usize| -> Option<u32> {
178        let (x, y) = (*b.get(i)?, *b.get(i + 1)?);
179        (x.is_ascii_digit() && y.is_ascii_digit()).then(|| ((x - b'0') * 10 + (y - b'0')) as u32)
180    };
181    let h = two(0)?;
182    if b.get(2) != Some(&b':') {
183        return None;
184    }
185    let m = two(3)?;
186    let mut secs = 0.0;
187    let mut i = 5;
188    if b.get(5) == Some(&b':') {
189        secs = two(6)? as f64;
190        i = 8;
191        if b.get(8) == Some(&b'.') {
192            let frac = &s[9..];
193            if frac.is_empty() || frac.len() > 9 || !frac.bytes().all(|c| c.is_ascii_digit()) {
194                return None;
195            }
196            let (f, used) = base::f64_parse(&b[8..]);
197            if used != b.len() - 8 {
198                return None;
199            }
200            secs += f;
201            i = b.len();
202        }
203    }
204    if i != b.len() || h > 23 || m > 59 || secs >= 60.0 {
205        return None;
206    }
207    Some((h as f64 * 3600.0 + m as f64 * 60.0 + secs) / 86_400.0)
208}
209
210// ISO 8601 as Excel and CSV exports write it: "2026-11-23", "2026-11-23T14:05",
211// "2026-11-23 14:05:00.5", a trailing "Z" (the wall time kept); `time_only`: also "14:05:00"
212pub(crate) fn parse_iso(s: &str, time_only: bool) -> Option<f64> {
213    let s = s.strip_suffix('Z').unwrap_or(s);
214    let b = s.as_bytes();
215    if time_only && b.get(2) == Some(&b':') {
216        return parse_time(s);
217    }
218    if b.len() < 10 || b[4] != b'-' || b[7] != b'-' {
219        return None;
220    }
221    let digits = |r: core::ops::Range<usize>| -> Option<u32> {
222        let t = b.get(r)?;
223        t.iter().all(u8::is_ascii_digit).then(|| t.iter().fold(0, |a, &c| a * 10 + (c - b'0') as u32))
224    };
225    let (y, m, d) = (digits(0..4)?, digits(5..7)?, digits(8..10)?);
226    let day = ole_day(y as i32, m as u8, d as u8)?;
227    match b.get(10) {
228        None => Some(day),
229        Some(b'T' | b' ') => Some(day + parse_time(&s[11..])?),
230        _ => None,
231    }
232}
233
234/// An error value of a cell.
235#[derive(Clone, Debug, PartialEq, Eq, Hash)]
236pub enum CellError {
237    /// `#NULL!`
238    Null,
239    /// `#DIV/0!`
240    Div0,
241    /// `#VALUE!`
242    Value,
243    /// `#REF!`
244    Ref,
245    /// `#NAME?`
246    Name,
247    /// `#NUM!`
248    Num,
249    /// `#N/A`
250    NA,
251    /// `#GETTING_DATA`
252    GettingData,
253    /// `#SPILL!`
254    Spill,
255    /// `#CALC!`
256    Calc,
257    /// another error text, as written (`#BUSY!`, `#FIELD!` ...)
258    Other(String),
259}
260
261impl CellError {
262    /// The error as Excel writes it (`#N/A`).
263    pub fn text(&self) -> &str {
264        match self {
265            CellError::Null => "#NULL!",
266            CellError::Div0 => "#DIV/0!",
267            CellError::Value => "#VALUE!",
268            CellError::Ref => "#REF!",
269            CellError::Name => "#NAME?",
270            CellError::Num => "#NUM!",
271            CellError::NA => "#N/A",
272            CellError::GettingData => "#GETTING_DATA",
273            CellError::Spill => "#SPILL!",
274            CellError::Calc => "#CALC!",
275            CellError::Other(s) => s,
276        }
277    }
278    /// The error of a text (ASCII case-insensitive, white space at the ends ignored); any other
279    /// text is `Other` with the text as written.
280    pub fn parse(s: &str) -> CellError {
281        const ALL: [CellError; 10] = [
282            CellError::Null,
283            CellError::Div0,
284            CellError::Value,
285            CellError::Ref,
286            CellError::Name,
287            CellError::Num,
288            CellError::NA,
289            CellError::GettingData,
290            CellError::Spill,
291            CellError::Calc,
292        ];
293        let t = s.trim();
294        ALL.into_iter().find(|e| e.text().eq_ignore_ascii_case(t)).unwrap_or_else(|| CellError::Other(String::from(s)))
295    }
296}
297
298/// A cell position, 0-based (`B3` is row 2, column 1).
299#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
300pub struct CellRef {
301    /// the row, 0-based
302    pub row: u32,
303    /// the column, 0-based
304    pub col: u32,
305}
306
307impl CellRef {
308    /// A cell position from a 0-based row and column.
309    pub const fn new(row: u32, col: u32) -> CellRef {
310        CellRef { row, col }
311    }
312    /// The A1 form without `$` (`B3`).
313    pub fn a1(&self) -> String {
314        format!("{}{}", col_name(self.col), self.row as u64 + 1)
315    }
316}
317
318/// The letters of a 0-based column (0 is `A`, 27 is `AB`, 16383 is `XFD`).
319pub fn col_name(col: u32) -> String {
320    let mut n = col as u64 + 1;
321    let mut out = Vec::new();
322    while n > 0 {
323        n -= 1;
324        out.push(b'A' + (n % 26) as u8);
325        n /= 26;
326    }
327    out.reverse();
328    out.into_iter().map(char::from).collect()
329}
330
331// a column's letters (ASCII, either case) -> its 0-based index
332fn letters(s: &str) -> Option<u32> {
333    if s.is_empty() || !s.bytes().all(|c| c.is_ascii_alphabetic()) {
334        return None;
335    }
336    let mut v: u64 = 0;
337    for c in s.bytes() {
338        v = v * 26 + (c.to_ascii_uppercase() - b'A') as u64 + 1;
339        if v > u32::MAX as u64 + 1 {
340            return None;
341        }
342    }
343    Some((v - 1) as u32)
344}
345
346// a row's digits (1-based) -> its 0-based index
347fn row_digits(s: &str) -> Option<u32> {
348    if s.is_empty() || s.len() > 10 || !s.bytes().all(|c| c.is_ascii_digit()) {
349        return None;
350    }
351    let v: u64 = s.parse().ok()?;
352    if v == 0 || v > u32::MAX as u64 + 1 {
353        return None;
354    }
355    Some((v - 1) as u32)
356}
357
358/// A cell reference in A1 form: column letters (either case), then the 1-based row, each with
359/// an optional `$` (`B3`, `$B$3`, `b$3`); None for anything else.
360pub fn parse_ref(s: &str) -> Option<CellRef> {
361    let s = s.strip_prefix('$').unwrap_or(s);
362    let split = s.find(|c: char| !c.is_ascii_alphabetic())?;
363    let col = letters(&s[..split])?;
364    let rest = &s[split..];
365    let row = row_digits(rest.strip_prefix('$').unwrap_or(rest))?;
366    Some(CellRef { row, col })
367}
368
369/// A rectangle of cells, `first` and `last` included, on a sheet (an index into the workbook's
370/// sheets) or on no sheet in particular.
371#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
372pub struct Area {
373    /// the sheet, an index into `xlsx::Workbook::sheets`; None when the reference named none
374    pub sheet: Option<usize>,
375    /// the top left cell
376    pub first: CellRef,
377    /// the bottom right cell
378    pub last: CellRef,
379}
380
381impl Area {
382    /// The rectangle between two corners in any order.
383    pub fn new(sheet: Option<usize>, a: CellRef, b: CellRef) -> Area {
384        Area {
385            sheet,
386            first: CellRef { row: a.row.min(b.row), col: a.col.min(b.col) },
387            last: CellRef { row: a.row.max(b.row), col: a.col.max(b.col) },
388        }
389    }
390    /// Its rows.
391    pub fn rows(&self) -> u64 {
392        self.last.row as u64 - self.first.row as u64 + 1
393    }
394    /// Its columns.
395    pub fn cols(&self) -> u64 {
396        self.last.col as u64 - self.first.col as u64 + 1
397    }
398    /// Whether a cell lies inside.
399    pub fn contains(&self, at: CellRef) -> bool {
400        (self.first.row..=self.last.row).contains(&at.row) && (self.first.col..=self.last.col).contains(&at.col)
401    }
402    /// The A1 form without sheet and `$`: `B3` for one cell, `A1:C10` for more.
403    pub fn a1(&self) -> String {
404        if self.first == self.last { self.first.a1() } else { format!("{}:{}", self.first.a1(), self.last.a1()) }
405    }
406}
407
408/// A sheet name as a formula writes it before `!`: as it is when it is a plain name (letters,
409/// digits, `_`, `.`, not starting with a digit, no cell reference), else in single quotes with
410/// each `'` doubled (`'Tab 1'`, `'O''Brien'`).
411pub fn quote_sheet(name: &str) -> String {
412    let plain = !name.is_empty()
413        && name.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '.')
414        && !name.starts_with(|c: char| c.is_ascii_digit())
415        && parse_ref(name).is_none();
416    if plain { String::from(name) } else { format!("'{}'", name.replace('\'', "''")) }
417}
418
419// one side of a range: a cell, a whole column (letters) or a whole row (digits)
420#[derive(Clone, Copy, PartialEq)]
421enum Side {
422    Cell(CellRef),
423    Col(u32),
424    Row(u32),
425}
426
427fn side(s: &str) -> Option<Side> {
428    if let Some(c) = parse_ref(s) {
429        return Some(Side::Cell(c));
430    }
431    let t = s.strip_prefix('$').unwrap_or(s);
432    if let Some(c) = letters(t) {
433        return Some(Side::Col(c));
434    }
435    row_digits(t).map(Side::Row)
436}
437
438/// A reference to one rectangle as formulas and defined names write it: `B3`, `$A$1:$C$10`,
439/// whole columns `A:C` (rows 0 to MAX_ROWS - 1), whole rows `1:3` (columns 0 to MAX_COLS - 1),
440/// with an optional sheet before `!` (`Sheet1!A1`, `'Tab 1'!$A$1:$C$10`, `''` for a quote in a
441/// quoted name) and an optional leading `=`.  The sheet is resolved by name among `sheets`
442/// (ASCII and Unicode case-insensitive, as Excel compares sheet names); without a sheet the
443/// area's `sheet` is None.  None for an unknown sheet, a 3-D reference (`Sheet1:Sheet3!A1`), an
444/// external one (`[1]Sheet1!A1`), a union (`A1,B2`), a function or `#REF!`.
445pub fn parse_area<S: AsRef<str>>(text: &str, sheets: &[S]) -> Option<Area> {
446    parse_area_by(text, |fold| sheets.iter().position(|s| s.as_ref().to_lowercase() == fold))
447}
448
449// parse_area with the sheet found by `find`, which gets the name in lower case (a workbook's own
450// map of its sheets: no search through all of them for each name)
451pub(crate) fn parse_area_by(text: &str, find: impl Fn(&str) -> Option<usize>) -> Option<Area> {
452    let t = text.trim();
453    let t = t.strip_prefix('=').unwrap_or(t).trim();
454    let (sheet, rest) = if let Some(q) = t.strip_prefix('\'') {
455        // a quoted name: '' is a quote, a single ' ends it
456        let mut name = String::new();
457        let mut it = q.char_indices();
458        let end = loop {
459            let (i, c) = it.next()?;
460            if c == '\'' {
461                if q[i + 1..].starts_with('\'') {
462                    name.push('\'');
463                    it.next();
464                } else {
465                    break i + 1;
466                }
467            } else {
468                name.push(c);
469            }
470        };
471        (Some(name), q[end..].strip_prefix('!')?)
472    } else if let Some((name, rest)) = t.split_once('!') {
473        (Some(String::from(name)), rest)
474    } else {
475        (None, t)
476    };
477    let sheet = match sheet {
478        Some(name) => {
479            if name.is_empty() || name.contains(['[', ']', ':']) {
480                return None;
481            }
482            Some(find(&name.to_lowercase())?)
483        }
484        None => None,
485    };
486    let (a, b) = match rest.split_once(':') {
487        Some((a, b)) => (side(a)?, side(b)?),
488        None => match side(rest)? {
489            Side::Cell(c) => (Side::Cell(c), Side::Cell(c)),
490            _ => return None,
491        },
492    };
493    let (first, last) = match (a, b) {
494        (Side::Cell(x), Side::Cell(y)) => (x, y),
495        (Side::Col(x), Side::Col(y)) => (CellRef::new(0, x), CellRef::new(MAX_ROWS - 1, y)),
496        (Side::Row(x), Side::Row(y)) => (CellRef::new(x, 0), CellRef::new(y, MAX_COLS - 1)),
497        _ => return None,
498    };
499    Some(Area::new(sheet, first, last))
500}
501
502/// A rectangular table: every row has `columns.len()` values.
503#[derive(Clone, Debug, Default, PartialEq)]
504pub struct Table {
505    /// the column names: trimmed, an empty one is `F<n>` (n the 1-based column, as Excel's OLE
506    /// DB driver names them), a repeated one gets a number (`Name`, `Name1`, `Name2`; compared
507    /// case-insensitively); without a header row all are `F1` ... `Fn`
508    pub columns: Vec<String>,
509    /// the rows of values
510    pub rows: Vec<Vec<Value>>,
511}
512
513impl Table {
514    /// The index of a column by name (case-insensitive).
515    pub fn column(&self, name: &str) -> Option<usize> {
516        let fold = name.to_lowercase();
517        self.columns.iter().position(|c| c.to_lowercase() == fold)
518    }
519}
520
521// the column names of a header row (see Table::columns)
522pub(crate) fn column_names(raw: Vec<String>) -> Vec<String> {
523    let mut out: Vec<String> = Vec::with_capacity(raw.len());
524    // folded names taken -> the next number to try for that base (no quadratic search)
525    let mut taken: BTreeMap<String, u32> = BTreeMap::new();
526    for (i, n) in raw.into_iter().enumerate() {
527        let t = n.trim();
528        let base = if t.is_empty() { format!("F{}", i + 1) } else { t.to_string() };
529        let mut name = base.clone();
530        let fold = base.to_lowercase();
531        if taken.contains_key(&fold) {
532            let mut k = taken.get(&fold).copied().unwrap_or(1);
533            loop {
534                name = format!("{base}{k}");
535                k += 1;
536                if !taken.contains_key(&name.to_lowercase()) {
537                    break;
538                }
539            }
540            taken.insert(fold, k);
541        }
542        taken.entry(name.to_lowercase()).or_insert(1);
543        out.push(name);
544    }
545    out
546}
547
548// the names F1 .. Fn of a table without a header row
549pub(crate) fn plain_names(n: usize) -> Vec<String> {
550    (1..=n).map(|i| format!("F{i}")).collect()
551}
552
553// the test binary of the unit tests: plat's start of a std program refers to the jfgui_main a
554// program defines
555#[cfg(test)]
556rt::test_main!();
557
558#[cfg(test)]
559mod tests;
560#[cfg(test)]
561mod tests_write;