Excelerate
Read, write and recalculate spreadsheets in pure Rust.
Opens .xlsx, .xlsb, .xls, .ods, .csv, .html, .slk, .gnumeric
and SpreadsheetML 2003, hands you the workbook as a plain Rust struct, evaluates
formulas (518 Excel functions and counting) and writes the whole thing back.
No Excel, no LibreOffice, no COM, no headless anything - just the crate.
[]
= "0.16"
use ;
let book = read?;
let sheet = book.active_sheet.unwrap;
println!;
println!;
# Ok::
at!("B2") is an address checked while compiling; set_at(row, column, ..)
takes numbers, and CellRef::parse takes text that arrives at run time.
Why you might want it
- The format is sniffed, not guessed from the extension.
reader::readlooks at the bytes first, so a.txtthat is secretly a zip package still opens as xlsx. The extension only gets a vote when the bytes stay quiet. - Formulas actually run. Recalculate the whole book, one sheet, or just what an edit touched - the incremental path is roughly 20x cheaper on a book with 20k formulas.
- Round-trips without eating your file. Read -> write -> read keeps styles, merges, conditional formatting, protection, autofilters with their sort state, sparklines and print setup; text with a colour or font change mid-cell keeps its runs in xlsx, xls, ODS and HTML alike. Charts, pictures, shapes and comments are modelled and written back; anything the crate does not model yet rides through byte for byte along with its relationships.
- Edits the grid like Excel does. Insert or remove rows, columns and
cells, copy or move a block, reorder the sheets - and the formulas, merges,
links, tables and drawings across the whole workbook follow. A copy rewrites
its formulas, a move keeps them and drags the references to it along.
Inserted rows can take the formatting of their neighbour, ranges and tables
sort in Excel's order, and the fill handle's series (
1, 3, 5,Jan, Feb,Q1, Q2) are one call. - Builds for WebAssembly, and ships as two npm packages:
@rosperitus/excelerateand a read-only@rosperitus/excelerate-readerat a third of the size. - No
unsafe,clippy::pedanticclean, and the deps arezip,quick-xml,flate2,thiserror,regexfor theREGEX*functions, andsha1/sha2/getrandomfor password hashes - all pure Rust, so a wasm build needs no C toolchain.
Use cases, step by step
Each block below runs as a test (cargo test --doc), against the files in
tests/fixtures/, so the asserts are the answers you get.
- Read a workbook and pull values out
- Build a report from scratch
- Change an input, recalculate what depends on it
- Insert rows and sort; formulas follow
- Convert between formats in memory
- Import a CSV with
;and a decimal comma - Ask a table by name
- Notes, links, a drop-down and a password
- Your own function, with a progress callback
- See how a cell is styled
- Title, author and your own fields
Read a workbook and pull values out
use CellValue;
use ;
// 1. Open it. The bytes decide the format; the extension is a fallback.
let book = read?;
// 2. Pick a sheet by name. `book.sheets()[0]` works by position.
let data = book.sheet_index_by_name.unwrap;
let sheet = &book.sheets;
// 3. One cell: the stored value, formula or not.
let b1 = at!;
assert_eq!;
// 4. The same cell as Excel shows it, with its number format applied.
println!;
// 5. Every non-empty cell, in address order. Empty ones are never visited.
for in sheet.iter
# Ok::
Build a report from scratch
Styles live in the workbook and a cell holds an id into them. intern hands
back the same id for the same style, so a thousand money cells cost one entry.
use recalculate;
use ;
use Options;
use ;
use ;
use Cursor;
let mut book = empty;
let mut sheet = new?;
// 1. Two styles: a bold header and a money format.
let mut header = default;
header.font.bold = true;
let header = book.styles.intern;
let mut money = default;
money.number_format = Custom;
let money = book.styles.intern;
// 2. The header row, then one row per record.
sheet.set_styled;
sheet.set_styled;
for in .zip
// 3. A total. It is only text until something computes it.
sheet.set_styled;
// 4. A wider first column, and the header row frozen when scrolling.
sheet.set_column_width;
sheet.view.pane = Some;
book.add_sheet?;
// 5. Compute, then write. `writer::write_xlsx(&book, "sales.xlsx")` for a file.
recalculate;
let mut bytes = Vecnew;
write_xlsx_to?;
// What was written reads back with the total in place, formatted.
let again = read_bytes?;
assert_eq!;
# Ok::
Change an input, recalculate what depends on it
recalculate computes the whole workbook. After an edit, Dependencies
computes only the formulas that read what changed; build it once and keep it
for a series of edits.
use ;
use ;
use Options;
use at;
let = ;
let mut book = empty;
let mut sheet = new?;
sheet.set;
sheet.set;
sheet.set;
sheet.set; // reads no cell
book.add_sheet?;
recalculate;
// 1. Index which formula reads which cell.
let deps = of;
// 2. Change the input.
book.sheet_mut.unwrap.set;
// 3. Recompute what the change reaches: A2, then A3. `NOW()` is volatile,
// so it runs on every pass too.
let computed = deps.recalculate_from;
assert_eq!;
assert_eq!;
# Ok::
When you change a formula rather than a value, tell the index with
deps.note(&book, sheet, cell).
Insert rows and sort; formulas follow
Grid edits rewrite every formula in the workbook that points past the edit, on every sheet, the way Excel does. A copy rewrites the copied formulas; a sort treats each moved row as copied.
use ;
use ;
use ;
let mut book = empty;
let mut sheet = new?;
sheet.set;
sheet.set;
for in
sheet.set;
book.add_sheet?;
// 1. Two rows above row 3 (rows count from 0 here), styled like row 2.
// The total moves from B6 to B8 and its range grows to cover them.
insert_rows_with?;
let total = book.sheets.get.map;
assert!;
// 2. Sort the block by its "Amount" header, largest first. The header stays.
let options = SortOptions ;
let keys = ;
sort_range_with?;
let first = book.sheets.get.map;
assert_eq!;
# Ok::
docs/editing.md has the rules each edit follows, and columns, cells, copy, move, fill and sheet renames.
Convert between formats in memory
A server that receives a file as bytes never needs a temp file. The name is optional and only helps when the bytes are ambiguous, as CSV is.
use ;
use Cursor;
// 1. Bytes in: here an Excel 97 file.
let bytes = read?;
let book = read_bytes?;
// 2. Bytes out, in three formats.
let mut xlsx = Vecnew;
write_xlsx_to?;
let mut ods = Vecnew;
write_ods_to?;
let mut csv = Vecnew;
write_csv_to?; // one sheet, your delimiter
assert!;
# Ok::
Import a CSV with ; and a decimal comma
A CSV from a Russian or German Excel writes 1 234,50. Say which characters
are which, and the field becomes the number 1234.5.
use ;
use at;
let text = "Item;Amount\nTea;1 234,50\nCoffee;99,90\n";
let book = read_csv_str;
let amount = book.sheets.get.and_then;
assert_eq!;
# Ok::
Without a delimiter, the reader picks the one that splits the lines most
evenly, and a leading sep=; line wins over both.
Ask a table by name
An Excel table has a name, and formulas can use it instead of an address:
Sales[Amount] keeps pointing at the column when rows are added. The engine
evaluates a formula you hand it without storing anything.
use ;
use Value;
use ;
// 1. The fixture holds one table, "Sales", with Region, Quarter and Sales.
let book = read?;
let table = &book.sheets.tables;
assert_eq!;
// 2. Evaluate against it, as if typed into E1 of the first sheet.
let mut engine = new;
let at = new;
let total = engine.eval;
let north = engine.eval;
assert!;
assert!;
# Ok::
Notes, links, a drop-down and a password
Everything on a sheet that is not a cell is a plain field of Worksheet.
use ;
use ;
use Cursor;
let mut sheet = new?;
let = ;
// 1. A note on B2. The author lives on the note itself.
sheet.comments.insert;
// 2. A link on A1.
sheet.hyperlinks.push;
// 3. A yes/no drop-down on C2:C100.
sheet.data_validations.push;
// 4. Lock the sheet. SHA-512 with a random salt, as Excel writes it; this
// stops editing in Excel and encrypts nothing.
sheet.protection = SheetProtection ;
sheet.protection.password = new;
let mut book = empty;
book.add_sheet?;
let mut bytes = Vecnew;
write_xlsx_to?;
let again = read_bytes?;
let sheet = &again.sheets;
assert_eq!;
assert!;
# Ok::
Merges, autofilters, conditional formats, print setup and the rest are in docs/sheet-features.md.
Your own function, with a progress callback
A workbook may call a function Excel does not have, say one your add-in
provided. Register it and formulas that use it compute; leave it out and they
answer #NAME?, as Excel does with the add-in missing.
use CustomFunctions;
use recalculate;
use Value;
use ;
use ;
use ;
use Cell;
let mut book = empty;
let mut sheet = new?;
sheet.set;
sheet.set;
book.add_sheet?;
// 1. The function: arguments arrive computed, a range as `Value::Array`.
let mut functions = new;
functions.register;
// 2. A progress callback. It is `Fn`, so a counter goes in a `Cell`.
let reports = new;
let report = ;
// 3. Both ride in one `Options`, which `read_*_with`, `write_*_with` and
// `recalculate` all take.
let options = new.with_functions.reporting;
recalculate;
assert_eq!;
assert!;
# Ok::
A built-in name always stays built in: registering SUM does not replace it.
See how a cell is styled
use ;
let book = read?;
let cell = book.sheets.get.unwrap;
// The cell holds an id; the workbook holds the style.
let style = book.styles.get.unwrap;
assert_eq!;
assert!;
assert!;
println!;
# Ok::
docs/styles.md covers colours, themes, number formats and rich text inside a cell.
Title, author and your own fields
What Excel shows under File > Info travels with the workbook in xlsx, xls and ODS, along with the fields a user adds under Custom.
use ;
use ;
let mut book = empty;
book.add_sheet?;
// 1. The standard fields are plain options. Dates are ISO 8601 text.
book.properties.title = Some;
book.properties.creator = Some;
book.properties.company = Some;
book.properties.created = Some;
// 2. Your own fields keep their type: text, whole number, number, yes/no, date.
book.properties.set_custom;
book.properties.set_custom;
// 3. They come back from xls just as from xlsx.
let mut bytes = Vecnew;
write_xls_to?;
let again = read_bytes?;
assert_eq!;
assert_eq!;
# Ok::
From JavaScript
The same crate compiled to WebAssembly, for Node and the browser:
import { Book } from "@rosperitus/excelerate";
import { readFileSync, writeFileSync } from "node:fs";
const book = Book.read(readFileSync("sales.xlsx"));
book.insertRows(0, 8, 2); // styled like row 7
book.sortRange(0, "A1:E500", ["-Amount"], { header: true });
book.setRangeStyle(0, "A1:E1", { font: { bold: true } });
book.recalculate();
writeFileSync("sales-sorted.xlsx", book.toXlsx());
The whole JS API is in docs/wasm.md and the package's README.
Formats
| Format | Read | Write |
|---|---|---|
| xlsx (OOXML) | ✅ | ✅ |
| xls (BIFF8) | ✅ | ✅ |
| xls (BIFF5, Excel 5 and 95) | ✅ | — |
| xlsb (BIFF12) | ✅ | — |
| ods (OpenDocument) | ✅ | ✅ |
| CSV | ✅ | ✅ |
| HTML | ✅ | ✅ |
SYLK (.slk) |
✅ | — |
| Gnumeric | ✅ | — |
SpreadsheetML 2003 (.xml) |
✅ | — |
Every format has its own sharp edges; they are all written down in docs/formats.md rather than left for you to find at 3am.
Docs
| Page | What's in it |
|---|---|
| Getting started | install, read a file, write one, the whole loop |
| Recipes | short answers: read a value, convert a file, recalculate one cell |
| Workbook model | workbook, sheet, cell, addresses and ranges |
| Editing the grid | inserting and removing rows, columns and cells, formatting what you insert, copying, moving, sorting and filling, and what follows each edit |
| Sheet features | merges, comments, tables, protection, filters, validation, print setup |
| File formats | what each format carries and what it drops |
| Formulas | evaluation, incremental recalc, driving the engine yourself |
| Styles and number formats | fonts, fills, borders, format strings |
| Long operations | progress, custom functions, what each step costs |
| Links to other workbooks | [1]Sheet1!A1, the value cache, plugging in a live file |
| WebAssembly | building for Node and the browser, and the whole JS API |
Building
cargo fmt && cargo clippy --all-targets -- -D warnings && cargo test
./build-npm.sh && (cd npm && npm install && npm test && npm run typecheck)
Status
Formats, styles, the formula engine and the xlsx object model (protection, autofilters, validation, conditional formatting, print setup, tables, charts, pictures, shapes, comments, pivot tables) are in. xls keeps formulas and styles both ways. See docs/formats.md for the exact line between "modelled" and "carried".
License
MIT - see LICENSE.