Skip to content

Styles and workbook settings ​

Cell formats, the style tables behind them, named cell styles, and the settings and protection stored on the workbook itself.

Format a small table

A1:C5 holds a price list. Fonts, fills, borders and number formats are set from the Home tab and change how a cell displays, not what it stores.

Powered by the real Formulon engine (WASM) — it runs entirely in your browser, nothing is uploaded.

What you can do ​

Default style table ​

Workbook.createDefault() (and fm_workbook_create_default) starts with Excel's minimum style table: font, border, and cell-style index 0, plus fill index 0 (none) and 1 (gray125).

The first non-duplicate wb.ooxml.addFont() or wb.ooxml.addBorder() then returns 1, and the first new wb.ooxml.addFill() returns 2. createForProfile() may already have a phonetic font at index 1 for a CJK locale, so always use the returned index instead of assuming a new style table starts empty.

Formatting cells ​

ws.updateCellFormat(range, patch) is the high-level way to format cells. One call merges a number format, font, fill, border, alignment and protection patch into every cell of the range, and ws.getCellFormat(cell) reads the resulting CellFormat.

  • An omitted key keeps its value.
  • null (Python None) clears a nullable key.
  • A colour in a patch is a '#RRGGBB' string or a Color.

A whole-column ("D:D"), whole-row ("3:3") or whole-sheet range formats that axis, so cells entered there later take the format. A column or row is formatted with ws.updateCellFormat('B:B', patch) or ws.updateCellFormat('3:3', patch).

Equal formats share one style record, so the index calls below, which live on wb.ooxml and ws.ooxml, are for code that manages cellXfs itself.

Python spells the call ws.update_cell_format(range, number_format=..., font={...}); see Read and write values.

Style tables and fonts ​

Part-level members ​

The part-level members (the font, fill, border, number-format and XF tables, differential formats and passthrough parts) are reached through wb.ooxml. The XF indexes of cells, rows and columns and the XML fragments of worksheet elements are reached through ws.ooxml (Python wb.ooxml.get_font(...), ws.ooxml.get_auto_filter_xml()).

wb.setDefaultFont() replaces font slot 0. wb.ooxml.setFont() replaces any existing font slot in place.

Theme-linked fonts ​

A font linked to the theme (scheme Minor or Major) takes its name from the theme when Excel would rename it. That happens:

  • when the workbook is loaded
  • when such a font is set, added or patched with a scheme
  • when the theme fonts change or a theme is applied or reset
  • when the profile changes
ProfileName taken from the theme
ja, ko, zh or thThe theme's face for the profile's script
Any otherThe theme's Latin face

A theme with no face for that script leaves the name, and size, family and charset are not touched. A save writes the name the font holds (File formats).

Font patches ​

PatchResult
States a name (updateCellFormat, font.name) without stating schemeSets scheme to None, even when the name is unchanged
Size onlyKeeps the theme link
States schemeThe stated scheme wins
A name that changes the faceTakes the family and charset Excel holds for the new face
A name that keeps the faceKeeps family and charset
States family or charsetThe stated value wins
A group with nothing set, such as font: {}Changes nothing

Clearing scheme on a name patch is what Excel does when a font name is set, because a theme-linked font is drawn with the theme's face whatever name it stores.

Completed font attributes ​

A font that states no family, charset or scheme is completed from the same face table when a file is loaded and when setDefaultFont, wb.ooxml.setFont or addFont receives it, so getFont reports the completed values. A family-less 游ゴシック reads family 3 and charset 128.

Row and column styles ​

A cell's effective formatting can also come from its row or column. An explicit cell style 0 overrides those defaults and is distinct from an unstyled cell.

MemberDoes
ws.ooxml.setColumnXfIndex() / set_column_xf_index(), ws.ooxml.setRowXfIndex() / set_row_xf_index()Replace the style XF over an inclusive span (first, last, xfIndex) or an A1 span ('B:D', '3:5') with the index
ws.ooxml.getColumnXfIndex(col), getRowXfIndex(row)Read the index back, null when there is none
resetColumnXfIndex() / resetRowXfIndex()Remove only that style assignment and retain the span's width or height, hidden, and outline attributes

A later value in an unstyled cell can take the column or row style. A row style wins when both cover the cell.

Cell XF indexes ​

ws.ooxml.setCellXfIndex(row, col, 0) is an explicit Normal style and wins over row and column styles.

Blank cells ​

A blank cell exists only while it has a format of its own: a non-default format, or an explicit default that overrides a row or column format.

