Skip to content

Formulas and recalculation ​

Use this when a program writes formulas into a workbook and reads their results, or needs control over when the workbook calculates.

Enter a formula ​

setFormula(cell, text) (Python set_formula) stores a formula. A string that starts with = passed to setValue, setValues or Python's ws[...] = goes through the same path. The leading = is optional for setFormula.

js
import createFormulon from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setValues('A1', [[2], [3]])
  ws.setFormula('B1', '=SUM(A1:A2)')
  ws.setValue('B2', '=A1*A2')
  ws.setValues('B3', [['=B1+B2']])

  console.log(ws.getValue('B1'), ws.getValue('B2'), ws.getValue('B3')) // 5 6 11
} finally {
  wb.dispose()
}
python
from formulon import Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    ws["A1:A2"] = [[2], [3]]
    ws.set_formula("B1", "=SUM(A1:A2)")
    ws["B2"] = "=A1*A2"
    ws.set_values("B3", [["=B1+B2"]])

    print(ws["B1"], ws["B2"], ws["B3"])  # 5.0 6.0 11.0

Formula text uses the en-US function names and the , argument separator whatever the workbook's profile. Formula language translates to and from a user's locale.

Read the value, the formula and the display text ​

A formula cell answers three questions. getValue returns the calculated value, getFormula returns the stored formula with its leading = (or null for a cell without one), and getDisplayText(cell).text returns the value as the cell's number format shows it. getFormulaR1C1 returns the formula relative to the cell. The stored formula is re-spelled from the parsed text, so a literal such as 1.50 reads back as 1.5, and an entered formula takes Excel's spelling: =sum(a1) reads back as =SUM(A1) (formula text).

js
import createFormulon from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setValue('A1', 1234.5)
  ws.setFormula('B1', '=A1*1.50')
  ws.updateCellFormat('B1', { numberFormat: '#,##0.00' })

  console.log(ws.getValue('B1')) // 1851.75
  console.log(ws.getFormula('B1')) // =A1*1.5
  console.log(ws.getFormulaR1C1('B1')) // =RC[-1]*1.5
  console.log(ws.getDisplayText('B1').text) // 1,851.75
  console.log(ws.getFormula('A1')) // null
} finally {
  wb.dispose()
}
python
from formulon import Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    ws["A1"] = 1234.5
    ws.set_formula("B1", "=A1*1.50")
    ws.update_cell_format("B1", number_format="#,##0.00")

    print(ws["B1"])  # 1851.75
    print(ws.get_formula("B1"))  # =A1*1.5
    print(ws.get_formula_r1c1("B1"))  # =RC[-1]*1.5
    print(ws.get_display_text("B1").text)  # 1,851.75
    print(ws.get_formula("A1"))  # None

Choose when the workbook calculates ​

In the default CalcMode.Auto, a read and a save compute the dirty cells first. CalcMode.Manual computes nothing until recalc(): a read returns the value from the last calculation, and null for a formula that was never calculated. hasDirtyCells() (Python has_dirty_cells()) reports whether any cell is waiting.

js
import createFormulon, { CalcMode } from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setValue('A1', 2)
  ws.setFormula('B1', '=A1*10')
  console.log(ws.getValue('B1')) // 20

  wb.setCalcMode(CalcMode.Manual)
  ws.setValue('A1', 5)
  ws.setFormula('C1', '=A1+1')
  console.log(ws.getValue('B1'), ws.getValue('C1'), wb.hasDirtyCells()) // 20 null true

  wb.recalc()
  console.log(ws.getValue('B1'), ws.getValue('C1'), wb.hasDirtyCells()) // 50 6 false
} finally {
  wb.dispose()
}
python
from formulon import CalcMode, Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    ws["A1"] = 2
    ws.set_formula("B1", "=A1*10")
    print(ws["B1"])  # 20.0

    wb.set_calc_mode(CalcMode.MANUAL)
    ws["A1"] = 5
    ws.set_formula("C1", "=A1+1")
    print(ws["B1"], ws["C1"], wb.has_dirty_cells())  # 20.0 None True

    wb.recalc()
    print(ws["B1"], ws["C1"], wb.has_dirty_cells())  # 50.0 6.0 False

The mode is saved with the file, so a workbook saved in Manual mode opens in Manual mode. ws.recalcViewport(range) computes only the cells one rectangle needs; Recalculation describes it with the iterative and parallel options.

Report a formula that does not parse ​

Formula text that does not parse throws FormulonError (Python FormulaSyntaxError) and changes nothing. parseError (Python parse_error) locates the failure: start and end are UTF-16 offsets into the text you passed, line and column are 1-based, and code is a ParseErrorCode whose name enumName gives.

