CellRune
CellRune is a headless Rust backend for bounded XLSX/XLSM reading and deterministic formula
calculation. It keeps the workbook read from disk immutable, returns recalculated values in a
separate snapshot, and can retain an exact package backing for explicit round-trip writing. Its
MCP integration is a local stdio workflow server, not a browser, UI, hosted service, or remote
transport.
Rust installation
The CellRune Rust crate 0.2.1 requires Rust 1.88 or newer.
cargo add cellrune@0.2.1
Or add the dependency directly:
[dependencies]
cellrune = "0.2.1"
Features
- reads
.xlsx files from paths, byte slices, or Read + Seek streams;
- opens package-backed
.xlsx and .xlsm documents with exact SHA-256 identity, borrowed access
to the retained input bytes, and bounded round-trip preservation, including from an owned byte
vector that it keeps without copying and can hand back;
- preserves sheet order, sparse cells, formulas, saved results, defined names, and relevant
number-format metadata;
- exposes merged ranges, hidden rows, worksheet-level autoFilter ranges and their filtered
columns, and validated worksheet-owned Excel
tables, including stable table and column IDs, complete filter/sort/formula/style metadata, and
case-insensitive lookup indexes;
- reads and writes every worksheet data validation rule, including Excel 2010 extension rules,
with the one-rule-per-cell edits of Excel's Data Validation dialog, and reads worksheet
hyperlinks and cell comments as read-only metadata;
- imports and exports one sheet as RFC 4180 CSV under a documented, lossless value rule;
- reads and writes a minimal cell formatting model (font, fill, border, alignment) with column
widths and row heights, patching only the style records an edit needs into existing packages;
- resolves typed multi-area, 3-D, structured table, current-row, and spill references under
cumulative reference and dependency budgets;
- inspects workbook and sheet-local defined names without running a calculation session, preserving
rectangular, 3-D, ordered multi-area, empty, dynamic, external, invalid, and unsupported results;
- expands shared formulas while preserving absolute and relative references;
- returns typed formula values and stable per-cell calculation issues in one result snapshot;
- reports normalized per-workbook function demand and exposes the implemented function catalog;
- calculates average-tie ranks, linear forecasts, matrix determinants, dated cash-flow present
values, declining-balance depreciation, normal/lognormal inverses, and deterministic
text-to-number conversions;
- evaluates first-class and defined-name
LAMBDA callables, including immediate invocation,
ISOMITTED, MAP, BYROW, BYCOL, REDUCE, SCAN, and MAKEARRAY, under explicit
recursion and iteration limits;
- evaluates audited 3-D aggregate references across workbook tab order, including hidden sheets and
reverse-written endpoints, without expanding the sheet span into dependency edges;
- applies configurable limits to ZIP, XML, workbook, formula, dependency, text, and array work;
- never executes macros, never follows external links, never reads the host clock for
TODAY() or NOW(), and draws RAND(), RANDBETWEEN(), and RANDARRAY() from an explicit
seed instead of host randomness;
- returns stable error and issue codes for programmatic handling, listed in
docs/ERROR_CODES.md;
read, formula, and targeted-calculation limit failures also name the exceeded limit or report
the observed value;
- materializes recalculated typed results into existing
.xlsx/.xlsm packages with strict or
explicit cache-invalidation policies and reports a verified output SHA-256 identity;
- writes
WorkbookDraft edits into an existing package without calculating, clearing only the
saved results the edits can affect and asking the host to recalculate on open only when needed;
- creates canonical
.xlsx workbooks and applies typed cell, formula, sheet (including sheet
deletion), name, table rename, table-column rename, table-row resize, table and autoFilter column
widening, number-format, date-system, and calculation-property edits through WorkbookDraft;
- reads, queries, preserves, and explicitly authors SpreadsheetML phonetic annotations and default
frozen panes without mixing presentation state into formula calculation;
- exposes the versioned read/edit/calculate/write contract through typed Python and
Node.js/TypeScript native packages, including saves of edits without calculating, adjustable
read and calculation limits, and capability scans; the table under
Language bindings lists what each surface offers;
- reports the cells and ranges a formula reads and the formulas that read a cell, from the
dependency graph of the installed calculation, marking references that depend on values;
- supports atomic typed edit batches, persistent parsed/dependency state, safe incremental
recalculation, bounded result deltas, cooperative cancellation, stale-result rejection, and
retained immutable change previews;
- provides a local stdio MCP server with high-level open, inspect, edit, preview, recalculate,
range-read, delta, and verified Save As tools over the same interop session; and
- raw-copies unchanged package entries without exposing ZIP or XML implementation types.
Usage
use cellrune::{
CalculationCellResult, CalculationOptions, ReadOptions, calculate_workbook, read_xlsx_path,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let workbook = read_xlsx_path("input.xlsx", ReadOptions::default())?;
let calculation = calculate_workbook(&workbook, CalculationOptions::default());
for (cell, result) in calculation.cells() {
match result {
CalculationCellResult::Value(value) => println!("{cell:?}: {value:?}"),
CalculationCellResult::Unavailable(issue) => {
eprintln!("{cell:?}: {}", issue.code().as_str());
}
}
}
Ok(())
}
Reading and calculation are separate operations. calculate_workbook does not modify the source
WorkbookSnapshot or its saved XLSX results. It attempts every formula in the workbook:
successfully calculated cells contain a typed Value, while a cell that cannot be calculated
contains a structured Unavailable(CalculationIssue). One unavailable formula does not suppress
independent results; dependent formulas report BlockedByUpstream when applicable.
Volatile functions require deterministic inputs through CalculationOptions:
with_today_serial for TODAY(), with_now_serial for NOW(), and with_random_seed for
RAND(), RANDBETWEEN(), and RANDARRAY(). A draw depends only on the seed, the cell, and the
call's position in its formula, so wherever full calculation produces a value the other
calculation modes produce the same one; the generator is not cryptographically secure. Use
with_locale_profile to select the built-in English (United States) or Korean (Korea)
conventions that DOLLAR, the names TEXT shows, the currency symbol and date order text reads
as a number with, the double-byte text functions, and the GROUPBY and PIVOTBY total labels
follow; CellRune never reads the host locale. Use with_arithmetic_semantics to use binary values
unchanged for near-zero correction, comparison, and rounding instead of Excel's fifteen-digit
rules, and with_financial_solver_semantics to opt into the extended search shipped through
0.1.2; the defaults select Excel's rules and Microsoft's function-specific solver budgets. Use
supported_function_catalog for the build's exact function surface and scan_function_usage to
summarize the functions used by a workbook. scan_formula_capabilities remains available as an
optional static inventory for migration planning and user-interface reporting; calculation does
not require it.
CellRune 0.1.14 adds exactly 19 official Excel-facing engineering names: CONVERT, BESSELI,
BESSELJ, BESSELK, BESSELY, COMPLEX, IMABS, IMAGINARY, IMARGUMENT, IMCONJUGATE,
IMREAL, IMDIV, IMPOWER, IMPRODUCT, IMSUB, IMSUM, IMEXP, IMLN, and IMSQRT.
CONVERT uses a typed, case-sensitive unit registry; the complex family shares one finite parser
and canonical formatter; and the four Bessel functions use budgeted first-party kernels.
The fixed-income wave on top of 0.1.14 adds exactly 26 official names: ACCRINT, ACCRINTM,
COUPDAYBS, COUPDAYS, COUPDAYSNC, COUPNCD, COUPNUM, COUPPCD, DISC, DURATION,
INTRATE, MDURATION, ODDFPRICE, ODDFYIELD, ODDLPRICE, ODDLYIELD, PRICE, PRICEDISC,
PRICEMAT, RECEIVED, TBILLEQ, TBILLPRICE, TBILLYIELD, YIELD, YIELDDISC, and
YIELDMAT. They share a typed day-count and coupon-schedule model and a safeguarded yield root
solver that charges the calculation budget and observes cancellation.
CellRune 0.1.22 adds 22 official statistical, distribution, and complex-logarithm names,
including exclusive percentiles, TRIMMEAN, the A variances, STEYX, PROB, chi-square,
Weibull, and confidence-interval functions, and IMLOG10/IMLOG2; the exact list is in
llms.txt.
CellRune 0.1.26 adds the seeded random functions RAND, RANDBETWEEN, and RANDARRAY.
CellRune 0.1.27 adds the shape statistics SKEW, SKEW.P, and KURT, the array statistics
FREQUENCY and MODE.MULT, the chi-square test and quantiles CHISQ.TEST, CHISQ.INV, and
CHISQ.INV.RT with their legacy names, the financial functions CUMIPMT, CUMPRINC, VDB,
AMORLINC, and AMORDEGRC,
the complex trigonometric functions IMSIN, IMCOS, IMTAN, IMCOT, IMSEC, IMCSC,
IMSINH, IMCOSH, IMSECH, and IMCSCH, ENCODEURL, FILTERXML, BAHTTEXT, CELL for the
information that depends only on the workbook, AGGREGATE, FIXED, and the byte-counting text functions with
ASC and DBCS; the exact list is in
llms.txt.
CellRune 0.1.27 adds AGGREGATE, FIXED, the byte-counting text functions LENB, LEFTB,
RIGHTB, MIDB, FINDB, SEARCHB, and REPLACEB, and ASC and DBCS, and formats TEXT
with Excel number-format codes: sections and conditions, dates and times in both date systems,
elapsed time, scientific notation, fractions, and thousands scaling. A construct whose Excel output
has not been established, such as a fixed fraction denominator, stays an explicit Unavailable
result rather than a guess; the details are in
llms.txt.
CellRune 0.1.16 added XLOOKUP, DATEVALUE, TIMEVALUE,
NETWORKDAYS.INTL, and WORKDAY.INTL. Their date and time text, lookup modes, calendar rules,
wildcard behavior, and array-result boundaries are documented alongside the current function
catalog in llms.txt.
The regex functions target PCRE2 semantics with bounded compile, matching, capture, and output
work. CellRune's prebuilt Python, Node.js, and MCP artifacts pin the bundled PCRE2 10.46 engine;
Rust consumers use pcre2-sys linkage policy and can set PCRE2_SYS_STATIC=1 to select its bundled
source build.
INDEX follows Excel's zero-index reference behavior: a zero row or column selects the complete
corresponding column or row, and zero for both selects the complete input range. Scalar formulas
apply legacy implicit intersection, while array formulas can materialize the selected rectangle.
In a dynamic or array formula, and in arguments that take arrays such as those of SUMPRODUCT, a
function that takes a value is called once per element of an array it receives, as Excel does
(=SQRT(A1:A3) spills three roots and SUMPRODUCT(LEN(A1:A3)) adds three lengths).
Unary and binary array operators that combine whole-column references use one common extent: the
greatest populated row among the columns those operands reference, with a one-row minimum for an
otherwise empty sheet. Cells in other columns of the same sheet do not widen it, so the value
depends only on the cells the expression's own dependency rectangles cover and a full and an
incremental recalculation agree. Missing cells within that extent are blanks, and directly
resolved source arrays plus operator outputs are charged to its cumulative array-cell budget. Function calls keep function-defined
argument boundaries: each array argument is evaluated under its own bounded context, and a
function's return does not establish a whole-column operator extent by itself. When another direct
whole-column operand has established such an enclosing context, the returned array is charged to
that context before the operator consumes it.
Direct 3-D references are accepted by SUM, AVERAGE, AVERAGEA, COUNT, COUNTA, MAX,
MAXA, MIN, MINA, PRODUCT, STDEV.P, STDEV.S, VAR.P, and VAR.S (including the
catalogued legacy aliases). The span follows workbook tab order, so hidden sheets participate and
reversed endpoint spelling produces the same set. Excel-defined direct 3-D error contexts remain
values: INDEX and VLOOKUP return #VALUE!, while OFFSET returns #REF!. Other direct 3-D
consumers remain an explicit UnsupportedSheetRange capability issue. A bare 3-D reference or one
composed through an array operator returns #VALUE!; it does not silently inherit an enclosing
aggregate's collection policy. The static capability scan and evaluator share this policy.
For repeated programmatic edits, use WorkbookCalculationSession instead of rebuilding stateless
calculation state after every cell:
use cellrune::{
CalculationOptions, CancellationToken, CellAddress, CellValue, EditBatch, FiniteNumber,
RecalculationMode, SheetId, WorkbookCalculationSession, WorkbookChange,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut session = WorkbookCalculationSession::create();
let sheet = SheetId::new(1)?;
let receipt = session.apply_changes(
0,
EditBatch::new([WorkbookChange::set_cell_value(
sheet,
CellAddress::from_a1("A1")?,
CellValue::Number(FiniteNumber::new(42.0)?),
)]),
)?;
let delta = session.recalculate(
RecalculationMode::Auto,
CalculationOptions::default(),
CancellationToken::new(),
)?;
assert_eq!(delta.result_revision(), receipt.result_revision());
Ok(())
}
Auto evaluates a proven dirty subset and falls back to the same full-workbook calculation
semantics when name, sheet, option, dynamic-reference, or spill topology is uncertain; an edited
cell formula is parsed and wired into the dependency graph on its own.
Forced incremental mode fails closed instead of guessing. Sessions use optimistic semantic
revisions for atomic edits, retain bounded result-delta history, and reject stale calculations.
A batch whose accepted operations make no semantic change keeps the current revision, topology,
and installed calculation instead of forcing a redundant recalculation.
Long-running work can be prepared outside the session lock with prepare_recalculation, cancelled
through a request-owned CancellationToken, and installed only if its source revision is still
current.
Use targeted calculation when a headless service needs only a few outputs. Rust exposes
calculate_targets and WorkbookCalculationSession::calculate_targets; Python and Node expose
the same operation without requiring a prior full calculation:
result = workbook.calculate_targets([
{"sheet": "Sheet1", "start": "B1"},
{"sheet": "Sheet1", "start": "D1", "end": "D10"},
])
const result = await workbook.calculateTargets([
{ sheet: "Sheet1", start: "B1" },
{ sheet: "Sheet1", start: "D1", end: "D10" },
]);