OperationResult
Setting 0 on a blank with no row or column format under itStores nothing
setBlank on a blank without its own formatRemoves the cell
ws.ooxml.resetCellXfIndex() / reset_cell_xf_index()Removes the direct assignment so a blank cell inherits its row or column style again, and removes a blank that had only that format
resetCellXfIndex() on a cell with a value, formula or commentsKeeps the value, formula, and comments
resetCellXfIndex() on an absent cellThe cell stays absent

An explicit default whose row or column format is removed later stays in memory but is not saved, and a restoreRangeXfs after that removal does not bring it back. A non-blank cell keeps owning the default XF.

Reading cell XF indexes ​

MemberReads
ws.ooxml.getCellXfIndex(cell) (Python get_cell_xf_index)The cell's own XF index: 0 for a cell with content and no format of its own, and null (None) where the address has neither content nor a format of its own, which includes a blank that only inherits a row or column format
ws.ooxml.listCellXfIndices(range?) (Python list_cell_xf_indices)The cells whose own format is not 0, formatted blanks included, which listCells leaves out
ws.ooxml.getEffectiveStyle(row, col).source / get_effective_style(row, col).sourceWhether the style is inherited or a direct cell assignment

Setting and removing named styles ​

wb.setCellStyle(record) in JavaScript takes a CellStyleInput: name is required, and styleXfIndex, builtinId, outlineLevel, hidden and customBuiltin are optional. The CellStyle that getCellStyle returns passes back as is. Python uses wb.set_cell_style(CellStyle(...)) with snake-case fields. The XF identifies a named-style base, not a cell XF.

wb.removeCellStyle(name) / remove_cell_style(name) removes a named style.

All three find a built-in style by its stored name or by its name in the workbook profile's language, so getCellStyle('Comma') and, under ja_JP, getCellStyle('桁区切り [0.00]') read the same record.

ConditionResult
setCellStyle on a built-in styleKeeps its builtinId and outlineLevel
setCellStyle on a built-in style with a record carrying a different builtinIdFails with StatusCode.AlreadyExists
wb.ooxml.setCellStyleXf()Marks every built-in style that uses the changed slot customBuiltin, as Excel does when a built-in style's format is edited, so a save keeps it

How a save writes the styles is under File formats. See Presentation and geometry for themes, resolved colors, effective styles, and display text.

Phonetic guides ​

Phonetic guides can be read and written as an ordered set of UTF-16 text spans with ws.getCellPhoneticRuns(row, col) / ws.setCellPhoneticRuns(row, col, runs) (Python get_cell_phonetic_runs() / set_cell_phonetic_runs()).

ws.getCellPhoneticProperties() / ws.setCellPhoneticProperties() separately control the ruby font, kana form, and alignment. Writing a cell value clears both its readings and its properties.

Named cell styles ​

A named cell style is an entry in Excel's Cell Styles gallery. It has two parts: a style XF in the <cellStyleXfs> table that carries the format, and a CellStyle record that gives that XF a name. Cells that use the style point at it through the styleXfIndex of their own XF. The style XF table is under wb.ooxml, and the named styles are on wb.

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

const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)

const plain = {
  fillIndex: 0, borderIndex: 0, numFmtId: 0,
  horizontal: HorizontalAlign.General, vertical: VerticalAlign.Bottom, wrapText: false,
}
const fontIndex = wb.ooxml.addFont({ ...wb.ooxml.getFont(0), bold: true })
const styleXf = wb.ooxml.addCellStyleXf({ ...plain, fontIndex })
wb.setCellStyle({ name: 'Emphasis', styleXfIndex: styleXf })

// A cell XF that inherits from the style, applied to A1.
const cellXf = wb.ooxml.addCellXf({ ...plain, fontIndex, styleXfIndex: styleXf })
ws.setValue('A1', 'Total')
ws.ooxml.setCellXfIndex('A1', cellXf)
console.log(ws.getCellFormat('A1').font.bold) // true
python
import dataclasses

from formulon import CellStyle, CellXfInput, HorizontalAlign, VerticalAlign, Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    plain = CellXfInput(
        font_index=0, fill_index=0, border_index=0, num_fmt_id=0,
        horizontal=HorizontalAlign.GENERAL, vertical=VerticalAlign.BOTTOM,
        wrap_text=False,
    )
    font_index = wb.ooxml.add_font(dataclasses.replace(wb.ooxml.get_font(0), bold=True))
    style_xf = wb.ooxml.add_cell_style_xf(dataclasses.replace(plain, font_index=font_index))
    wb.set_cell_style(CellStyle(name='Emphasis', style_xf_index=style_xf))

    # A cell XF that inherits from the style, applied to A1.
    cell_xf = wb.ooxml.add_cell_xf(dataclasses.replace(plain, font_index=font_index, style_xf_index=style_xf))
    ws['A1'] = 'Total'
    ws.ooxml.set_cell_xf_index('A1', cell_xf)
    print(ws.get_cell_format('A1').font.bold)  # True