js
import createFormulon, { ParseErrorCode, enumName } from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setFormula('A1', '=1+1')
  for (const text of ['=SUM(', '=1+*2', '="abc']) {
    try {
      ws.setFormula('A1', text)
    } catch (e) {
      if (!(e instanceof formulon.FormulonError) || !e.parseError) throw e
      const { code, start, end, column } = e.parseError
      console.log(enumName(ParseErrorCode, code), start, end, column)
    }
  }
  console.log(ws.getFormula('A1'))
} finally {
  wb.dispose()
}
// UnexpectedEof 5 5 6
// ExpectedExpression 3 4 4
// LexerUnterminatedString 1 5 2
// =1+1
python
import formulon
from formulon import ParseErrorCode, Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    ws.set_formula("A1", "=1+1")
    for text in ["=SUM(", "=1+*2", '="abc']:
        try:
            ws.set_formula("A1", text)
        except formulon.FormulaSyntaxError as e:
            pe = e.parse_error
            print(formulon.enum_name(ParseErrorCode, pe.code), pe.start, pe.end, pe.column)
    print(ws.get_formula("A1"))
# UNEXPECTED_EOF 5 5 6
# EXPECTED_EXPRESSION 3 4 4
# LEXER_UNTERMINATED_STRING 1 5 2
# =1+1

#NAME? is the result of a well-formed formula that names something unknown, such as =NOSUCH(1), so it never signals a syntax error. A malformed formula stored in a loaded file is kept as it is and evaluates to #NAME?. Errors and diagnostics covers the other failures.

Evaluate a formula without writing it ​

ws.evaluateFormula(cell, text) (Python evaluate_formula) answers "what would this formula return at this cell?" without storing anything. The result is a scalar, or a 2-D array for a multi-cell result. formulon.evaluateFormula(text) does the same against a fresh one-sheet workbook.

js
import createFormulon from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setValues('A1', [[4, 5]])

  console.log(ws.evaluateFormula('C1', '=A1*B1')) // 20
  console.log(JSON.stringify(ws.evaluateFormula('C1', '=SEQUENCE(2)'))) // [[1],[2]]
  console.log(ws.getValue('C1')) // null
  console.log(formulon.evaluateFormula('=ROUND(PI(),4)')) // 3.1416
} finally {
  wb.dispose()
}
python
import formulon
from formulon import Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    ws["A1:B1"] = [[4, 5]]

    print(ws.evaluate_formula("C1", "=A1*B1"))  # 20.0
    print(ws.evaluate_formula("C1", "=SEQUENCE(2)"))  # [[1.0], [2.0]]
    print(ws["C1"])  # None
    print(formulon.evaluate_formula("=ROUND(PI(),4)"))  # 3.1416
bash
formulon eval '=ROUND(PI(),4)'
formulon eval --in book.xlsx '=SUM(A1:B2)'

The call does not join the dependency graph, so nothing it read becomes dirty later. Evaluate a formula shows the same call on every surface.

Pin the clock for volatile functions ​

NOW() and TODAY() read the host clock unless the workbook has a pinned time. wb.setPinnedNow(time) takes a Date (read through its local getters) or a CivilTime record; Python's set_pinned_now takes a datetime or a date. null (None) returns to the host clock. The pin is not saved with the file.

js
import createFormulon from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setFormula('A1', '=TEXT(NOW(),"yyyy-mm-dd hh:mm")')
  ws.setFormula('A2', '=TODAY()')
  wb.setPinnedNow(new Date(2026, 0, 15, 9, 30))

  console.log(ws.getValue('A1')) // 2026-01-15 09:30
  console.log(ws.getValue('A2')) // 46037
  console.log(JSON.stringify(wb.getPinnedNow())) // {"year":2026,"month":1,"day":15,"hour":9,"minute":30,"second":0}
} finally {
  wb.dispose()
}
python
from datetime import datetime

from formulon import Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    ws.set_formula("A1", '=TEXT(NOW(),"yyyy-mm-dd hh:mm")')
    ws.set_formula("A2", "=TODAY()")
    wb.set_pinned_now(datetime(2026, 1, 15, 9, 30))

    print(ws["A1"])  # 2026-01-15 09:30
    print(ws["A2"])  # 46037.0
    print(wb.get_pinned_now())  # 2026-01-15 09:30:00
bash
formulon eval --now 2026-01-15T09:30:00 '=TEXT(NOW(),"yyyy-mm-dd hh:mm")'

Setting or clearing the pin marks every formula dirty. Without a pin, a volatile function is evaluated again when an edit or recalc() calculates it, not on every read. Recalculation gives the accepted range.