API conventions
The JavaScript and Python APIs follow the same rules, so what you learn from one method carries over to the rest of its family and to the other language.
Python names are the snake_case forms of the JavaScript ones (updateCellFormat is update_cell_format), and a Python keyword argument has the name of the JavaScript object key.
This page states each rule once. The WASM API and Python API pages list the methods that follow them.
Reading values
A read returns a calculated value
With the default calculation mode, CalcMode.Auto, a read first computes every dirty cell, so getValue after setFormula needs no recalc() call. The same holds for save, which computes dirty cells before it writes. Under CalcMode.Manual nothing is computed until recalc(): a read returns the value from the last calculation, and null (Python None) for a cell that was never calculated. AutoNoTable behaves like Auto but skips data tables.
import createFormulon from '@libraz/formulon';
const formulon = await createFormulon();
const wb = formulon.Workbook.createDefault();
try {
const ws = wb.sheet(0);
ws.setValue('A1', 2);
ws.setFormula('A2', '=A1*10');
console.log(ws.getValue('A2')); // 20
wb.setCalcMode(formulon.CalcMode.Manual);
ws.setValue('A1', 5);
console.log(ws.getValue('A2')); // 20
wb.recalc();
console.log(ws.getValue('A2')); // 50
} finally {
wb.dispose();
}import formulon
with formulon.Workbook.create_default() as wb:
ws = wb.sheet(0)
ws["A1"] = 2
ws["A2"] = "=A1*10"
print(ws["A2"]) # 20.0
wb.set_calc_mode(formulon.CalcMode.MANUAL)
ws["A1"] = 5
print(ws["A2"]) # 20.0
wb.recalc()
print(ws["A2"]) # 50.0recalc() is the verb for "compute the dirty cells now"; wb.hasDirtyCells() reports whether any are waiting. A volatile function such as NOW() or RAND() is evaluated again when a change or recalc() marks it dirty, not on every read. A loaded file starts with its formulas dirty, so under Auto the first read or save recomputes the workbook. To read the values the file carries instead, call setCalcMode(CalcMode.Manual) right after loading, and setCalcOnSave(false) as well to save them unchanged.
Because a read can compute, it can fail with the recalculation statuses (StatusCode.Graph*), and a read made from inside an iterative-calculation progress callback throws StatusCode.GraphRecalcReentrant.
Native values and typed values
getValue, getValues, listCells, getCellsInRange, iterRows and evaluateFormula return native values:
| Cell content | JavaScript | Python |
|---|---|---|
| Empty | null | None |
| Number | number | float |
| Boolean | boolean | bool |
| Text | string | str |
| Excel error | ExcelError | ExcelError |
| Array result | NativeValue[][] | list of rows |
An ExcelError has a code (ErrorCode) and prints as #DIV/0!. An Excel error is a value you read, never an exception. Python returns numbers as float because every Excel number is a double.
import createFormulon from '@libraz/formulon';
const formulon = await createFormulon();
const wb = formulon.Workbook.createDefault();
try {
const ws = wb.sheet(0);
ws.setValue('A1', '=1/0');
const value = ws.getValue('A1');
console.log(value instanceof formulon.ExcelError); // true
console.log(String(value)); // #DIV/0!
console.log(value instanceof formulon.ExcelError && value.code === formulon.ErrorCode.Div0); // true
console.log(ws.getTypedValue('A1').kind === formulon.ValueKind.Error); // true
} finally {
wb.dispose();
}import formulon
with formulon.Workbook.create_default() as wb:
ws = wb.sheet(0)
ws["A1"] = "=1/0"
value = ws["A1"]
print(isinstance(value, formulon.ExcelError)) # True
print(value) # #DIV/0!
print(value.code == formulon.ErrorCode.DIV0) # True
print(ws.get_typed_value("A1").kind == formulon.ValueKind.ERROR) # TrueThe tagged Value, which names its kind, comes from getTypedValue, getTypedValues, evaluateTypedFormula and evaluateTypedFormulaArray (Python get_typed_value, get_typed_values, evaluate_typed_formula, evaluate_typed_formula_array). Use it when the tag matters, for example to tell a text cell holding "1" from a number, or to write a grid back without losing types: setValues accepts the result of getTypedValues, and a TextValue is always stored as text. formulon.toNative(value) (Python formulon.to_native(value)) converts a Value you already hold.
In Python, ws["A1"], ws[row, col] and ws["A1:B2"] read and write native values, and the range form is a list of rows. get_value and get_values give the same results.
Evaluating a formula
formulon.evaluateFormula(formula) and ws.evaluateFormula(cell, formula) (Python formulon.evaluate_formula, ws.evaluate_formula) return the whole result: a scalar for a 1x1 result and a two-dimensional array otherwise. ws.evaluateFormulaArray(cell, formula) always returns a two-dimensional array, and the evaluateTyped… forms return tagged values.
import createFormulon from '@libraz/formulon';
const formulon = await createFormulon();
console.log(formulon.evaluateFormula('=SUM(1,2,3)')); // 6
console.log(formulon.evaluateFormula('=SEQUENCE(1,1)')); // 1
console.log(formulon.evaluateFormula('=SEQUENCE(2,2)')); // [ [ 1, 2 ], [ 3, 4 ] ]import formulon
print(formulon.evaluate_formula("=SUM(1,2,3)")) # 6.0
print(formulon.evaluate_formula("=SEQUENCE(1,1)")) # 1.0
print(formulon.evaluate_formula("=SEQUENCE(2,2)")) # [[1.0, 2.0], [3.0, 4.0]]Writing values
Formulas and text
A string that starts with = passed to setValue, setValues, set_value, set_values or ws["A1"] = … is entered as a formula, through the same path and with the same failures as setFormula. A lone = is a syntax error. A string that starts with +, -, @ or the fullwidth = is text. setText (Python set_text) always stores text, and a tagged TextValue does too.
Enter text you did not write yourself with setText. A cell value that arrives from a user or a file and starts with = would otherwise become a formula.
When setValues fails part-way on a syntax error, the cells before the failing one stay written, and the error context names the row= and col= of the failure.
Syntax errors
A formula that does not parse fails the call that entered it. The error is a FormulonError (Python FormulaSyntaxError, which is also a ValueError but not an InvalidArgumentError).
codeis a parser status from 1000 to 1014.parseError(Pythonparse_error, with the same five fields) says where.startandendare UTF-16 offsets into the text you passed, andlineandcolumnare 1-based.parseReferenceand the A1 arguments fail the same way, with status 1004 and a span over the whole text.
import createFormulon from '@libraz/formulon';
const formulon = await createFormulon();
const wb = formulon.Workbook.createDefault();
try {
const ws = wb.sheet(0);
ws.setValue('A1', '=SUM(1,2)');
console.log(ws.getValue('A1')); // 3
ws.setText('A2', '=SUM(1,2)');
console.log(ws.getValue('A2')); // =SUM(1,2)
try {
ws.setValue('A3', '=SUM(1,');
} catch (e) {
console.log(e.code, e.parseError.start, e.parseError.end, e.parseError.column); // 1000 7 7 8
}
} finally {
wb.dispose();
}import formulon
with formulon.Workbook.create_default() as wb:
ws = wb.sheet(0)
ws["A1"] = "=SUM(1,2)"
print(ws["A1"]) # 3.0
ws.set_text("A2", "=SUM(1,2)")
print(ws["A2"]) # =SUM(1,2)
try:
ws["A3"] = "=SUM(1,"
except formulon.FormulaSyntaxError as e:
pe = e.parse_error
print(pe.start, pe.end, pe.line, pe.column) # 7 7 1 8#NAME? is the result of a well-formed formula that names something unknown. A formula read from a file that does not parse still evaluates to #NAME?, because the file is not a call you made.
Dates
setValue, setValues and ws[...] = accept a JavaScript Date (read through its local getters, milliseconds dropped, as Python reads a naive datetime) and a Python date, datetime or time.
- Every
Dateargument in the API is read the same way, with one exception:ThreadedCommentInput.createdreads the UTC getters, because a threaded comment stores its timestamp in UTC (see Comments and notes). - The value is stored as a serial number in the workbook's date system.
- When the cell's effective format is General, the cell also gets a built-in format: id 14 for a date, id 22 for a date with a time (a JavaScript
Dateat local midnight counts as a date),h:mm:ssfor a time. - Ids 14 and 22 are written in the profile's own pattern,
m/d/yyandm/d/yy h:mmunder en-US andyyyy/m/dandyyyy/m/d h:mmunder ja-JP. - A Python
datetimewith a time zone raisesValueError, and atimedeltaraisesTypeError.
getDate (Python get_date) reads a date cell back as a Date whose local wall-clock fields equal the serial's calendar fields (Python: a naive datetime with those fields), so ws.setValue(cell, ws.getDate(cell)) stores the same value back.
- It returns
nullfor an empty cell and fails withInvalidArgumentfor a cell that is not a number. - A local time that falls in a daylight-saving gap resolves as the
Dateconstructor does, and a time that exists is never shifted. - A plain
getValueof a date cell stays a number, because a date is a number with a format.
import createFormulon from '@libraz/formulon';
const formulon = await createFormulon();
const wb = formulon.Workbook.createDefault();
try {
const ws = wb.sheet(0);
ws.setValue('A1', new Date(2026, 10, 8));
console.log(ws.getValue('A1')); // 46334
console.log(ws.getDisplayText('A1').text); // 11/8/26
console.log(ws.getDate('A1').toDateString()); // Sun Nov 08 2026
} finally {
wb.dispose();
}import datetime
import formulon
with formulon.Workbook.create_default() as wb:
ws = wb.sheet(0)
ws["A1"] = datetime.date(2026, 11, 8)
print(ws["A1"]) # 46334.0
print(ws.get_date("A1")) # 2026-11-08 00:00:00Colours
- A colour you pass is a
ColorInput: a'#RRGGBB'or'#AARRGGBB'string, or aColorobject. - A colour you read is a
Colorwithkind(ColorKind),argb(a number, AARRGGBB),theme,tintandindexed; only the fields that matchkindare meaningful. - The same two types apply to fonts, fills, borders, conditional formats, sparklines, shapes, the chart parts and the tab colour (
ws.getTabColor(),ws.setTabColor(color | null)). - A theme or indexed colour is not resolved to RGB by a read;
wb.resolveColorrenders it.
import createFormulon from '@libraz/formulon';
const formulon = await createFormulon();
const wb = formulon.Workbook.createDefault();
try {
const ws = wb.sheet(0);
ws.updateCellFormat('A1', { font: { color: '#C00000' } });
const color = ws.getCellFormat('A1').font.color;
console.log(color.kind === formulon.ColorKind.Rgb); // true
console.log(color.argb.toString(16)); // ffc00000
} finally {
wb.dispose();
}import formulon
with formulon.Workbook.create_default() as wb:
ws = wb.sheet(0)
ws.update_cell_format("A1", font={"color": "#C00000"})
color = ws.get_cell_format("A1").font.color
print(color.kind == formulon.ColorKind.RGB) # True
print(hex(color.argb)) # 0xffc00000Rows, columns and ranges
Every row or column span is a closed interval (first, last), inserts and deletes included: insertRows(first, last) inserts last - first + 1 rows before row first, as setRowHeight(first, last, height) styles them. A first greater than last is InvalidArgument. Both forms also accept a span string, '3:5' for rows and 'C:E' for columns.
A rectangle argument takes a CellRect or an A1 string such as 'A1:B2'; any other value throws TypeError in every binding (Sheet.listShowPhoneticCells range must be a CellRect or an A1 string).
Wherever a record has a field that holds a cell or a range, that field takes an A1 string too:
PivotInput.anchor: 'E1', therangesof a validation or a conditional format, a print area.A field that holds an array of ranges takes a single string.
A
SheetRectfield takes'Sheet1!A1:B2'; without a sheet prefix the string resolves on the record's own sheet.A string with several space-separated areas is not accepted.
The exceptions that stay numeric are the anchors with EMU offsets (
DrawingAnchorInput) and the base cell ofReferenceNotationOptions.A field that holds one rectangle is named
range, and a field that holds a list of them is namedranges, in every record and in Python keyword arguments (TableInput.range,ArrayFormula.range,ParsedReference.range,ProtectedRangeInput.ranges,get_values(range)).A rectangle on its own sheet is a
CellRect; one that names its sheet is aSheetRect.A single cell is a
CellAddress({ row, col }), in a field calledcell,active,topLeftorlocation, and takes an A1 cell such as'B2'on input.A defined name's
scopeis aSheetRefornullfor the workbook.
import createFormulon from '@libraz/formulon';
const formulon = await createFormulon();
const wb = formulon.Workbook.createDefault();
try {
const ws = wb.sheet(0);
ws.setValue('A3', 'moved');
ws.insertRows(2, 4); // first, last: three rows before row index 2
console.log(ws.getValue('A6')); // moved
ws.setRowHeight('3:5', 30); // first, last: rows 3 to 5, as a span string
ws.setColumnWidth('C:E', 14);
console.log(ws.getRowHeightPt(2), ws.getRowHeightPt(4)); // 30 30
} finally {
wb.dispose();
}import formulon
with formulon.Workbook.create_default() as wb:
ws = wb.sheet(0)
ws["A3"] = "moved"
ws.insert_rows(2, 4) # first, last: three rows before row index 2
print(ws["A6"]) # moved
ws.set_row_height("3:5", 30) # first, last: rows 3 to 5, as a span string
ws.set_column_width("C:E", 14)
print(ws.get_row_height_pt(2), ws.get_row_height_pt(4)) # 30.0 30.0Four readers cover a block of cells:
getValues(range?)returns a dense grid with a slot for every position.listCells(range?)lists only the cells that hold a value or a formula.getCellsInRange(range?, { cursor, limit })pages through a large range.iterRows(range?)(Pythoniter_rows) walks rows of native values.
getTypedValues(range?) is getValues with tagged values. getUsedRange() returns the bounding rectangle of the cells that hold a value or a formula, formatting not included, or null.
The five block reads share one default: an omitted or null range is the used range. A sheet with no used range gives [] from getValues, no rows from iterRows, no cells from listCells, and an empty page with nextCursor: null from getCellsInRange. Sheets, cells and structure compares them.
A call with more positional arguments than a method declares throws TypeError (takes at most <n> arguments).
Workbook.load takes a Uint8Array, an ArrayBuffer or any typed-array view. Read a Blob with await blob.arrayBuffer() first.
A Workbook is iterable: for (const ws of wb) yields its sheets in order.
Optional trailing arguments
A trailing argument with an obvious default can be left out:
getPrecedents(cell)andgetDependents(cell)follow one level (depth1).recalcParallel()chooses the thread count itself (threadCount0, at most 8).copySheet(index)appends the copy.evaluateCfRange(range)evaluates time-period rules against today: the pinned date when the workbook has one, otherwise the host's date.
Python takes the same defaults (get_precedents, get_dependents, copy_sheet, evaluate_cf_range). An argument beyond the ones a method declares throws TypeError naming the method and how many arguments it takes.
Set, update and patch
update and update<X> always change only the keys you pass. The argument is a patch (TablePatch, ShapePatch, and so on), and a key you leave out keeps its value. set<X> follows the type of its argument: a record replaces the whole value and an input record fills in defaults for what it leaves out.
- A record that lives once per sheet or workbook (sheet protection, an AutoFilter, the pinned time, the theme, a chart title or legend) is replaced by
set<X>(record)and removed byset<X>(null); there is noremove<X>for it, andupdate<X>(patch)merges.ws.setSheetProtection(null)unprotects the sheet andws.updateSheetProtection({ allowFormatCells: true })changes one flag. reset<X>restores the default (resetRowHeight,resetColumnWidth,resetTheme, andws.ooxml.resetCellXfIndexon the XF layer).remove<X>fails withStatusCode.NotFoundwhen the thing is absent, andclear<X>does nothing when there is nothing to clear.- A patch accepts
null(PythonNone) only for a key that can be cleared, meaning a key named in the patch type'sClearableparameter,Patch<T, Clearable>(SheetProtectionPatchclearsalgorithmName,hashValue,saltValue,legacyPasswordHashandspinCount). It clears that key, and in TypeScriptnullon any other key is a compile error. At run time it throwsTypeError. - An empty patch changes nothing.
- An unknown key throws
TypeErrorat any depth, so a misspelled{ font: { bogus: 1 } }fails instead of being ignored. The keys of a record a getter returns are known: a key that exists on the record but not on the patch (objectId,kind,columns) is ignored. - An input record (
TableInput,ChartInput,FontInput,CommentInput, and the other*Inputtypes) states what it sets and defaults the rest: an omitted key takes its documented default, andnullis accepted only where the type says so. A setter accepts the record its getter returns, sows.setComment('A1', ws.getComment('B1'))andwb.setWorkbookProtection(wb.getWorkbookProtection())need no conversion; the keys that cannot be set are ignored. An unknown key in an input record throwsTypeError.
import createFormulon from '@libraz/formulon';
const formulon = await createFormulon();
const wb = formulon.Workbook.createDefault();
try {
const ws = wb.sheet(0);
ws.updateCellFormat('A1:B1', { font: { bold: true } }); // other format keys keep their values
console.log(ws.getCellFormat('A1').font.bold); // true
ws.updateCellFormat('A1:B1', { font: { bold: null } }); // null clears a clearable key
console.log(ws.getCellFormat('A1').font.bold); // null
} finally {
wb.dispose();
}In Python a partial update takes keyword-only arguments that default to UNCHANGED. Pass a value to set it, leave the argument out to keep it, and pass None to clear a key that can be cleared. None anywhere else is a TypeError. Do not use None to mean "unchanged".
import formulon
with formulon.Workbook.create_default() as wb:
ws = wb.sheet(0)
ws.update_view(zoom_pct=125) # other view fields keep their values
print(ws.get_view().zoom_pct, ws.get_view().show_grid_lines) # 125 True
ws.set_values("A1", [["Region"], ["East"]])
table = ws.add_table(formulon.TableInput(range="A1:A2", name="Sales"))
table.update_style_options(style_name=None) # None clears the table style
print(table.get_style_options().style_name) # NoneA Python add or set that takes a record takes a dataclass (ws.set_auto_filter(AutoFilterInput("A1:C9")), ws.add_chart(ChartInput(type=ChartPlotType.BAR, range="A1:B5")), cache.set_worksheet_source(PivotWorksheetSourceInput(range="A1:B5"))), and the record a getter returns is accepted in its place. An update_* method takes its keys keyword-only. set_theme_colors, set_theme_script_font, set_cell_phonetic_properties, set_selection, set_source on a chart and set_field_date_group follow the same shape.
Lookups: null or NotFound
A getter that finds a record by its own key returns null (Python None) when nothing matches, as wb.getDefinedName('Rate') does. A call that hands you a handle or a result, such as wb.sheet('Missing'), wb.table('Missing'), ws.pivot('Missing'), a drawing handle, or chart.getData(), throws FormulonError with StatusCode.NotFound instead. A position past the end of a collection throws StatusCode.IndexOutOfRange.
Python's wb[key] counts a negative index from the end, as a sequence does: wb[-1] is the last sheet. wb.sheet(-1) and every other call that takes a position treats a negative one as past the start and raises IndexOutOfRangeError.
Errors: a wrong call and a refused value
An argument error reads <Class>.<method> <path> <constraint> in the WebAssembly package, the native package and Python alike:
Sheet.updateView patch.zoomPct must be an integer
Sheet.remove_validation validation 99 is out of range (0 items)The class is the one the call was made on (Sheet, WorkbookOoxml, PivotCache, Picture, Chart; Workbook.load for a static factory; Formulon.<fn> for a module function). The path is the parameter, extended by the record field for a nested value (patch.sparklines[2].location). The constraint comes from a fixed vocabulary:
| Constraint | Meaning |
|---|---|
must be a boolean, a number, a string, an object, an array | The value has the wrong type |
must be an integer | A fractional, NaN or infinite number where an integer is expected |
is required | A required key or argument is missing |
has no field <key> | An unknown key in a record |
must not be null | null where the key cannot be cleared |
is too large | An integer beyond 32 bits |
must not be negative | A negative count, length or coordinate |
must be in <lo>..<hi> | A value outside the range the parameter accepts |
must not be empty | An empty string or list where one is not accepted |
<v> is out of range (<n> items) | A position past the end of a collection of <n> items |
takes at most <n> arguments | More positional arguments than the method declares |
The class of the error follows the constraint:
| Case | JavaScript | Python |
|---|---|---|
| A wrong type | TypeError | TypeError |
| A fractional, NaN or infinite number | RangeError | TypeError (any float or bool where an integer is expected) |
| An integer beyond 32 bits | RangeError | ValueError |
| A position (a sheet index, a collection index) that is negative or past the end | FormulonError with StatusCode.IndexOutOfRange (StatusCode.SheetIndexOutOfRange for a sheet) | IndexOutOfRangeError (StatusCode.SHEET_INDEX_OUT_OF_RANGE for a sheet) |
| A coordinate (a row or a column) or a quantity (a count, a length) that is negative or outside the grid or its limit | FormulonError with StatusCode.InvalidArgument | InvalidArgumentError |
TypeError and RangeError are thrown before the engine runs. A value that is representable but that the engine refuses throws FormulonError with a status code (Python: the matching subclass), for example AlreadyExists or PreconditionFailed. Match on the class and code, not on the text; the message is for display.
A boolean argument or field takes true or false only. setDate1904('yes'), setCalcOnSave(null), parseReference(text, { r1c1: 1 }) and updateView({ showGridLines: 1 }) throw TypeError, as do the Python counterparts (set_date1904(1), format_reference(range, absolute=1)). A value is never read as truthy or falsy.
A string argument or field takes a JavaScript string only. An ArrayBuffer or a one-byte typed array there throws TypeError (must be a string) in the WebAssembly and native packages alike.
recalcParallel() shows the cases: threadCount is optional (0 = automatic, capped at 8); a non-number is TypeError, a fractional or non-finite number RangeError, a negative number InvalidArgument, and one above 8 SecurityResourceLimit.
An Excel error such as #DIV/0! is neither: it is a value you read, as Evaluate a formula shows. A formula that does not parse is a refused value with a position; see Syntax errors.
Try =1/0 or =SQRT(-1), then wrap the formula in IFERROR, and compare the result with the failure that loading 16 bytes of noise throws.
Cell errors and host failures
An error returned by a formula is a value: the call itself succeeded and the error arrived with kind = Error. A host failure travels a different channel entirely — no value comes back and a FormulonError is thrown. Both run here, next to each other.
Powered by the real Formulon engine (WASM) — it runs entirely in your browser, nothing is uploaded.
Enums
An enum is a table of numbers wherever the C library defines a set of values: a const object with a matching union type in JavaScript (FillPattern.Solid), an IntEnum in Python (FillPattern.SOLID). A table is a set of strings only when the C library also uses strings, as for table totals functions.
Some tables look alike and stay separate on purpose:
ReadingOrder(cell alignment) andCfDataBarDirection(data bars) hold the same three directions, because both name a reading direction. Each keeps its own name so a call reads in the terms of its feature.AnchorKindsays what kind of anchor an object has, andAnchorEditAssays how a two-cell anchor follows row and column edits.DatePeriod(conditional-format time periods),DynamicFilterType(AutoFilter) andPivotFilterKind(pivot filters) are separate tables because their sets differ, but a period they share is spelled the same way in all three (Today,ThisMonth,NextQuarter).Colappears only in coordinate names (firstCol,lastCol). An enum member spells it out (PivotAxis.Column,ChartBarDirection.Column,PivotShowValuesAs.PercentOfColumn).ChartDataSource.kindis aChartSourceKindnumber (None,Ref,Literal), not a string.
The rule, date-period and value-object numbers of conditional formats, the validation types, the comparison operators (ComparisonOperator, shared by conditional formats, validation and AutoFilter), the icon sets (IconSetName) and the parser codes (ParseErrorCode) are tables too. formulon.enumName(table, value) (Python enum_name) gives the member name of a number, as in enumName(CfRuleType, 1).
Part-level members
wb.ooxml and ws.ooxml (Python wb.ooxml, ws.ooxml) hold the members that work on the parts of the file, with index numbers and XML fragments as arguments:
- Workbook: the cell XF, font, fill, border, number format, DXF and cell-style-XF tables (
getCellXf,addCellXf,listFonts,addNumberFormatand the others in each family), the named cell styles, and the passthrough parts. - Sheet: the stored XML fragments (
getPageSetupXmland its setters, and the same for auto-filter, margins, print options, header and footer, and sheet properties), the XF index of a cell, row or column, and the column and row styles.
Everything an everyday task needs sits directly on wb and ws: updateCellFormat and getCellFormat change and read a format by name, updateCellFormat('B:B', …) formats a whole column, setDefaultFont and the theme members stay where they are.
The XF-layer reads and resets, such as ws.ooxml.getEffectiveStyle(row, col) for the style the engine draws and ws.ooxml.resetCellXfIndex(row, col), are on ooxml. Reach for ooxml when the task is about the file's own tables. The ooxml property always returns the same object, and the members are not repeated on wb or ws.
import createFormulon from '@libraz/formulon';
const formulon = await createFormulon();
const wb = formulon.Workbook.createDefault();
try {
console.log(wb.ooxml.getFont(0).name); // Calibri
} finally {
wb.dispose();
}import formulon
with formulon.Workbook.create_default() as wb:
print(wb.ooxml.get_font(0).name) # CalibriSheet references and handles
The key is a SheetRef, and every workbook method that targets a sheet accepts the same three forms:
| Form | Example | Notes |
|---|---|---|
| Index | wb.sheet(0) | 0-based position. An index past the last sheet fails with StatusCode.SheetIndexOutOfRange (Python IndexOutOfRangeError) |
| Name | wb.sheet('Data') | Compared case-insensitively. An unknown name fails with StatusCode.NotFound (Python NotFoundError) |
| Handle | wb.setActiveSheet(ws) | A Sheet of the same workbook. A handle of another workbook is a TypeError |
A handle identifies a sheet, not a position or a name:
- The workbook keeps one handle per sheet, so
wb.sheet(0) === wb.sheet('Sheet1')for the sheet at index 0 namedSheet1(Pythonis). - A handle follows its sheet across add, copy, move, and rename.
ws.indexandws.namereport the current position and name. - After
removeSheet, every use of that handle throwsStatusCode.NotFound. After the workbook is disposed (Python: closed), every use throwsStatusCode.BindingInvalidHandle(PythonWorkbookClosedError).
Objects other than sheets work the same way. A table, a PivotTable, a pivot cache, a chart, a picture, a shape and a slicer are handles too: ws.table(ref), ws.pivot(name), wb.pivotCache(id), ws.chart(id), ws.picture(id), ws.shape(id) and ws.slicer(id).
- The parent keeps
add*,remove*,list*and the lookup, and everyadd*returns the handle; an operation on the object is a method of the handle (ws.pivot('Sales').addDataField(spec),ws.chart(1).setTitle('Revenue')). - Chart, picture, shape and slicer share the members of
Drawing(ws.drawing(id)). - A handle follows its object while others are added or removed and throws
StatusCode.NotFoundonce the object is gone. - Python has the same classes:
formulon.Table,Pivot,PivotCache,Drawing,Picture,Chart,ShapeandSlicer.
Lifetime
wb.dispose() (Python wb.close(), or the with block) releases the workbook at that call. After it, every call on the workbook or its Sheet handles throws StatusCode.BindingInvalidHandle (Python WorkbookClosedError). A workbook you forget to dispose may be released when the garbage collector reclaims it, in both npm packages. That is best-effort: the collector can run late or never, so release a workbook with dispose() when you need the memory back at a known point.
Rules kept on purpose
add* returns one of three forms
- It returns a handle when the new thing is an object you go on to use (
addSheet,addTable,addPivot,addChart,addShape,addSlicer,addPicture,addPivotCache). - It returns the index or id of the new record when later calls address the record by that number (
addValidation,addCfRule,addProtectedRange,addSparklineGroup,addFont,addCellXf). - It returns what it created when the record has no identity apart from its position or key:
addMergethe storedCellRect,addDataTablethe top-leftCellAddressof the result range,addPersonthe stored id.
Python keeps get_ and set_ methods
Each name is the snake_case form of the JavaScript one, and most getters take a cell, a range or a key, which a property cannot. A Python argument that shares a name with a built-in keeps it.
setComment replaces, and setHyperlink replaces a link with the same range
A cell has at most one comment, so setComment(cell, comment) sets or replaces it.
Hyperlinks may overlap, as in Excel:
setHyperlink(link)replaces the link on exactlylink.rangeand appends it otherwise.removeHyperlink(range)removes every link that intersects the range.removeHyperlinkAt(hyperlinkIndex)removes a single link by its position inlistHyperlinks().
Tables and pivots belong to the sheet
ws.addTable(input), ws.table(ref) and ws.pivot(ref) work the same way, and a table index is local to its sheet. A table name is unique in the workbook, so wb.table(name) is the one workbook-wide lookup and finds it from anywhere.
A negative position is an error
It is StatusCode.IndexOutOfRange (SheetIndexOutOfRange for a sheet) wherever a call takes a position. Only Python wb[-1] counts from the end, as a sequence does and returns the last sheet.
One error class in JavaScript
FormulonError carries code, message, context and, for a syntax error, parseError; Python has subclasses for the same statuses.
A cell argument names its sheet only through the sheet handle
wb.sheet('Sheet1').getValue('A1') reads a cell of another sheet; ws.getValue('Sheet1!A1') is refused with that advice.