Skip to content

Open, edit and save a workbook ​

Use this when a program receives a spreadsheet file, changes some cells and writes a file back. The examples create their input file first, so each one runs on its own.

Open a file ​

Workbook.load takes the file's bytes: a Uint8Array, a Node Buffer or an ArrayBuffer. Python's Workbook.load also takes a path or a binary file object. The format is detected from the package contents, so an .xlsb file opens through the same call as an .xlsx file and the file name plays no part.

js
import { readFile, writeFile } from 'node:fs/promises'
import createFormulon from '@libraz/formulon'

const formulon = await createFormulon()
const seed = formulon.Workbook.createDefault()
try {
  seed.sheet(0).setValues('A1', [['Region', 'Sales'], ['East', 120]])
  await writeFile('report.xlsx', seed.save())
} finally {
  seed.dispose()
}

const wb = formulon.Workbook.load(await readFile('report.xlsx'))
try {
  console.log(wb.listSheets().map((s) => s.name).join()) // Sheet1
  console.log(wb.sheet('Sheet1').getValue('B2')) // 120
} finally {
  wb.dispose()
}
python
from formulon import Workbook

with Workbook.create_default() as seed:
    seed[0]["A1:B2"] = [["Region", "Sales"], ["East", 120]]
    seed.save("report.xlsx")

with Workbook.load("report.xlsx") as wb:
    print(",".join(s.name for s in wb.list_sheets()))  # Sheet1
    print(wb["Sheet1"]["B2"])  # 120.0

Bytes that are not a workbook package throw FormulonError with a StatusCode.Io* code; Python raises InvalidFileError. Errors and diagnostics shows how to tell those apart, and Workbook lifecycle lists what the reader keeps.

Edit and save as XLSX ​

Edits go through the Sheet handle. save() returns XLSX bytes in JavaScript. In Python, save(path) writes the file and save() without a path returns the bytes. Both compute dirty formulas first, so the file carries current cached values for readers that do not calculate.

js
import { readFile, writeFile } from 'node:fs/promises'
import createFormulon from '@libraz/formulon'

const formulon = await createFormulon()
const seed = formulon.Workbook.createDefault()
try {
  seed.sheet(0).setValues('A1', [['Qty', 'Price'], [3, 2.5]])
  await writeFile('order.xlsx', seed.save())
} finally {
  seed.dispose()
}

const wb = formulon.Workbook.load(await readFile('order.xlsx'))
try {
  const ws = wb.sheet(0)
  ws.setValue('C1', 'Total')
  ws.setFormula('C2', '=A2*B2')
  await writeFile('order.xlsx', wb.save())
} finally {
  wb.dispose()
}

const back = formulon.Workbook.load(await readFile('order.xlsx'))
try {
  console.log(back.sheet(0).getFormula('C2')) // =A2*B2
  console.log(back.sheet(0).getValue('C2')) // 7.5
} finally {
  back.dispose()
}
python
from formulon import Workbook

with Workbook.create_default() as seed:
    seed[0]["A1:B2"] = [["Qty", "Price"], [3, 2.5]]
    seed.save("order.xlsx")

with Workbook.load("order.xlsx") as wb:
    ws = wb[0]
    ws["C1"] = "Total"
    ws.set_formula("C2", "=A2*B2")
    wb.save("order.xlsx")

with Workbook.load("order.xlsx") as back:
    print(back[0].get_formula("C2"))  # =A2*B2
    print(back[0]["C2"])  # 7.5

Save as XLSB ​

save(WorkbookFormat.Xlsb) returns XLSB bytes in JavaScript. In Python the extension of the path decides: .xlsx and .xlsb are accepted, and any other extension raises an error unless format= is given. save() without a format always writes XLSX, also for a workbook that was loaded from an XLSB file, so pass the format again when the output must stay XLSB.

js
import { readFile, writeFile } from 'node:fs/promises'
import createFormulon, { WorkbookFormat } from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  wb.sheet(0).setValue('A1', 42)
  await writeFile('book.xlsb', wb.save(WorkbookFormat.Xlsb))
} finally {
  wb.dispose()
}