wb.getCellStyle(name) returns the record for a name, or null (Python None), and listCellStyles() lists every named style in file order. wb.ooxml.listCellStyleXfs() and getCellStyleXf(index) read the style XF table. setCellStyle with an existing name replaces that entry.

Python spells these get_cell_style, list_cell_styles, list_cell_style_xfs and get_cell_style_xf.

Automatic row height ​

ws.setRowAutoHeight(first, last, heightPt) (Python set_row_auto_height) stores heightPt, in points, as the cached automatic height of rows first to last. The rows keep following their content and font, unlike setRowHeight, which fixes a manual height. A span string such as '3:5' works in place of the two indices.

Workbook settings and protection ​

Calculation settings ​

<calcPr> settings have typed accessors on wb:

SettingAccessors
Full precision (false means "set precision as displayed")getFullPrecision() / setFullPrecision()
Calculate on savegetCalcOnSave() / setCalcOnSave()
Reference mode (RefMode.A1 or RefMode.R1C1)getRefMode() / setRefMode()

They record the workbook's state and do not change evaluation. The other <calcPr> attributes are kept across a resave.

Date system ​

getDate1904() / setDate1904() read and switch the date system. Switching does not convert stored serials, so every date shifts by 1462 days.

Python spells the settings above get_full_precision(), get_calc_on_save(), get_ref_mode(), and get_date1904(), with matching set_ methods.

Workbook location ​

getLocation() / setLocation({ directory, fileName }) (Python get_location() / set_location(WorkbookLocationInput(file_name=..., directory=...))) hold where the workbook is saved as a WorkbookLocation.

FieldHolds
fileNameThe file name with its extension
directoryThe folder, or null for a name without one

getLocation() is null until a location is set, and loading from bytes leaves it unset. The command-line tools set it from the input path made absolute, and recalc -o sets it to the output path before saving. The location is metadata only and never touches a file system.

