Model
Central interface for managing and manipulating spreadsheet data in memory.
The Model class represents a collection of workbooks and provides a unified API for reading, writing, and calculating cell values across all workbooks. It manages workbook dependency graphs to ensure accurate recalculation when values change, and handles formula evaluation with support for cross-workbook references.
Basic usage
Section titled “Basic usage”// Wait for formula parser to load before using modelsawait Model.preconditions;
// Create a model from JSF (recommended)const parsedJSF = JSON.parse(jsf);const model = Model.fromJSF(parsedJSF);
// Alternatively, create from CSF (for backward compatibility)const parsedCSF = JSON.parse(csf);const model = Model.fromCsf(parsedCSF);
// Write primitive values to cellsmodel.write('A1', "Hello, World!");model.write('A2', 42);model.write('A3', true);
// Read cell valuesmodel.readValue("=A1");model.readValue("=Sheet1!A1"); // Read from a specific sheetmodel.readValue("=[budget.xlsx]Sheet1!A1"); // Read from a specific workbook
// Work with multiple workbooksmodel.addWorkbook(anotherWorkbook);model.write('Sheet1!A1', 100); // Write to specific sheetmodel.write('[another_workbook.xlsx]Sheet1!A1', 200); // Write to specific workbookPerformance considerations
Section titled “Performance considerations”- Lazy recalculation: only changed cells and their dependents are recalculated
- Batch writes: Use
writeMultiple()for better performance when writing many cells - Functions may be volatile: functions like NOW() and RAND() recalculate every time
Precondition
Section titled “Precondition”Some methods require the Model.preconditions promise to be resolved before use. This ensures the formula parser, a WebAssembly module, has finished loading. Always await this before calling static factory methods or methods marked with this precondition in their docs.
Extends
Section titled “Extends”emitter
Implements
Section titled “Implements”Constructors
Section titled “Constructors”Constructor
Section titled “Constructor”new Model():
Model
Returns
Section titled “Returns”Model
Overrides
Section titled “Overrides”EventEmitter.constructor
Properties
Section titled “Properties”coerceNullToZero
Section titled “coerceNullToZero”coerceNullToZero:
CoercionMode=COERCE_NONE
Implementation of
Section titled “Implementation of”EvaluationContext.coerceNullToZero
env:
Map<"isPrint"|"isMobile"|"username",MaybeBoxedFormulaArgument>
Information about outside environment relevant to the model and functions. Writable from the outside, but functions get only read access to it.
Implementation of
Section titled “Implementation of”evaluateAST()
Section titled “evaluateAST()”evaluateAST: (
ast,options) =>MaybeBoxedFormulaValue
Evaluate a formula in the form of an AST, in a given evaluation context.
This wraps the evaluateAST function as a Model method, just to enable
calling it via evaluation context to dodge circular imports.
Parameters
Section titled “Parameters”ASTNode
options
Section titled “options”Returns
Section titled “Returns”Implementation of
Section titled “Implementation of”evaluateASTNode
Section titled “evaluateASTNode”evaluateASTNode:
FnEvaluateASTNode
Evaluate an AST node.
This wraps the evaluateASTNodeUnbound function as a Model method, just
to enable calling it via evaluation context to dodge circular imports.
Implementation of
Section titled “Implementation of”EvaluationContext.evaluateASTNode
getEntities()
Section titled “getEntities()”getEntities: (
this) =>ModelEntity[]
Returns a list of defined names and tables in the Model.
No guarantees are made about the order of the entities.
Parameters
Section titled “Parameters”Model
Returns
Section titled “Returns”getGlobal()
Section titled “getGlobal()”getGlobal: (
this,name,workbookName?) =>FormulaError|DefinedName
Parameters
Section titled “Parameters”Model
string
workbookName?
Section titled “workbookName?”null | string
Returns
Section titled “Returns”the cell object for the given defined-name, or a #NAME? error if not found
getTable()
Section titled “getTable()”getTable: (
this,name,workbookName) =>null|Table
Parameters
Section titled “Parameters”Model
string
workbookName
Section titled “workbookName”undefined | null | string
Returns
Section titled “Returns”null | Table
getWorkbook()
Section titled “getWorkbook()”getWorkbook: (
this,name?) =>undefined|Workbook
Get the workbook with the given name (case-insensitive), or undefined if no such workbook is in the model.
Parameters
Section titled “Parameters”Model
null | string
Returns
Section titled “Returns”undefined | Workbook
getWorkbookByKey()
Section titled “getWorkbookByKey()”getWorkbookByKey: (
this,key) =>undefined|Workbook
Get the workbook with the given dependency-graph key (based uniquely on the
workbook name in a case-insensitive way by the wbNameToKey function).
Get workbook with the given keyInDepGraph
Parameters
Section titled “Parameters”Model
number
Returns
Section titled “Returns”undefined | Workbook
Implementation of
Section titled “Implementation of”EvaluationContext.getWorkbookByKey
instanceId
Section titled “instanceId”instanceId:
number
lastWrite
Section titled “lastWrite”lastWrite:
number=0
mode:
ModeBit=MODE_GRID_SHEET
Implementation of
Section titled “Implementation of”profile
Section titled “profile”profile:
null|Profile=null
Profiling information
Implementation of
Section titled “Implementation of”resolveName()
Section titled “resolveName()”resolveName: (
this,name,sheetName?) =>FormulaError|DefinedName
Get the cell object for the given defined name (matched case-insensitively)
in the indicated scope or in this context. If sheetName is given, then
only sheet-scoped defined names will be considered, not workbook-scoped
defined names. If this context permits cross-workbook name resolution, then
a match in the current workbook will be preferred but if no match is found
there, then the first match across all workbooks in model order will be
returned. If no match is found, #NAME? is returned.
Parameters
Section titled “Parameters”Model
string
sheetName?
Section titled “sheetName?”null | string
Returns
Section titled “Returns”Implementation of
Section titled “Implementation of”resolveSheet()
Section titled “resolveSheet()”resolveSheet: (
this,sheetName?,workbookName?) =>null|WorkSheet
Get the sheet with the given name (matched case-insensitively), or the first sheet of the context workbook if no name is given. The context workbook is the default (first) workbook of the model if not evaluating in the context of a specific workbook.
Parameters
Section titled “Parameters”Model
sheetName?
Section titled “sheetName?”null | string
workbookName?
Section titled “workbookName?”null | string
Returns
Section titled “Returns”null | WorkSheet
Implementation of
Section titled “Implementation of”EvaluationContext.resolveSheet
resolveTable()
Section titled “resolveTable()”resolveTable: (
this,name,workbookName) =>null|Table
Get the table with the given name (matched case-insensitively) in the context workbook, or if not found there, then in the first workbook in the model that contains a table by this name.
Parameters
Section titled “Parameters”Model
string
workbookName
Section titled “workbookName”undefined | null | string
Returns
Section titled “Returns”null | Table
Implementation of
Section titled “Implementation of”EvaluationContext.resolveTable
resolveWorkbook()
Section titled “resolveWorkbook()”resolveWorkbook: (
this,name?) =>undefined|Workbook
Get the workbook with the given case-insensitive name, or if no name is
given, the context workbook, or the default (first) workbook of the model
if not evaluating in the context of a specific workbook.
Get the workbook with the given name (case-insensitive), or undefined if no such workbook is in the model.
Parameters
Section titled “Parameters”Model
null | string
Returns
Section titled “Returns”undefined | Workbook
Implementation of
Section titled “Implementation of”EvaluationContext.resolveWorkbook
subscribers
Section titled “subscribers”subscribers:
never[] =[]
workbookName
Section titled “workbookName”
readonlyworkbookName:null=null
Name of the workbook containing the reference or formula, null for a GRID element formula
Implementation of
Section titled “Implementation of”EvaluationContext.workbookName
writeState()
Section titled “writeState()”writeState: (
this,includeOverwrittenCells) =>ModelStateTree
Returns an object tree of all current writes to the model. The outermost object’s keys will be workbook names, second level will be sheet names, and third level will be cell IDs or names with the written values as values:
{ "myworkbook": { "sheet1": { "A1": 1234 } }}By default, writes that would not produce the same state are omitted from the output. These are writes to formula cells that have been overwritten again by the recalculation process. Re-applying them to a reset model would not reliably produce the same state.
Parameters
Section titled “Parameters”Model
includeOverwrittenCells
Section titled “includeOverwrittenCells”boolean = false
include writes to formula cells that have been overwritten by recalculation.
Returns
Section titled “Returns”Implementation of
Section titled “Implementation of”preconditions
Section titled “preconditions”
staticpreconditions:Promise<{parse:FnParseFormula;replaceRefsOnDelete:ReplaceRefsOnDeleteFn;replaceRefsOnMove:ReplaceRefsOnMoveFn;replaceSheetReferences:ReplaceSheetReferencesFn;replaceWorkbookReferences:ReplaceWorkbookReferencesFn; }> =formulaParserReady
Promise that should be awaited before calling certain methods of Model
(noted with a precondition in the documentation of those methods).
Accessors
Section titled “Accessors”defaultWorkbookName
Section titled “defaultWorkbookName”Get Signature
Section titled “Get Signature”get defaultWorkbookName():
string
Returns
Section titled “Returns”string
defect
Section titled “defect”Get Signature
Section titled “Get Signature”get defect():
undefined|null|string
Returns
Section titled “Returns”undefined | null | string
errors
Section titled “errors”Get Signature
Section titled “Get Signature”get errors():
ModelError[]
Returns
Section titled “Returns”hasData
Section titled “hasData”Get Signature
Section titled “Get Signature”get hasData():
boolean
Returns
Section titled “Returns”boolean
lazyImportPromise
Section titled “lazyImportPromise”Get Signature
Section titled “Get Signature”get lazyImportPromise():
Promise<void>
Returns
Section titled “Returns”Promise<void>
Get Signature
Section titled “Get Signature”get meta():
ModelMeta
Returns
Section titled “Returns”ModelMeta
Get Signature
Section titled “Get Signature”get ready():
boolean
Returns
Section titled “Returns”boolean
volatiles
Section titled “volatiles”Get Signature
Section titled “Get Signature”get volatiles(): readonly (
CellVertexId|NameVertexId)[]
Returns
Section titled “Returns”readonly (CellVertexId | NameVertexId)[]
Methods
Section titled “Methods”_attachWorkbook()
Section titled “_attachWorkbook()”_attachWorkbook(
wb,options):void
Legacy internal-looking name for the now-public method attachWorkbook
Parameters
Section titled “Parameters”options
Section titled “options”AddWorkbookOptions = {}
Returns
Section titled “Returns”void
addError()
Section titled “addError()”addError(
modelError):ModelError
Parameters
Section titled “Parameters”modelError
Section titled “modelError”Returns
Section titled “Returns”addWorkbook()
Section titled “addWorkbook()”addWorkbook(
data,options):Workbook
Construct a workbook from the given JSF and then attach it to this model.
This is just a convenience wrapper calling Workbook.fromJsf and attachWorkbook.
If your workbook source is in CSF format, consider using Model.fromCsf instead, or if you have multiple CSF workbooks, use Workbook.fromCsf and attachWorkbook.
Parameters
Section titled “Parameters”JSF
The workbook data in JSF format
options
Section titled “options”AddWorkbookOptions = {}
Configuration options for the new workbook
Returns
Section titled “Returns”The newly created Workbook instance that was added to the model
Precondition
Section titled “Precondition”The Model.preconditions promise must be resolved before calling this method
Throws
Section titled “Throws”Error if data is invalid in some way
Throws
Section titled “Throws”Error if a non-external workbook with the same name already exists in the model
Throws
Section titled “Throws”Error if precondition is not satisfied (the formula parser has not finished importing)
Example
Section titled “Example”// Add multiple related workbooksconst model = new Model();model.addWorkbook(budget2024jsf); // From e.g. budget2024.xlsxmodel.addWorkbook(budget2025jsf); // From e.g. budget2025.xlsxaddWorkbookFromXlsx()
Section titled “addWorkbookFromXlsx()”addWorkbookFromXlsx(
data,filename,options?):Promise<Workbook>
Add a workbook from XLSX binary data.
This is a convenience method that wraps @borgar/xlsx-convert to load XLSX data
directly into the model. External references in the XLSX are also added to the model.
Parameters
Section titled “Parameters”Binary XLSX data (works in browsers and Node.js)
ArrayBuffer | Buffer<ArrayBufferLike> | Uint8Array<ArrayBufferLike>
filename
Section titled “filename”string
Filename to associate with the workbook
options?
Section titled “options?”AddWorkbookOptions & object
Options for workbook loading
Returns
Section titled “Returns”Promise<Workbook>
A Promise resolving to the main Workbook instance
addWorkbookFromXlsxFile()
Section titled “addWorkbookFromXlsxFile()”addWorkbookFromXlsxFile(
path,options?):Promise<Workbook>
Add a workbook from an XLSX file path.
This is a convenience method that wraps @borgar/xlsx-convert to load XLSX files
directly into the model. External references in the XLSX are also added to the model.
Parameters
Section titled “Parameters”string
Path to the XLSX file (Node.js only - uses fs)
options?
Section titled “options?”AddWorkbookOptions & object
Options for workbook loading
Returns
Section titled “Returns”Promise<Workbook>
A Promise resolving to the main Workbook instance
Example
Section titled “Example”await Model.preconditions;const model = new Model();const budget2024 = await model.addWorkbookFromXlsxFile('budget2024.xlsx');const budget2025 = await model.addWorkbookFromXlsxFile('budget2025.xlsx');analyzeAndFixFormula()
Section titled “analyzeAndFixFormula()”analyzeAndFixFormula(
formula,options?):AnalyzeFormulaResult
Parameters
Section titled “Parameters”formula
Section titled “formula”string
options?
Section titled “options?”sheetName?
Section titled “sheetName?”string
workbookName?
Section titled “workbookName?”null | string
Returns
Section titled “Returns”AnalyzeFormulaResult
analyzeFormula()
Section titled “analyzeFormula()”analyzeFormula(
formula,options?):AnalyzeFormulaResult
Parameters
Section titled “Parameters”formula
Section titled “formula”string
options?
Section titled “options?”sheetName?
Section titled “sheetName?”string
workbookName?
Section titled “workbookName?”null | string
Returns
Section titled “Returns”AnalyzeFormulaResult
attachWorkbook()
Section titled “attachWorkbook()”attachWorkbook(
wb,options):void
Add an additional workbook to this model.
This method allows you to combine multiple spreadsheet workbooks into a single model, enabling
cross-workbook formula references. Each workbook must have a name unique (case-insensitively)
within the model, unless an existing workbook with the same name is an external reference stub
(marked with isExternal: true), in which case it will be replaced by the new workbook.
Parameters
Section titled “Parameters”The workbook to add
options
Section titled “options”AddWorkbookOptions = {}
Configuration options for which optimization and recalculation work to do
Returns
Section titled “Returns”void
Throws
Section titled “Throws”Error if a non-external workbook with the same name already exists in the model
Example
Section titled “Example”// Add multiple related workbooksconst model = new Model();model.attachWorkbook(Workbook.fromJsf(budget2024jsf));model.attachWorkbook(Workbook.fromJsf(budget2025jsf);clearCachedFormula()
Section titled “clearCachedFormula()”clearCachedFormula(
formula):undefined|null
Parameters
Section titled “Parameters”formula
Section titled “formula”undefined | null | string
Returns
Section titled “Returns”undefined | null
clearCachedFormulasExcept()
Section titled “clearCachedFormulasExcept()”clearCachedFormulasExcept(
formulas):undefined|void
Parameters
Section titled “Parameters”formulas
Section titled “formulas”string[]
Returns
Section titled “Returns”undefined | void
clearCells()
Section titled “clearCells()”clearCells(
ref):void
Parameters
Section titled “Parameters”A reference to the cell, or range of cells, to clear. Defined names are not supported.
string | Reference
Returns
Section titled “Returns”void
emit()
Section titled “emit()”emit(
event, …arguments_):Emitter
Emit an event, invoking all handlers registered for it.
Parameters
Section titled “Parameters”string
The name of the event to emit.
arguments_
Section titled “arguments_”…any[]
Arguments to pass to the event handlers.
Returns
Section titled “Returns”Emitter
The Emitter instance for method chaining.
Inherited from
Section titled “Inherited from”EventEmitter.emit
evaluateExpression()
Section titled “evaluateExpression()”evaluateExpression<
Values,Single,Fallback>(expression,__namedParameters):EvaluateExpressionReturnType<Values,Single,Fallback>
Evaluate expression and return the resulting value, or cell, or 2-D array of values or of cells.
A 2-D array is the type returned by Reference.resolveArea: an Array of Arrays of values or Cell instances,
plus the attributes top, left, bottom, right, sheetName.
expr may be a literal value or a formula, or nullish or empty-string or the string '='. In the
latter three cases, fallBack is returned.
Also, if values is false and single is true, then fallBack is returned if a cell could not be resolved.
This is not done if values is true or single is true. (The intent is to iron out this inconsistency when we
get to removing the fallBack parameter altogether, in ENGINE-142.)
Type Parameters
Section titled “Type Parameters”Values
Section titled “Values”Values extends boolean = boolean
Single
Section titled “Single”Single extends boolean = boolean
Fallback
Section titled “Fallback”Fallback = unknown
Parameters
Section titled “Parameters”expression
Section titled “expression”string
what to evaluate. Treated as a formula if it begins with = and isn’t just that.
__namedParameters
Section titled “__namedParameters”EvaluateExpressionOptions<Values, Single, Fallback>
Returns
Section titled “Returns”EvaluateExpressionReturnType<Values, Single, Fallback>
the evaluated value, directly, or wrapped in a Cell instance or area array.
If single is false and values is false, this returns an AreaCellArray.
If single is false and values is true, this returns an AreaValueArray.
If single is true and values is false, this returns a Cell.
If single is true and values is true, this returns a CellValue.
getCell()
Section titled “getCell()”getCell(
cellId,sheetName?,workbookName?):null|Cell
Parameters
Section titled “Parameters”cellId
Section titled “cellId”string
sheetName?
Section titled “sheetName?”null | string
workbookName?
Section titled “workbookName?”null | string
Returns
Section titled “Returns”null | Cell
getWorkbookById()
Section titled “getWorkbookById()”getWorkbookById(
id):undefined|Workbook
Get the workbook with the given ID, or null if no such workbook is in the model.
Parameters
Section titled “Parameters”string
Returns
Section titled “Returns”undefined | Workbook
getWorkbooks()
Section titled “getWorkbooks()”getWorkbooks():
Workbook[]
Returns
Section titled “Returns”Workbook[]
goalSeek()
Section titled “goalSeek()”goalSeek(
controlCell,targetCell,targetValue):number|FormulaError
Parameters
Section titled “Parameters”controlCell
Section titled “controlCell”string | Reference
targetCell
Section titled “targetCell”string | Reference
targetValue
Section titled “targetValue”number
Returns
Section titled “Returns”number | FormulaError
hasListeners()
Section titled “hasListeners()”Call Signature
Section titled “Call Signature”hasListeners(
event):boolean
Check if there are any handlers registered for a specific event.
Parameters
Section titled “Parameters”string
The name of the event.
Returns
Section titled “Returns”boolean
true if there are one or more handlers, false otherwise.
Inherited from
Section titled “Inherited from”EventEmitter.hasListeners
Call Signature
Section titled “Call Signature”hasListeners():
boolean
Check if there are any handlers registered for any event.
Returns
Section titled “Returns”boolean
true if there are one or more handlers for any event, false otherwise.
Inherited from
Section titled “Inherited from”EventEmitter.hasListeners
isGlobal()
Section titled “isGlobal()”isGlobal(
cellRef,workbookName?):boolean
Parameters
Section titled “Parameters”cellRef
Section titled “cellRef”string
workbookName?
Section titled “workbookName?”string
name of a workbook to look in, if cellRef does not have a workbook prefix
Returns
Section titled “Returns”boolean
iterativeCalculationSettings()
Section titled “iterativeCalculationSettings()”iterativeCalculationSettings():
IterativeCalculationOptions
Returns
Section titled “Returns”IterativeCalculationOptions
listenerCount()
Section titled “listenerCount()”Call Signature
Section titled “Call Signature”listenerCount(
event):number
Get the count of listeners for a specific event.
Parameters
Section titled “Parameters”string
The name of the event.
Returns
Section titled “Returns”number
The number of listeners for the event.
Inherited from
Section titled “Inherited from”EventEmitter.listenerCount
Call Signature
Section titled “Call Signature”listenerCount():
number
Get the count of all event handlers in total.
Returns
Section titled “Returns”number
The total number of event handlers.
Inherited from
Section titled “Inherited from”EventEmitter.listenerCount
listeners()
Section titled “listeners()”listeners(
event): (…arguments_) =>void[]
Retrieve the event handlers registered for a specific event.
Parameters
Section titled “Parameters”string
The name of the event.
Returns
Section titled “Returns”(…arguments_) => void[]
An array of functions registered as handlers for the event.
Inherited from
Section titled “Inherited from”EventEmitter.listeners
Call Signature
Section titled “Call Signature”off<
T>(event,listener):object&Emitter
Remove a specific event handler for a specified event.
Type Parameters
Section titled “Type Parameters”T extends keyof ModelEventArgs
Parameters
Section titled “Parameters”T
The name of the event.
listener
Section titled “listener”ModelEventListener<T>
The specific handler function to remove.
Returns
Section titled “Returns”object & Emitter
The Emitter instance for method chaining.
Overrides
Section titled “Overrides”EventEmitter.off
Call Signature
Section titled “Call Signature”off(
event):object&Emitter
Remove all event handlers for a specified event.
Parameters
Section titled “Parameters”string
The name of the event for which to remove all handlers.
Returns
Section titled “Returns”object & Emitter
The Emitter instance for method chaining.
Overrides
Section titled “Overrides”EventEmitter.off
Call Signature
Section titled “Call Signature”off():
object&Emitter
Remove all event handlers for all events.
Returns
Section titled “Returns”object & Emitter
The Emitter instance for method chaining.
Overrides
Section titled “Overrides”EventEmitter.off
on<
T>(event,listener):object&Emitter
Register an event handler that listens to a specified event.
Type Parameters
Section titled “Type Parameters”T extends keyof ModelEventArgs
Parameters
Section titled “Parameters”T
The name of the event to listen to.
listener
Section titled “listener”ModelEventListener<T>
The function to execute when the event is emitted.
Returns
Section titled “Returns”object & Emitter
The Emitter instance for method chaining.
Overrides
Section titled “Overrides”EventEmitter.on
once()
Section titled “once()”once(
event,listener):Emitter
Register a one-time event handler for a specified event.
Parameters
Section titled “Parameters”string
The name of the event to listen to.
listener
Section titled “listener”(…arguments_) => void
The function to execute once when the event is emitted.
Returns
Section titled “Returns”Emitter
The Emitter instance for method chaining.
Inherited from
Section titled “Inherited from”EventEmitter.once
orderWorkbooks()
Section titled “orderWorkbooks()”orderWorkbooks(
idList):void
Set the order in which workbooks are treated as default.
Parameters
Section titled “Parameters”idList
Section titled “idList”string[]
list of IDs in the order to use
Returns
Section titled “Returns”void
readCell()
Section titled “readCell()”readCell(
expression,fallBack):Cell
Evaluate expression and return the resulting Cell.
See evaluateExpression.
Parameters
Section titled “Parameters”expression
Section titled “expression”string
the expression to evaluate. Treated as a formula if it begins with = and isn’t just that.
fallBack
Section titled “fallBack”Cell = BLANK_CELL
value to return if expr is empty or null or just =, or failed to resolve to a cell.
Returns
Section titled “Returns”the resulting Cell instance, or fallBack, or a Cell instance with a FormulaError as its value.
readCellOrDefinedName()
Section titled “readCellOrDefinedName()”readCellOrDefinedName(
expression,fallBack):CellItem
Evaluate expression, resolving any name reference result and recursing to
that formula, until a result that isn’t a name reference is obtained.
Return a single Cell which is:
- if the result is a reference to a range of sheet cells, the top-left cell cell of that range
- else if the result is that of a defined-name formula (not the original
expression), return that last defined-nameCellobject - else the result itself (or its top-left element if it is a
Matrix), wrapped in aCellwith noid.
Parameters
Section titled “Parameters”expression
Section titled “expression”string
the expression to evaluate. Treated as a formula if it begins with = and isn’t just that.
fallBack
Section titled “fallBack”CellItem = BLANK_CELL
value to return if expr is empty or null or just =, or failed to resolve to a cell.
Returns
Section titled “Returns”the resulting Cell instance, or fallBack, or a Cell instance with a FormulaError as its value.
evaluateExpression
readCells()
Section titled “readCells()”readCells(
expression,options):AreaCellArray
Evaluate expression and return the resulting 2-D array of cells.
See evaluateExpression.
Parameters
Section titled “Parameters”expression
Section titled “expression”string
the expression to evaluate. Treated as a formula if it begins with = and isn’t just that.
options
Section titled “options”cropTo?
Section titled “cropTo?”"any-cell-information" | "cells-with-non-blank-values"
Returns
Section titled “Returns”the resulting 2-D array of cells, or an error or fallback wrapped into the same structure.
readValue()
Section titled “readValue()”readValue(
expression,fallBack):CellValue
Evaluate expression and return the resulting value.
See evaluateExpression.
Parameters
Section titled “Parameters”expression
Section titled “expression”string
the expression to evaluate. Treated as a formula if it begins with = and isn’t just that.
fallBack
Section titled “fallBack”CellValue = null
value to return if expr is empty or null or just =.
Returns
Section titled “Returns”the resulting Cell instance, or fallBack, or a Cell instance with a FormulaError as its value.
recalculate()
Section titled “recalculate()”recalculate(
whichCells):object
Recalculates formula cells in the model and updates their values.
This method triggers the recalculation engine to evaluate formulas based on the dependency graph. It emits a ‘beforerecalc’ event before starting, handles any errors during calculation, and triggers an update event when complete.
If any sheets have GSDV cells (which should only happen if this is the initial recalculation),
then Cells.clearGsdv is called and if any cells are deleted as a result, a second initial
recalculation is performed (with CHANGED_ONLY, so not updating volatiles again) to update
formulas depending on them.
Parameters
Section titled “Parameters”whichCells
Section titled “whichCells”WhichCellsToRecalculate = CHANGED_OR_VOLATILE
Controls which cells to recalculate:
"CHANGED_OR_VOLATILE"(default): recalculates cells that have changed or are marked volatile"CHANGED_ONLY": recalculates only cells that have changed"ALL_FORMULA_CELLS": forces recalculation of all formula cells
Returns
Section titled “Returns”object
An object with a nativeWorkbooksChanged property containing any GRID-native
workbooks that needed recalculation.
nativeWorkbooksChanged
Section titled “nativeWorkbooksChanged”nativeWorkbooksChanged:
Set<Workbook>
removeWorkbook()
Section titled “removeWorkbook()”removeWorkbook(
id):boolean
Remove a workbook from this model and clean up all related dependencies.
When a workbook is removed, all cells that depend on formulas in that workbook will be recalculated. Any cross-workbook references to the removed workbook will result in #REF! errors in dependent cells.
Parameters
Section titled “Parameters”string
The unique identifier of the workbook to remove
Returns
Section titled “Returns”boolean
true if the workbook was found and removed, false otherwise
Example
Section titled “Example”const jsf = ...; // Load workbook as JSFjsf.id = '1234';const model = Model.fromJSF(jsf);const removed = model.removeWorkbook('1234');reset()
Section titled “reset()”reset():
void
Reset all cell values to their initial state (as data was when read). Only values are reset; other cell attributes (function, style) are not affected. This also triggers recalculation, so volatile cells will update.
Returns
Section titled “Returns”void
rewriteFormulaAfterMove()
Section titled “rewriteFormulaAfterMove()”rewriteFormulaAfterMove(
formula,from,to):string
Parameters
Section titled “Parameters”formula
Section titled “formula”string
formula to update.
reference containing a workbook and sheet prefix
string | A1Reference
reference containing a workbook and sheet prefix
string | A1Reference
Returns
Section titled “Returns”string
the updated formula.
Precondition
Section titled “Precondition”Formula parser has finished importing (formulaParserReady has resolved).
runFormula()
Section titled “runFormula()”runFormula(
formula,extraContext):FormulaValue
Evaluate a spreadsheet formula and return the computed result.
Results are automatically cached based on the formula text and will be reused if the same formula is evaluated multiple times with unchanged dependencies.
Parameters
Section titled “Parameters”formula
Section titled “formula”string
The Excel formula to evaluate, with or without leading ’=’ (e.g., ‘SUM(A1:A10)’ or ‘=SUM(A1:A10)‘)
extraContext
Section titled “extraContext”extra options or properties to pass through to the formula runner. These
will be available to each spreadsheet function as attributes on this
null | Partial<EvaluationContext>
Returns
Section titled “Returns”Result of the formula
Precondition
Section titled “Precondition”The Model.preconditions promise must be resolved before calling this method
Throws
Section titled “Throws”Error if precondition is not satisfied (the formula parser has not finished importing)
Throws
Section titled “Throws”EvaluationError if AST is invalid or an unanticipated internal error occurs so
evaluation can’t complete. This error will have its .ast and .formula properties
populated.
Throws
Section titled “Throws”FormulaSyntaxError if formula needs to be parsed and can’t be
Example
Section titled “Example”import xlsxConvert from "@borgar/xlsx-convert";import { Model } from '@grid-is/apiary';
await Model.preconditions;
const wb = await xlsxConvert("budget.xlsx");const model = Model.fromJSF(wb);const totalSpent = model.runFormula("=SUM(D:D)");Model.readValue to read a value from a cell
setupInitRecalculation()
Section titled “setupInitRecalculation()”setupInitRecalculation():
void
Returns
Section titled “Returns”void
setWorkbookState()
Section titled “setWorkbookState()”setWorkbookState(
workbookId,state,defect):void
Parameters
Section titled “Parameters”workbookId
Section titled “workbookId”string
undefined | "uploading" | "processing" | "ready" | "invalid"
defect
Section titled “defect”null | string
Returns
Section titled “Returns”void
triggerMetrics()
Section titled “triggerMetrics()”triggerMetrics(
ev):void
Parameters
Section titled “Parameters”(…args) => void
Returns
Section titled “Returns”void
triggerUpdate()
Section titled “triggerUpdate()”triggerUpdate():
void
Returns
Section titled “Returns”void
write()
Section titled “write()”Call Signature
Section titled “Call Signature”write(
cellRef,value,recalcNow?,skipVolatiles?,neutralizeFormulaOnSingleCellWrite?):void
(Deprecated signature) Write the given value to the given cell (A1 address or global name).
Parameters
Section titled “Parameters”cellRef
Section titled “cellRef”the address or global name to write to
string | Reference
the value to write
recalcNow?
Section titled “recalcNow?”boolean
true (the default) to recalculate immediately before returning
skipVolatiles?
Section titled “skipVolatiles?”boolean
true to skip evaluation of volatile cells when recalculating
neutralizeFormulaOnSingleCellWrite?
Section titled “neutralizeFormulaOnSingleCellWrite?”boolean
true to neutralize formula in single-cell write
Returns
Section titled “Returns”void
Call Signature
Section titled “Call Signature”write(
cellRef,value,opts?):void
Write the given value to the given cell (A1 address or global name)
Parameters
Section titled “Parameters”cellRef
Section titled “cellRef”the address or global name to write to
string | Reference
the value to write
WriteOptions
Returns
Section titled “Returns”void
writeMultiple()
Section titled “writeMultiple()”writeMultiple(
writes,opts):void
Efficiently write multiple values to different cells in a single operation.
Perform each write in the given list of writes and recalculate once at the end
(if the list was non-empty, or if forceRecalc is true).
This method is optimised for bulk data updates. Instead of recalculating after each individual write (which can be slow), it performs all writes first and then recalculates once at the end. This provides significantly better performance when updating many cells at once.
Parameters
Section titled “Parameters”writes
Section titled “writes”readonly [string, CellValue][]
Array of two-element arrays [cell, val] for individual writes
WriteOptions = {}
Options controlling the batch write behaviour
Returns
Section titled “Returns”void
Example
Section titled “Example”model.writeMultiple([ ['A1', 100], ['A2', 200], ['A3', 300],]);writes()
Section titled “writes()”writes(
includeOverwrittenCells): [string,CellValue][]
Return a list of writes to the model.
By default, writes that would not produce the same state are omitted from the list. These are writes to formula cells that have been overwritten again by the recalculation process. Re-applying them to a reset model would not reliably produce the same state.
Parameters
Section titled “Parameters”includeOverwrittenCells
Section titled “includeOverwrittenCells”boolean = false
include writes to formula cells that have been overwritten by recalculation.
Returns
Section titled “Returns”[string, CellValue][]
empty()
Section titled “empty()”
staticempty(filename):Model
Create an empty Model instance with a single blank workbook and worksheet.
This is a convenience method for creating a new Model from scratch without needing to provide CSF data. The resulting model contains one workbook with one empty worksheet named “Sheet1”.
Parameters
Section titled “Parameters”filename
Section titled “filename”string = 'Book1.xlsx'
The name to assign to the empty workbook
Returns
Section titled “Returns”Model
A new Model instance containing an empty workbook
Precondition
Section titled “Precondition”The Model.preconditions promise must be resolved before calling this method
Throws
Section titled “Throws”Error thrown if precondition is not satisfied (the formula parser has not finished importing)
fromCsf()
Section titled “fromCsf()”
staticfromCsf(csf,options):Model
Make a Model instance and populate it with a workbook from the given CSF.
CSF (Common Spreadsheet Format) is a JSON representation of a workbook. This method is typically used when loading data that has been previously processed from XLSX to JSON. Packages to do that include xlsx-convert or xlsx.
Parameters
Section titled “Parameters”The workbook data in CSF format
options
Section titled “options”AddWorkbookOptions = {}
Configuration options for workbook initialisation
Returns
Section titled “Returns”Model
A new Model instance containing the loaded workbook
Precondition
Section titled “Precondition”The Model.preconditions promise must be resolved before calling this method
Throws
Section titled “Throws”Error thrown if precondition is not satisfied (the formula parser has not finished importing)
Example
Section titled “Example”// Ensure parser is readyawait Model.preconditions;
// Create model from JSF dataconst model = Model.fromJSF(jsf, { // When a workbook is read-only, work required to support writes is skipped in order to load // the workbook faster. In particular, formulas will not be parsed and the workbook will not // be added to the dependency graph. No initial recalculation occurs, which may lead to // inaccuracies in workbooks that depend on it. readOnly: true});
// Access the loaded dataconst cellValue = model.readValue('=A1');fromData()
Section titled “fromData()”
staticfromData(csf,options):Model
Parameters
Section titled “Parameters”options
Section titled “options”AddWorkbookOptions = {}
Returns
Section titled “Returns”Model
fromJSF()
Section titled “fromJSF()”
staticfromJSF(jsf,options):Model
Make a Model instance and populate it with a workbook from the given JSF.
JSF (JSON Spreadsheet Format) is a JSON representation of a workbook produced by the xlsx-convert library. This method is typically used when loading data that has been previously processed from XLSX to JSON.
Parameters
Section titled “Parameters”JSF
A JSF object representing a workbook
options
Section titled “options”AddWorkbookOptions & object = {}
Configuration options for workbook initialization
Returns
Section titled “Returns”Model
A new Model instance containing the loaded workbook
Precondition
Section titled “Precondition”The Model.preconditions promise must be resolved before calling this method
Throws
Section titled “Throws”Error thrown if precondition is not satisfied (the formula parser has not finished importing)
Example
Section titled “Example”// Load Excel file using xlsx-convertimport xlsxConvert from "@borgar/xlsx-convert";
await Model.preconditions;
const wb = await xlsxConvert("budget.xlsx");const model = Model.fromJSF(wb);const totalSpent = model.runFormula("=SUM(D:D)");fromXlsx()
Section titled “fromXlsx()”
staticfromXlsx(data,filename,options?):Promise<Model>
Load a Model from XLSX binary data.
This is a convenience method that wraps @borgar/xlsx-convert to load XLSX data
directly into a Model without requiring users to manually import the conversion library.
Parameters
Section titled “Parameters”Binary XLSX data (works in browsers and Node.js)
ArrayBuffer | Buffer<ArrayBufferLike> | Uint8Array<ArrayBufferLike>
filename
Section titled “filename”string
Filename to associate with the workbook
options?
Section titled “options?”AddWorkbookOptions & object
Options for workbook loading
Returns
Section titled “Returns”Promise<Model>
A Promise resolving to a new Model instance
Precondition
Section titled “Precondition”The Model.preconditions promise must be resolved before calling this method, or an error will be thrown.
Example
Section titled “Example”await Model.preconditions;const response = await fetch('https://example.com/budget.xlsx');const data = await response.arrayBuffer();const model = await Model.fromXlsx(data, 'budget.xlsx');fromXlsxFile()
Section titled “fromXlsxFile()”
staticfromXlsxFile(path,options?):Promise<Model>
Load a Model from an XLSX file path.
This is a convenience method that wraps @borgar/xlsx-convert to load XLSX files
directly into a Model without requiring users to manually import the conversion library.
Parameters
Section titled “Parameters”string
Path to the XLSX file (Node.js only - uses fs)
options?
Section titled “options?”AddWorkbookOptions & object
Options for workbook loading
Returns
Section titled “Returns”Promise<Model>
A Promise resolving to a new Model instance
Precondition
Section titled “Precondition”The Model.preconditions promise must be resolved before calling this method, or an error will be thrown.
Example
Section titled “Example”await Model.preconditions;const model = await Model.fromXlsxFile('budget.xlsx');const totalSpent = model.runFormula("=SUM(D:D)");