const back = formulon.Workbook.load(await readFile('book.xlsb'))
try {
  console.log(back.sheet(0).getValue('A1')) // 42
} finally {
  back.dispose()
}
python
from formulon import Workbook

with Workbook.create_default() as wb:
    wb[0]["A1"] = 42
    wb.save("book.xlsb")

with Workbook.load("book.xlsb") as back:
    print(back[0]["A1"])  # 42.0

The XLSB writer does not emit everything the model can hold. saveWithDiagnostics(format) (Python save_with_diagnostics(format=...)) returns the bytes together with counters of what was left out, and a nonzero deferredFeatureCount means the XLSB file differs from the model. An XLSX save reports through the same counter, for example a custom view of an XLSB source that has no XLSX form.

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

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setValue('A1', 1)
  ws.setFormula('A2', '=A1+1')
  const out = wb.saveWithDiagnostics(WorkbookFormat.Xlsb)
  console.log(out.bytes.length > 0) // true
  console.log(out.deferredFeatureCount, out.downgradedFormulaCount) // 0 0
} finally {
  wb.dispose()
}
python
from formulon import Workbook, WorkbookFormat

with Workbook.create_default() as wb:
    ws = wb[0]
    ws["A1"] = 1
    ws.set_formula("A2", "=A1+1")
    out = wb.save_with_diagnostics(format=WorkbookFormat.XLSB)
    print(len(out.bytes) > 0)  # True
    print(out.deferred_feature_count, out.downgraded_formula_count)  # 0 0

XLSB lists what each container keeps.

Read the values a file carries without recalculating ​

A file opens with every formula dirty when Excel would recalculate it on open: it sets fullCalcOnLoad or does not carry the current calcId, and it is not in Manual mode. The first read or save then recomputes them. Any other file opens with its stored values, and wb.recalcFull() (Python recalc_full()) recomputes every formula of it. To read the values stored in a file that loads dirty, switch to manual calculation right after loading: a read then returns the cached value, or null where the file has none. setCalcOnSave(false) makes save write the cached values unchanged, which keeps a file that was last calculated by Excel exactly as it was.

js
import { readFile, writeFile } from 'node:fs/promises'
import createFormulon, { CalcMode } from '@libraz/formulon'

const formulon = await createFormulon()
const seed = formulon.Workbook.createDefault()
try {
  const ws = seed.sheet(0)
  ws.setValue('A1', 2)
  ws.setFormula('B1', '=A1*10')
  await writeFile('cached.xlsx', seed.save())
} finally {
  seed.dispose()
}

const wb = formulon.Workbook.load(await readFile('cached.xlsx'))
try {
  wb.setCalcMode(CalcMode.Manual)
  wb.setCalcOnSave(false)
  const ws = wb.sheet(0)
  ws.setValue('A1', 3)

  console.log(ws.getValue('B1')) // 20
  await writeFile('unchanged.xlsx', wb.save())
} finally {
  wb.dispose()
}
python
from formulon import CalcMode, Workbook

with Workbook.create_default() as seed:
    seed[0]["A1"] = 2
    seed[0].set_formula("B1", "=A1*10")
    seed.save("cached.xlsx")

with Workbook.load("cached.xlsx") as wb:
    wb.set_calc_mode(CalcMode.MANUAL)
    wb.set_calc_on_save(False)
    ws = wb[0]
    ws["A1"] = 3

    print(ws["B1"])  # 20.0
    wb.save("unchanged.xlsx")
bash
# dump opens the workbook in Manual mode, so it prints the cached values
formulon dump --view formulas --json cached.xlsx

recalc() computes the dirty cells at the moment you choose, in either mode. Recalculation covers the calculation modes.

Convert or recalculate a file with the CLI ​

The formulon CLI recalculates a workbook and writes a new one without any code. The output container follows the extension of -o, so the same command converts XLSX to XLSB. The input format is detected from the bytes.

bash
formulon recalc report.xlsx -o report.xlsb
formulon recalc report.xlsb -o report.xlsx
formulon recalc report.xlsx -o out.bin --format xlsb

Loss warnings for features the output container cannot hold go to stderr. CLI reference lists the options and exit codes.