The folder is absolute and stored in a canonical form: POSIX (/a/b), drive (C:\a\ reads back C:/a) or UNC (//server/share/a). A relative folder or a file name without a workbook extension throws StatusCode.InvalidArgument.

While a file name is set, a reference to the workbook's own defined name reads Book.xlsx!Name rather than [0]!Name, and [Book.xlsx]Sheet1!A1 entered in a formula means this workbook, with no external link.

The folder drives:

  • CELL("filename"), which reads "" until one is set
  • the folder path written into a saved file
  • the relative form of local hyperlink targets on save

Reference text ​

wb.formatReference(range, { sheetName, absolute }) (Python format_reference(range, *, sheet_name=None, absolute=False)) writes range, an A1 string, a CellRect or a ParsedReference, as A1 text. sheetName sets the qualifier (it overrides the sheet name of a ParsedReference), and absolute writes $ anchors.

Workbook protection ​

getWorkbookProtection() / setWorkbookProtection(protection) read and replace <workbookProtection>. The argument is a WorkbookProtectionInput whose every key is optional, and the WorkbookProtection a read returns passes back as is.

Omitted keyValue
A flagfalse
A spin count0
A string (omitted or null)Absent

The keys are lockStructure, lockWindows, lockRevision, the legacy password hashes, and the workbook* and revisions* algorithm, hash, salt, and spin-count fields.

Hashes are stored as the host computes them, the engine does not enforce the locks, and attributes the record does not model are kept. An all-empty record removes the element.

Python uses get_workbook_protection() / set_workbook_protection() with a WorkbookProtectionInput or a WorkbookProtection.

Protected ranges ​

A sheet's <protectedRange> entries are listed with ws.listProtectedRanges() and managed with ws.addProtectedRange(input), ws.updateProtectedRange(protectedRange, patch), and ws.removeProtectedRange(protectedRange), where protectedRange is the entry's index or its name.

Each entry has:

FieldHolds
nameNon-empty and unique on the sheet
rangesA list of one or more CellRect rectangles or A1 ranges (or one A1 string)
Password fieldsThe password hash, algorithm, salt and spin count
Security descriptorThe security descriptor

The ranges move with row and column edits.

An update changes only the keys the patch names. Leaving ranges out keeps the stored ranges, including any the engine could not parse. On add, name and ranges are required and every other key is absent when omitted (ProtectedRangeInput).

ConditionResult
An empty ranges on updateStatusCode.InvalidArgument
A name outside 1 to 255 UTF-16 unitsStatusCode.InvalidArgument
More than 8,191 rectanglesStatusCode.InvalidArgument

Those are the limits Excel keeps; a loaded range beyond them reads back as stored.

A ProtectedRange read back from listProtectedRanges() can be passed as the input or the patch, and null clears any of the five password fields, legacyPasswordHash included.

Security descriptors ​

<securityDescriptor> child elements of a protected range in an .xlsx are read as its security descriptor and written back as the attribute, as Excel does.

A security descriptor reads back in the spelling Excel saves, not the text passed in: SID aliases upper-cased, the owner, group and DACL sections in that order, and rights as tokens.

A descriptor Excel drops is not stored and reads back as null, with the range kept. Excel drops:

  • one naming a SID with no fixed value (a domain-relative alias such as DA)
  • one naming an unknown alias
  • text with no upper-case letter

Python uses list_protected_ranges(), add_protected_range(), update_protected_range() (keyword-only, defaulting to UNCHANGED), and remove_protected_range().

Attribute-only range styles ​

Reading the bases ​

ws.ooxml.getRangeXfBases(range) / get_range_xf_bases(range) lists, in ascending order, every cell XF that some cell of the selection resolves to: the XF of each cell that carries its own, and the row, column, or default (0) style of the rest. A selection wholly covered by styled cells does not list 0, and a column style shadowed everywhere by row styles is not listed.

ws.ooxml.getRangeXfBasesExcluding(range, excluded) (Python get_range_xf_bases_excluding()) gives the base list with the cells of excluded (each a CellAddress or an A1 cell) left out, for a host that resolves those cells itself.

Changing attributes ​

For an attribute-only change:

  1. Read the bases.
  2. Build the patched XFs with wb.ooxml.addFont() / wb.ooxml.addCellXf() (Python: add_font() / add_cell_xf()).
  3. Pass the pairs to ws.ooxml.remapRangeXfs(range, mapping), where mapping is a Map from the former XF to the new one (a plain object throws TypeError).

Python's remap_range_xfs(range, mapping) takes a {from_xf: to_xf} dict.

Take a snapshotRangeXfs() / snapshot_range_xfs() first when the operation needs an undo path, and pass its bytes to restoreRangeXfs() / restore_range_xfs() to restore the style state.

What the remap writes ​

The remap rewrites covered row and column styles and existing cell XFs while leaving values and formulas untouched.

  • In a plain finite range every blank cell gets its own format.
  • A row, column, or whole-sheet selection is written as row or column formats and gives a blank its own format only where row-over-column precedence would otherwise resolve differently.
  • A blank remapped to 0 keeps a record only where that overrides a row or column format.

Failures and limits ​

The operation fails without mutation in these cases:

ConditionResult
A target is past the cell-XF table (checked first)StatusCode.IndexOutOfRange
The range covers more than 134,217,728 cells and is not a whole row or column selectionStatusCode.SecurityResourceLimit

snapshotRangeXfs, restoreRangeXfs and listCellXfIndices have no cell ceiling; a result sized by the area of a large rectangle is read range by range.

snapshotRangeXfs writes version 2 of its capture, which records runs of formatted blanks, and restoreRangeXfs also accepts version 1. Bytes that are not a valid capture throw StatusCode.InvalidArgument.

Setting one index over a rectangle ​

ws.ooxml.setRangeXfIndex(range, xfIndex) (Python ws.ooxml.set_range_xf_index(range, xf_index)) applies a cell-style XF index across an inclusive rectangle in one call.

  • Blank cells take it as their own format, which is useful for ruling an empty report area. They are stored as runs of columns in each row, so a rectangle costs memory in proportion to its rows.
  • Whole rows or whole columns are written as row or column formats and add no cells, so getCellXfIndex reads null there while the effective style shows the format.
  • Setting 0 leaves a blank only where it overrides a row or column format.
ConditionResult
An index past the cell-XF table (checked first)StatusCode.IndexOutOfRange
A rectangle up to 134,217,728 cells in setRangeXfIndexAccepted
A larger rectangle that is not a whole row or column selectionStatusCode.SecurityResourceLimit (Python SecurityError), and nothing changes

Conditional formats ​

ws.addCfRule() / add_cf_rule() adds a rule, and ws.evaluateCfRange() / evaluate_cf_range() reports which cells match. Rule types, differential formats, data bars, color scales, icon sets, and the today option are covered in Conditional formats.