JFLib

sheet_io#

XLSX and CSV import: workbooks and delimited text as typed tables -- crate root lib/sheet_io/src/lib.rs

sheet_io -- XLSX and CSV import and export: workbooks and delimited text as typed tables
(JFDiagrammer JD18, FEATURES.md IM-05 / IM-10, decision F6: "CSV und .xlsx in P2 mit XLSX-Leser
in JFLib"; the writers JD19, EX-12 shape reports and EX-16 data export as CSV / .xlsx)

  xlsx::Workbook::open(bytes, Limits) -> Workbook     the workbook part, its relationships,
       the shared strings and the styles (which number formats are dates); not the sheets yet
  wb.sheets() / names() / date1904()                   sheets with state and kind, defined
       names (global and sheet-local, _xlnm.* included) and tables (ListObjects) as names
  wb.sheet(i) -> Grid                                  one worksheet, sparse: stored values
       (a formula's cached result, formulas are never evaluated)
  wb.table(&area, header) / wb.sheet_table(i, header) -> Table   a rectangle as a table
  csv::read(bytes, &Options) -> Csv                    RFC 4180 and what Excel writes: the
       encoding (BOM, UTF-8, else Windows-1252) and the delimiter (; , TAB |) detected
  csv::to_table(&csv, header, infer, cells) -> Table   with numbers, booleans and dates typed
  xlsx::write(&BookOut, &WriteOptions) -> Vec<u8>      typed rows as a workbook Excel opens
       without repair (xlsx_write.rs): shared strings, dates with Excel's number formats, a
       bold and frozen header, column widths, a filter; Excel's limits as errors
  csv::write(rows, &WriteOptions) / csv::write_table -> Vec<u8>   delimiter, line end,
       encoding (UTF-8 with or without BOM, UTF-16, Windows-1252), decimal comma, a guard
       against formula injection
  Value, CellError, CellRef / parse_ref / col_name, Area / parse_area, civil / serial

What is written reads back with the readers here as it was written (the tests check it), with
the exceptions each writer names: Excel's newer errors and dates it cannot show become texts,
NaN and infinities #NUM!; CSV has no types at all.  Writing is deterministic (no time stamps,
the same rows give the same bytes) and bounded (xlsx::WriteOptions, csv::WriteOptions::max_bytes).

Why a crate of its own: one crate per foreign format family, like dxf, gltf and pdf.  Not
doc_io: that is jfWord's document model, and every user of a spreadsheet reader would pull in
doc_core, doc_layout and text.  Not archive: that holds containers (ZIP, OPC), not their
content.  Not base: base::encoding is strict Unicode by design ("no guessed legacy code
pages"), while CSV files from Excel come in Windows-1252.  CSV sits next to XLSX because both
deliver the same typed Table.

Every file is untrusted input: the ZIP container is bounded before anything is inflated
(archive::Limits, the compression ratio included), the XML reader (formats::xml::Reader) takes
no DTD and no entity but the five predefined ones and bounds the nesting, rows, columns, cells,
shared strings and their bytes, sheets and names are bounded, no size a file advertises
(<dimension>, count, uniqueCount) sizes an allocation, cells are stored sparsely, nothing
recurses, a CSV table pads its rows only within a count of cells.  A broken file is an error,
never a panic.

sheet_io crate root#

Re-exports: datetime::Civil

/// Excel's rows per sheet: the last row of a whole-column reference (`A:C`)
MAX_ROWS: u32 = 1_048_576
/// Excel's columns per sheet (A to XFD): the last column of a whole-row reference (`1:3`)
MAX_COLS: u32 = 16_384
  • enum Value A cell value with its type.

    Date holds an OLE Automation date, as Visio and Excel's 1900 date system use it: days since 1899-12-30, the fraction is the time of day (values are taken as linear, also below zero). Values from 0 to below 1 are a time of day without a date. The XLSX reader converts the 1904 date system and Excel's fake 1900-02-29 (see xlsx).

    • Empty -- no value (an empty cell, a formula without a cached result)
    • Number(f64) -- a number
    • Text(String) -- a text
    • Bool(bool) -- TRUE or FALSE
    • Date(f64) -- a date and time as an OLE Automation date (days since 1899-12-30)
    • Error(CellError) -- an error value of a cell (#N/A, #DIV/0! ...)

impl Value

  • fn text(&self) -> String The display form: numbers as the shortest text that reads back (base::f64_format, -0 as 0), dates as ISO 8601 (2026-11-23, 2026-11-23 14:05:00, a time of day alone as 14:05:00, milliseconds only when there are some: 14:05:00.250), booleans as TRUE / FALSE, errors as Excel writes them (#N/A), Empty as "".

  • fn is_empty(&self) -> bool Whether this is Empty.

  • fn number(&self) -> Option<f64> The number of a Number or a Date (its serial), else None.

  • fn civil(serial: f64) -> Option<Civil> The date and time of an OLE Automation date (days since 1899-12-30, the fraction the time of day), rounded to the millisecond; None for NaN, infinities and values beyond 10^8 days.

  • fn serial(c: &Civil) -> f64 The OLE Automation date of a date and time (days since 1899-12-30, the fraction the time of day); civil reads it back.

  • enum CellError An error value of a cell.

    • Null -- #NULL!
    • Div0 -- #DIV/0!
    • Value -- #VALUE!
    • Ref -- #REF!
    • Name -- #NAME?
    • Num -- #NUM!
    • NA -- #N/A
    • GettingData -- #GETTING_DATA
    • Spill -- #SPILL!
    • Calc -- #CALC!
    • Other(String) -- another error text, as written (#BUSY!, #FIELD! ...)

impl CellError

  • fn text(&self) -> &str The error as Excel writes it (#N/A).

  • fn parse(s: &str) -> CellError The error of a text (ASCII case-insensitive, white space at the ends ignored); any other text is Other with the text as written.

  • struct CellRef A cell position, 0-based (B3 is row 2, column 1).

    • row: u32 -- the row, 0-based
    • col: u32 -- the column, 0-based

impl CellRef

  • const fn new(row: u32, col: u32) -> CellRef A cell position from a 0-based row and column.

  • fn a1(&self) -> String The A1 form without $ (B3).

  • fn col_name(col: u32) -> String The letters of a 0-based column (0 is A, 27 is AB, 16383 is XFD).

  • fn parse_ref(s: &str) -> Option<CellRef> A cell reference in A1 form: column letters (either case), then the 1-based row, each with an optional $ (B3, $B$3, b$3); None for anything else.

  • struct Area A rectangle of cells, first and last included, on a sheet (an index into the workbook's sheets) or on no sheet in particular.

    • sheet: Option<usize> -- the sheet, an index into xlsx::Workbook::sheets; None when the reference named none
    • first: CellRef -- the top left cell
    • last: CellRef -- the bottom right cell

impl Area

  • fn new(sheet: Option<usize>, a: CellRef, b: CellRef) -> Area The rectangle between two corners in any order.

  • fn rows(&self) -> u64 Its rows.

  • fn cols(&self) -> u64 Its columns.

  • fn contains(&self, at: CellRef) -> bool Whether a cell lies inside.

  • fn a1(&self) -> String The A1 form without sheet and $: B3 for one cell, A1:C10 for more.

  • fn quote_sheet(name: &str) -> String A sheet name as a formula writes it before !: as it is when it is a plain name (letters, digits, _, ., not starting with a digit, no cell reference), else in single quotes with each ' doubled ('Tab 1', 'O''Brien').

  • fn parse_area<S: AsRef<str>>(text: &str, sheets: &[S]) -> Option<Area> A reference to one rectangle as formulas and defined names write it: B3, $A$1:$C$10, whole columns A:C (rows 0 to MAX_ROWS - 1), whole rows 1:3 (columns 0 to MAX_COLS - 1), with an optional sheet before ! (Sheet1!A1, 'Tab 1'!$A$1:$C$10, '' for a quote in a quoted name) and an optional leading =. The sheet is resolved by name among sheets (ASCII and Unicode case-insensitive, as Excel compares sheet names); without a sheet the area's sheet is None. None for an unknown sheet, a 3-D reference (Sheet1:Sheet3!A1), an external one ([1]Sheet1!A1), a union (A1,B2), a function or #REF!.

  • struct Table A rectangular table: every row has columns.len() values.

    • columns: Vec<String> -- the column names: trimmed, an empty one is F<n> (n the 1-based column, as Excel's OLE DB driver names them), a repeated one gets a number (Name, Name1, Name2; compared case-insensitively); without a header row all are F1 ... Fn
    • rows: Vec<Vec<Value>> -- the rows of values

impl Table

  • fn column(&self, name: &str) -> Option<usize> The index of a column by name (case-insensitive).

sheet_io/src/csv.rs#

Source: lib/sheet_io/src/csv.rs

csv -- delimited text: RFC 4180 and what Excel writes

  read(bytes, &Options) -> Csv         decode, find the delimiter, split into records
  decode(bytes) -> (String, Encoding)  a BOM decides; else valid UTF-8; else Windows-1252
  detect_delimiter(text) -> u8         ; , TAB or |
  to_table(&csv, header, infer, cells) -> Table   numbers, booleans and dates typed on request
  write(rows, &WriteOptions) / write_table(&table, &WriteOptions) -> Vec<u8>   the other way
       (JD19, FEATURES.md EX-12 / EX-16): delimiter, line end, encoding, decimal separator,
       an optional guard against formula injection; what is written reads back with read

The grammar: a field in quotes may hold the delimiter, line breaks and "" for a quote; records
end with CR LF, LF or CR; the last record may end without a line break, and a line break at
the very end starts no further record; an empty line is a record of one empty field.  Lenient
where Excel is: a quote inside a field that does not start with one is kept as it is (ab"cd),
text after a closing quote is kept and the field goes on to the next delimiter ("ab"cd is
abcd), a quote left open runs to the end of the text.  Line breaks inside quotes are read as
LF (CR LF and CR too), as Excel keeps them in a cell.  A first line "sep=;" (Excel's hint) sets
the delimiter unless Options gives one, and is never a record.

Encodings: a BOM (UTF-8, UTF-16 LE / BE: Excel's "Unicode text" is UTF-16 LE with TAB),
UTF-16 without a BOM when every second byte of the start is zero, valid UTF-8, else
Windows-1252 as WHATWG defines it (0x80 is the euro sign; the five bytes it leaves open are the
C1 controls of the same number).  Decoding never fails: a forced encoding turns what it cannot
read into U+FFFD.

Untrusted input: CsvLimits bounds the bytes, records, fields of a record, fields in all and the
bytes of one field; nothing recurses.
  • enum Encoding The text encoding of a CSV file.

    • Utf8 -- UTF-8 without a byte-order mark
    • Utf8Bom -- UTF-8 with a byte-order mark (Excel's "CSV UTF-8")
    • Utf16Le -- UTF-16 little-endian (Excel's "Unicode text", with BOM)
    • Utf16Be -- UTF-16 big-endian
    • Windows1252 -- Windows-1252, the ANSI code page of Western European Windows (Excel's plain "CSV")
  • struct CsvLimits What a CSV file may hold. The default: 256 MiB, two million records, Excel's 16384 fields a record, eight million fields in all, 1 MiB a field.

    • bytes: usize -- bytes of the file
    • records: usize -- records (lines)
    • fields: usize -- fields of one record
    • cells: usize -- fields of all records together (each costs memory even when empty)
    • field_bytes: usize -- bytes of one field (UTF-8)

impl CsvLimits

  • const DEFAULT: CsvLimits = CsvLimits { bytes: 256 << 20, records: 2_000_000, fields: ... The default limits (see CsvLimits).

  • struct Options How a CSV file is read.

    • delimiter: Option<u8> -- the delimiter (an ASCII byte); None: a sep= line, else detect_delimiter
    • encoding: Option<Encoding> -- the encoding; None: decode detects it
    • quote: u8 -- the quote character (an ASCII byte), " as a rule
    • limits: CsvLimits -- the bounds of the file

impl Options

  • const DEFAULT: Options = Options { delimiter: None, encoding: None, quote: b'"', l ... Detect delimiter and encoding, quote with ", the default limits.

  • struct Csv A CSV file read: its records of fields, as text.

    • delimiter: u8 -- the delimiter used
    • encoding: Encoding -- the encoding read
    • records: Vec<Vec<String>> -- the records, each a list of fields (records may differ in length)
  • enum Error Why a CSV file was not read.

    • Limit(&'static str) -- over a limit: the name of the field of CsvLimits
    • Options -- a delimiter or quote that is no ASCII byte, or both the same

impl Error

  • fn text(&self) -> String The error as a sentence in English.

  • fn decode(bytes: &[u8]) -> (String, Encoding) Decode a CSV file: a byte-order mark decides (UTF-8, UTF-16 LE, UTF-16 BE); else UTF-16 when every second byte of the start is zero; else UTF-8 when it is valid; else Windows-1252. The BOM is not part of the text.

  • fn decode_as(bytes: &[u8], encoding: Encoding) -> String Decode in a given encoding (a matching BOM is skipped; what is not valid becomes U+FFFD).

  • fn detect_delimiter(text: &str) -> u8 The delimiter of a CSV text: a first line sep=X names it; else, over the first 20 non-empty records (quotes respected, so a quoted delimiter or line break does not count), a candidate that occurs the same number of times, at least once, in every one of them wins, in the order TAB, ;, ,, | (a TAB is rarely data; German Excel writes ; and , in its numbers, so ; goes before ,); when none is that consistent, the one found in the most records (the same order breaks ties); , when there is none at all.

  • fn read(bytes: &[u8], opts: &Options) -> Result<Csv, Error> Read a CSV file (see the module's head for the grammar).

  • fn to_table(csv: &Csv, header: bool, infer: bool, cells: usize) -> Result<Table, Error> The records as a Table. header: the first record names the columns (see Table::columns). The table is as wide as the longest record: shorter records are padded with Empty, nothing is cut off; with a header, columns past it that are empty in every record are dropped (a delimiter at the end of the data lines). Empty records at the end are dropped. An empty field is Empty. infer: the other fields are typed, else they are Text:

    • numbers: 1.5, -3, +2, .5, 1e3; with ; as delimiter also German ones, 1,5,
    `1.234,5`, `-1.234.567,89` (a field with a comma reads `.` as the thousands separator, in
    groups of three; without a comma `1.234` is 1.234).  A number with a leading zero (`007`,
    `0123`) stays Text: it is an identifier more often than not.  White space at the ends is
    ignored.
    • booleans: TRUE, FALSE, WAHR, FALSCH in any case
    • dates: ISO 8601 (2026-11-23, 2026-11-23T14:05, 2026-11-23 14:05:00) and German
    `d.m.yyyy` (`23.11.2026`, `1.2.2026 14:05`) as `Value::Date`

    At most cells values (rows times the width, the padding included), else Limit("cells"): one long record over many short ones pads them all (CsvLimits::cells bounds only the fields read).

  • enum LineEnd How the lines of a CSV file written end.

    • CrLf -- CR LF, as Excel writes and RFC 4180 says
    • Lf -- LF, as Unix tools write
  • struct WriteOptions How a CSV file is written (write, write_table).

    • delimiter: u8 -- , ; TAB or |: the delimiters detect_delimiter finds again
    • line_end: LineEnd -- the line end
    • encoding: Encoding -- the encoding: UTF-8 with BOM by default (Excel reads UTF-8 without BOM in the ANSI code page); UTF-16 is written with its BOM; Windows-1252 refuses a character it lacks (WriteError::Unmappable) rather than writing ? for it
    • decimal: u8 -- the decimal separator of numbers: ., or , as German Excel writes them (then the delimiter cannot be ,; to_table reads them back with ;)
    • guard_formulas: bool -- a text starting with = + - @ TAB or CR gets a leading ', so a spreadsheet opening the file does not run it as a formula (CSV injection). Off by default: it changes the data (every program but Excel shows the ', and Excel shows it too in a cell read from CSV), so the application decides, by who opens the file. Only texts: a Number -5 stays -5.
    • max_bytes: usize -- the most bytes of the file written (WriteError::Limit("max_bytes"))

impl WriteOptions

  • const DEFAULT: WriteOptions = WriteOptions { delimiter: b',', line_end: LineEnd::CrLf, ... ,, CR LF, UTF-8 with BOM, . as the decimal separator, no formula guard, up to CsvLimits::DEFAULT.bytes (what read takes by default).

  • const GERMAN: WriteOptions = WriteOptions { delimiter: b';', decimal: b',', ..WriteOpt ... As German Excel opens a CSV file with a double click: ; and a decimal comma; else DEFAULT.

  • enum WriteError Why a CSV file was not written.

    • Options -- a delimiter other than , ; TAB |, a decimal separator other than . and ,, or , as both
    • Unmappable { record: usize, field: usize, ch: char, } -- a character the encoding (Windows-1252) does not have
    • Limit(&'static str) -- over a limit: the name of the field of WriteOptions

impl WriteError

  • fn text(&self) -> String The error as a sentence in English.

  • fn write(rows: &[Vec<Value>], opts: &WriteOptions) -> Result<Vec<u8>, WriteError> Write rows as a CSV file: one record a row (rows may differ in length), each ending with the line end, the last one too. Fields: a Number as the shortest text that reads back with the decimal separator of the options, no thousands separators (-0 as 0); NaN and the infinities as #NUM! (as in xlsx::write); a Date as ISO 8601 text (Value::text: 2026-11-24, 2026-11-24 14:05:30, a time alone 14:05:30, which to_table keeps as text); a Bool as TRUE / FALSE; an Error as Excel writes it (#N/A); Empty as an empty field; a Text as it is. A field is quoted when it holds the delimiter, a quote, CR or LF, starts or ends with a space or TAB, or is a first field sep=...; a quote in it is doubled. CSV has no types: read and to_table give a Text that looks like a number back as a Number.

  • fn write_table(table: &Table, opts: &WriteOptions) -> Result<Vec<u8>, WriteError> Write a table as a CSV file: a header record of its column names (texts; none for a table without columns), then its rows (see write).

sheet_io/src/xlsx.rs#

Source: lib/sheet_io/src/xlsx.rs

xlsx -- Office Open XML workbooks: .xlsx, .xlsm (the macros are never read), .xltx, .xltm, in
transitional and strict OOXML

  Workbook::open(bytes, Limits)      the package (archive::opc), the workbook part found through
                                     the package's officeDocument relationship, the sheets
                                     through the workbook's relationships (never by guessing
                                     paths), the shared strings and the styles; tables
                                     (ListObjects) of the worksheets as names
  wb.sheet(i) -> Grid                one worksheet part, read when asked for
  wb.table(&area, header)            a rectangle as a Table; wb.sheet_table(i, header) the used
                                     range of a sheet

Values: the stored ones.  Formulas are never evaluated: a formula's cached <v> counts, a
formula without one is Empty.  Cell types s (shared string), str (a formula's text),
inlineStr, b, e, n and d (ISO 8601 text); a number is a Date when its style's number format is
one: the built-in ids 14-22, 27-36, 45-47, 50-58 (the last two groups are dates in Excel's
East Asian locales and Excel treats them so everywhere), or a custom code with a date or time
token (d m y h s e g) outside quotes, brackets and the escapes \x _x *x; [h] [mm] [ss] make an
elapsed time.

Dates become OLE Automation dates (days since 1899-12-30, as Visio uses them):
  1900 system   serials from 1 to below 60 (1900-01-01 .. 1900-02-28) move one day up, Excel
                counts the 1900-02-29 that never was; serial 60 itself, that day, reads as
                1900-02-28 like the serial before it; from 61 (1900-03-01) on serials are OLE
                dates already; from 0 to below 1 (Excel's "1900-01-00") a time of day
                without a date, as it is
  1904 system   (workbookPr date1904) serial + 1462; under a format of a time of day alone
                (h:mm) a value from 0 to below 1 stays a time without a date
  both          an elapsed-time format keeps the value as it is (1.5 = 36 hours)

Text: shared strings with rich runs (<r><t>), phonetic runs (<rPh>) left out; a <t> without
xml:space="preserve" (on it or an element around it) loses its white space at either end, as
in Excel; _xHHHH_ is decoded (Excel's escape of control characters; _x005F_ is "_", so
"_x005F_x0041_" reads "_x0041_").

Positions: a row without r follows the previous row, a cell without r the previous cell of its
row (the first at column A).  Rows and cells out of order are sorted; a cell given twice: the
last one wins.  Only cells with a value are kept (sparse): one cell at A1 and one at XFD1048576
are two cells.

Untrusted input: the ZIP within Limits::archive (the compression ratio checked before
inflating), the XML without DTD and with the nesting bounded (Limits::depth), the rows,
columns, cells, shared strings and their bytes, sheets and names bounded; <dimension>, count
and uniqueCount are never read; a shared-string index out of range is Invalid.  Names find
their sheet in a map, each worksheet part and each table part is read once.
  • struct Limits What a workbook may hold. The default is generous for real workbooks: Excel's own sheet size, four million cells a sheet, two million shared strings of 256 MiB, ZIP parts up to 512 MiB and a compression ratio of at most 200 for parts over 1 MiB.
    • archive: archive::Limits -- the ZIP container: parts, sizes, the compression ratio (checked before inflating)
    • rows: u32 -- rows of a sheet: a row index from 0 to rows - 1
    • cols: u32 -- columns of a sheet: a column index from 0 to cols - 1
    • cells: usize -- cells kept of one sheet (those with a value), and values of one Table
    • strings: usize -- entries of the shared-string table
    • string_bytes: usize -- bytes of the shared strings together, and of the texts of one sheet together
    • depth: usize -- nesting of the XML elements of a part
    • sheets: usize -- sheets the workbook lists
    • names: usize -- defined names and tables together

impl Limits

  • const DEFAULT: Limits = Limits { archive: archive::Limits { entries: 10_000, part ... The default limits (see Limits).

  • enum Error Why a workbook or a sheet was not read.

    • Archive(archive::Error) -- the ZIP container (archive's reader), its limits included
    • Package(opc::Error) -- the OPC package: content types, relationships, part names (archive::opc)
    • NotXlsx -- not an OOXML workbook: no ZIP, no officeDocument relationship, another main part (a document, a binary .xlsb)
    • Xml { part: String, offset: usize, what: &'static str, } -- a part's XML is not well-formed or uses what the reader refuses (a DOCTYPE)
    • Limit(&'static str) -- over a limit: the name of the field of Limits
    • Missing(&'static str) -- something the workbook needs is not there
    • Invalid(&'static str) -- a value or structure that breaks the format

impl Error

  • fn text(&self) -> String The error as a sentence in English.

  • enum SheetState Whether a sheet is shown.

    • Visible -- shown as a tab
    • Hidden -- hidden; the user can show it again
    • VeryHidden -- hidden; only a macro or the file can show it again
  • enum SheetKind What a sheet holds.

    • Worksheet -- cells
    • Chartsheet -- one chart, no cells (sheet gives an empty Grid)
    • Other -- a dialog or macro sheet, or a sheet whose part is missing (sheet gives an empty Grid)
  • struct SheetInfo A sheet of the workbook, in tab order.

    • name: String -- the tab's name
    • state: SheetState -- shown or hidden
    • kind: SheetKind -- worksheet, chartsheet or other
  • struct DefinedName A defined name of the workbook, or a table (ListObject) of a worksheet.

    • name: String -- the name as written (Daten, _xlnm.Print_Area; a table's display name)
    • scope: Option<usize> -- the sheet a sheet-local name belongs to (localSheetId); None for a global name
    • hidden: bool -- hidden from the user (hidden="1")
    • formula: String -- the formula as written ('Tab 1'!$A$1:$C$10); for a table its sheet and range
    • area: Option<Area> -- the rectangle when the formula is one (parse_area); a reference without a sheet takes the sheet of the name's scope. A table's area leaves out its totals row.
    • table: bool -- a table (ListObject, xl/tables/tableN.xml) rather than a defined name

impl DefinedName

  • fn builtin(&self) -> bool Whether this is one of Excel's built-in names (_xlnm.Print_Area, _xlnm._FilterDatabase ...).

  • struct Grid The cells of one sheet that hold a value, sparse: rows in ascending order, each with its cells (column, value) in ascending order.

impl Grid

  • fn sheet(&self) -> usize The sheet's index.

  • fn get(&self, row: u32, col: u32) -> &Value The value of a cell (0-based); Empty where there is none.

  • fn row(&self, row: u32) -> &[(u32, Value)] The cells of a row with a value: (column, value) in ascending columns.

  • fn rows(&self) -> impl Iterator<Item = (u32, &[(u32, Value)])> The rows with a value, ascending: (row, its cells).

  • fn cells(&self) -> usize The cells with a value.

  • fn is_empty(&self) -> bool Whether no cell has a value.

  • fn used(&self) -> Option<Area> The used range: from the first to the last row and column that hold a value; None for an empty sheet.

  • fn table(&self, area: &Area, header: bool, cells: usize) -> Result<Table, Error> A rectangle of this grid as a Table (header: its first row names the columns). Rows and columns past the used range are left out (a whole-column reference gives the rows that hold data), the area's first row and column stay; at most cells values (rows times columns), else Limit("cells"). The area's sheet is not looked at.

  • struct Workbook An XLSX workbook: its sheets, names, shared strings and styles; the sheets themselves are read when asked for.

impl Workbook

  • fn open(bytes: &[u8], limits: Limits) -> Result<Workbook, Error> Read a workbook within limits: the package, workbook.xml, its relationships, the shared strings, the styles and the tables of the worksheets; not the cells.
  • fn sheets(&self) -> &[SheetInfo] The sheets in tab order.
  • fn names(&self) -> &[DefinedName] The defined names in file order (built-in _xlnm.* ones included, see DefinedName::builtin), then the tables of the worksheets (DefinedName::table).
  • fn date1904(&self) -> bool Whether the workbook counts dates from 1904 (its serials are converted either way).
  • fn sheet_by_name(&self, name: &str) -> Option<usize> The index of a sheet by name (ASCII and Unicode case-insensitive, as Excel compares them).
  • fn area(&self, text: &str) -> Option<Area> parse_area with this workbook's sheet names.
  • fn sheet(&self, index: usize) -> Result<Grid, Error> Read one sheet: its stored values. A chartsheet or another kind of sheet gives an empty Grid; Missing("sheet") for an index past the sheets.
  • fn table(&self, area: &Area, header: bool) -> Result<Table, Error> A rectangle of a sheet as a Table (header: its first row names the columns, see Table::columns); see Grid::table for how it is cut to the used range. The area needs a sheet (Missing("the area's sheet") without one); at most Limits::cells values.
  • fn sheet_table(&self, index: usize, header: bool) -> Result<Table, Error> The used range of a sheet as a Table (from the first to the last row and column that hold a value); an empty sheet gives an empty Table.

sheet_io/src/xlsx_write.rs#

Source: lib/sheet_io/src/xlsx_write.rs

xlsx_write -- typed rows as an XLSX workbook (JFDiagrammer JD19, FEATURES.md EX-12 "Shape-Bericht
exportieren ... als Excel-Tabelle (.xlsx)", EX-16 "Daten exportieren (Inventar)"); re-exported
as sheet_io::xlsx::{write, BookOut, SheetOut, WriteOptions, WriteError}

  xlsx::write(&BookOut, &WriteOptions) -> Vec<u8>     the workbook as an OPC package
  BookOut { sheets }                                  the sheets in tab order, the first active
  SheetOut { name, rows, header_rows, widths, autofilter }
  SheetOut::new(name, rows) / SheetOut::from_table(name, &Table)  (the column names as a header
                                                      row: bold, kept in view)

Values, as xlsx::Workbook reads them back:
  Number   the shortest text that reads back (-0 as 0).  NaN and the infinities, which Excel
           cannot store, become the error #NUM! (what Excel shows for a number out of its
           range) instead of refusing the whole workbook for one cell
  Text     a shared string (equal texts stored once); "" is no cell.  The characters XML
           cannot hold (controls but TAB and LF; U+FFFE, U+FFFF) and CR are Excel's escape
           _xHHHH_, and a "_" that would read as the start of one (_x and four hex digits) is
           _x005F_, so Excel and the reader give back the text as it was; white space at either
           end is kept (xml:space="preserve")
  Bool     t="b"
  Error    t="e" for the seven errors of ECMA-376 (#NULL! #DIV/0! #VALUE! #REF! #NAME? #NUM!
           #N/A).  Excel stores the newer ones (#SPILL!, #CALC!, #GETTING_DATA, ...) as #VALUE!
           with rich-value metadata, so they are written as a text of the same letters
  Date     a serial of Excel's 1900 date system: OLE dates from 1900-01-01 to 1900-02-28 one
           day down (Excel counts a 1900-02-29 that never was; the reader moves them up again),
           a time of day alone (0 to below 1) as it is.  The number format is the one Excel
           picks when a date is typed in: the viewer's short date (built-in 14) without a time
           part, short date and h:mm (22) with one (seconds stay in the value, unshown), h:mm:ss
           (21) for a time alone.  A date Excel cannot show (before 1900-01-01, after
           9999-12-31) is written as its text (Value::text); NaN and infinities as #NUM!
  Empty    no cell
No formula is ever written: a text starting with "=" stays a text, so a workbook written here
carries no formula injection (csv::WriteOptions::guard_formulas is CSV's matter).

Excel's limits are errors (WriteError), never a file Excel has to repair: values only up to
row 1 048 576 and column XFD (Empty past them is fine), texts up to 32 767 characters (UTF-16
units, as Excel counts them), sheet names of 1 to 31 characters without [ ] : * ? / \ and
control characters, not starting or ending with ', not "History" (Excel's change history),
unique case-insensitively; at least one sheet; column widths 0 to 255.  WriteOptions bounds the
cells and the bytes of XML, checked cell by cell, so a caller bounds the memory writing takes,
and sets the DEFLATE level (6; 1 is several times faster on large sheets).

The package: [Content_Types].xml, _rels/.rels, xl/workbook.xml (bookViews, sheets, a hidden
_xlnm._FilterDatabase name per filter, as Excel writes them), its relationships,
xl/worksheets/sheetN.xml (dimension, sheetViews with a frozen pane below the header rows,
sheetFormatPr, cols, sheetData, autoFilter, pageMargins), xl/styles.xml (fonts regular and
bold, the fills none and gray125 Excel expects first, one border, the style xf, eight cell xfs:
general, date, date and time, time, each regular and bold; the Normal cell style),
xl/sharedStrings.xml when there are texts, docProps/core.xml (empty: no author, no time) and
docProps/app.xml.  Children come in the order of the schema (ECMA-376 Part 1): Excel repairs
a part whose elements come in another.  Deterministic: no time stamps, archive's fixed ZIP
date: the same book and options give the same bytes.

Column widths: a given one as it is; else from the longest line among the column's values (an
East Asian wide character counts twice, a header cell a tenth more for bold) plus a margin,
from Excel's default 8.43 up to 80.
/// Excel's most characters in one cell (UTF-16 units, as Excel counts them)
MAX_TEXT: usize = 32_767
/// Excel's most characters of a sheet name (UTF-16 units)
MAX_SHEET_NAME: usize = 31
  • struct BookOut A workbook to write: its sheets in tab order, the first one the active tab.

    • sheets: Vec<SheetOut> -- the sheets, at least one
  • struct SheetOut One worksheet to write.

    • name: String -- the tab's name: 1 to 31 characters, none of [ ] : * ? / \ and no control character, not starting or ending with ', not "History", unlike the other sheets' names in any case
    • rows: Vec<Vec<Value>> -- the rows from row 1 on, each from column A on; rows may differ in length, Empty (and an empty Text) is no cell
    • header_rows: u32 -- how many of the first rows are a header: bold and kept in view (a frozen pane below them)
    • widths: Vec<Option<f64>> -- column widths from column A on, in characters of the default font's digits as Excel counts them (0 to 255; 0 hides the column); None, or no entry, estimates the width from the column's values
    • autofilter: bool -- filter buttons on the last header row over the columns that hold values (needs header_rows of 1 or more)

impl SheetOut

  • fn new(name: &str, rows: Vec<Vec<Value>>) -> SheetOut A sheet of rows without header, filter or given widths.

  • fn from_table(name: &str, table: &Table) -> SheetOut A table as a sheet: a header row of its column names (bold, kept in view), then its rows; no filter (set autofilter), the widths estimated.

  • struct WriteOptions How a workbook is written and what writing may take. The default: DEFLATE level 6, ten million cells, 1 GiB of XML.

    • level: u8 -- DEFLATE level 1 (fastest) to 9 (smallest), 0: stored; 6 by default, as diagram_io's vsdx::write. For a large sheet 1 is several times faster and the file about a sixth larger
    • cells: usize -- cells with a value in all sheets together
    • bytes: usize -- bytes of the XML of all parts together, before compression: with the rows given, what bounds the memory writing takes (the compressed package comes on top)

impl WriteOptions

  • const DEFAULT: WriteOptions = WriteOptions { level: 6, cells: 10_000_000, bytes: 1 << 30 } The default (see WriteOptions).

  • enum WriteError Why a workbook was not written.

    • NoSheets -- a workbook without sheets (Excel needs one)
    • SheetName { sheet: usize, what: &'static str, } -- a sheet's name Excel does not take (see SheetOut::name)
    • Sheet { sheet: usize, what: &'static str, } -- a sheet's settings: header rows past Excel's last row, a filter without a header row, a width outside 0 to 255, widths past column XFD
    • Cell { sheet: usize, at: CellRef, what: &'static str, } -- a value Excel cannot hold where it stands: past row 1 048 576 or column XFD, a text over 32 767 characters
    • Limit(&'static str) -- over a limit: the name of the field of WriteOptions
    • Package(opc::Error) -- the package (archive::opc) refused what was built: never for a workbook that passed the checks above

impl WriteError

  • fn text(&self) -> String The error as a sentence in English.

  • fn write(book: &BookOut, opts: &WriteOptions) -> Result<Vec<u8>, WriteError> Write a workbook as XLSX (see the module's head for how values, dates and widths are written and what Excel's limits are). Deterministic: the same book gives the same bytes.

Source: docs/API.md in the JFLib repository.