Skip to content

Render a sheet in your own UI ​

Use this page when you draw a grid yourself, in a canvas, a table or a terminal, and need the same text, styles and geometry Excel would show. Every call here reads the workbook and changes nothing. formulon-cell is a ready-made grid component built on these calls; Presentation, geometry, and pagination describes the model, and the calls are under Display text, Styles, Rows, columns and geometry, Merges and Sheet view in the WASM API.

Read the cells in view ​

getCellsInRange(range, { limit }) returns the populated cells of a range one page at a time, so a viewport costs as much as its non-empty cells, not its area. Pass cursor: nextCursor for the next page until nextCursor is null. getDisplayText(cell) gives the text Excel shows for a cell under its number format and the workbook's profile, and displayStatus (DisplayStatus) reports a value the format cannot show.

js
import createFormulon from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setValues('A1', [['Region', 'Q1', 'Q2'], ['East', 1200.5, -300], ['West', 980, 450]])
  ws.updateCellFormat('B2:C3', { numberFormat: '#,##0.00;[Red](#,##0.00)' })

  const texts = []
  let cursor
  do {
    const page = ws.getCellsInRange('A1:C3', { cursor, limit: 4 })
    for (const cell of page.cells) texts.push(ws.getDisplayText(cell.row, cell.col).text)
    cursor = page.nextCursor ?? undefined
  } while (cursor !== undefined)

  console.log(texts.join(' | ')) // Region | Q1 | Q2 | East | 1,200.50 | (300.00) | West | 980.00 | 450.00
} finally {
  wb.dispose()
}
python
from formulon import Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    ws.set_values("A1", [["Region", "Q1", "Q2"], ["East", 1200.5, -300], ["West", 980, 450]])
    ws.update_cell_format("B2:C3", number_format="#,##0.00;[Red](#,##0.00)")

    texts = []
    cursor = None
    while True:
        page = ws.get_cells_in_range("A1:C3", cursor=cursor, limit=4)
        texts += [ws.get_display_text(c.row, c.col).text for c in page.cells]
        cursor = page.next_cursor
        if cursor is None:
            break

    print(" | ".join(texts))  # Region | Q1 | Q2 | East | 1,200.50 | (300.00) | West | 980.00 | 450.00

The display text carries no colour: the [Red] of the format above changes nothing in the result, so a grid that colours negative numbers reads the colour from the number format itself. The text also does not depend on the column width; Excel's #### for a number too wide for its column is the renderer's to draw.

Resolve the effective style ​

A cell shows the format of its own XF, or else its row's, its column's or the sheet default. getCellFormat(cell) reads that effective format with its number format, font, fill, border, alignment and protection, and source (EffectiveStyleSource) says which layer it came from. ws.ooxml.getEffectiveStyle(cell) gives the same cell's colours already resolved to ARGB, theme and tint applied, which is what a painter needs.

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

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setValues('A1', [['Region', 'Q1'], ['East', 1200]])
  ws.updateCellFormat('A1:B1', { font: { bold: true, color: '#FFFFFF' }, fill: { foreground: '#2F6FED' } })
  ws.updateCellFormat('2:2', { fill: { foreground: '#FFF2CC' } })

  const header = ws.getCellFormat('A1')
  console.log(enumName(EffectiveStyleSource, header.source), header.font.bold) // Cell true
  console.log(enumName(EffectiveStyleSource, ws.getCellFormat('D2').source)) // Row

  const hex = (argb) => (argb & 0xffffff).toString(16).padStart(6, '0')
  const style = ws.ooxml.getEffectiveStyle('A1')
  console.log(hex(style.fontColor.argb), hex(style.fillForeground.argb)) // ffffff 2f6fed
  console.log(hex(ws.ooxml.getEffectiveStyle('D2').fillForeground.argb)) // fff2cc
} finally {
  wb.dispose()
}
python
from formulon import Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    ws.set_values("A1", [["Region", "Q1"], ["East", 1200]])
    ws.update_cell_format("A1:B1", font={"bold": True, "color": "#FFFFFF"}, fill={"foreground": "#2F6FED"})
    ws.update_cell_format("2:2", fill={"foreground": "#FFF2CC"})

    header = ws.get_cell_format("A1")
    print(header.source.name, header.font.bold)  # CELL True
    print(ws.get_cell_format("D2").source.name)  # ROW

    style = ws.ooxml.get_effective_style("A1")
    print(format(style.font_color.argb & 0xFFFFFF, "06x"), format(style.fill_foreground.argb & 0xFFFFFF, "06x"))  # ffffff 2f6fed
    print(format(ws.ooxml.get_effective_style("D2").fill_foreground.argb & 0xFFFFFF, "06x"))  # fff2cc

Conditional formatting is not part of the effective style. Evaluate it for the viewport with evaluateCfRange and lay each match over the cell, as Add conditional formatting shows.

Lay out columns and rows ​

getColumnWidthPt(col) and getRowHeightPt(row) return sizes in points, 0 for a hidden column or row. getCellRectPt(range) returns a cell's or a range's rectangle in points from the sheet's top-left corner, which places a cell without summing the sizes yourself. Widths follow Excel's column-width model for the workbook's default font and platform; GeometryMode.Print gives the width pagination uses instead of the screen width.

js
import createFormulon from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setColumnWidth('A', 14)
  ws.setRowHeight('1', 24)
  ws.setColumnHidden('C', true)

  console.log(ws.getColumnWidthPt('A'), ws.getColumnWidthPt('B'), ws.getColumnWidthPt('C')) // 73.5 48 0
  console.log(ws.getRowHeightPt('1'), ws.getRowHeightPt('2').toFixed(2)) // 24 14.57
  console.log(JSON.stringify(ws.getCellRectPt('B2'))) // {"x":73.5,"y":24,"widthPt":48,"heightPt":14.571428571428571}
} finally {
  wb.dispose()
}
python
from formulon import Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    ws.set_column_width("A", 14)
    ws.set_row_height("1", 24)
    ws.set_column_hidden("C", True)

    print(ws.get_column_width_pt("A"), ws.get_column_width_pt("B"), ws.get_column_width_pt("C"))  # 73.5 48.0 0.0
    print(ws.get_row_height_pt("1"), f"{ws.get_row_height_pt('2'):.2f}")  # 24.0 14.57
    print(ws.get_cell_rect_pt("B2"))  # RectPt(x=73.5, y=24.0, width_pt=48.0, height_pt=14.571428571428571)

listColumnOverrides() and listRowOverrides() list only the columns and rows that differ from the default, which suits a renderer that keeps its own size index.

Draw merged cells ​

A merge shows the value and format of its top-left cell across the whole range. getMergesInRange(range) returns the merges that touch the viewport, including one that starts outside it, and getCellRectPt(merge) gives the rectangle to draw it in.

js
import createFormulon from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setValue('A5', 'Total')
  ws.addMerge('A5:C5')

  const [merge] = ws.getMergesInRange('B1:D10')
  console.log(JSON.stringify(merge)) // {"firstRow":4,"firstCol":0,"lastRow":4,"lastCol":2}
  console.log(ws.getDisplayText(merge.firstRow, merge.firstCol).text) // Total
  console.log(ws.getCellRectPt(merge).widthPt) // 144
} finally {
  wb.dispose()
}
python
from formulon import Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    ws["A5"] = "Total"
    ws.add_merge("A5:C5")

    merge = ws.get_merges_in_range("B1:D10")[0]
    print(merge)  # CellRect(first_row=4, first_col=0, last_row=4, last_col=2)
    print(ws.get_display_text(merge.first_row, merge.first_col).text)  # Total
    print(ws.get_cell_rect_pt(merge).width_pt)  # 144.0

Freeze panes and other view settings ​

getView() returns the sheet's view: freezeRows and freezeCols are the frozen rows at the top and columns at the left, paneTopLeft is the first cell of the scrolling pane, and showGridLines, showRowColumnHeaders, showZeros, zoomPct and rightToLeft are the display switches a grid honours.

js
import createFormulon from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.updateView({ freezeRows: 1, freezeCols: 1, showGridLines: false })

  const view = ws.getView()
  console.log(view.freezeRows, view.freezeCols) // 1 1
  console.log(JSON.stringify(view.paneTopLeft)) // {"row":1,"col":1}
  console.log(view.showGridLines, view.zoomPct, view.rightToLeft) // false 100 false
} finally {
  wb.dispose()
}
python
from formulon import Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    ws.update_view(freeze_rows=1, freeze_cols=1, show_grid_lines=False)

    view = ws.get_view()
    print(view.freeze_rows, view.freeze_cols)  # 1 1
    print(view.pane_top_left)  # CellAddress(row=1, col=1)
    print(view.show_grid_lines, view.zoom_pct, view.right_to_left)  # False 100 False

Place pictures, charts and shapes ​

listDrawings() returns every drawing object on the sheet in stacking order, back first. Each object's getDrawingProperties().anchor places it by cell: a two-cell anchor runs from fromRow / fromCol to toRow / toCol, each with an offset in EMU (12,700 EMU per point). Convert it to points with getCellRectPt, so the object moves and stretches with the rows and columns it is anchored to.

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

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setValues('A1', [['Region', 'Q1'], ['East', 1200], ['West', 980]])
  ws.addChart({ type: ChartPlotType.Bar, range: 'A1:B3', anchor: { fromRow: 4, fromCol: 1, toRow: 14, toCol: 5 } })

  const EMU_PER_PT = 12700
  for (const drawing of ws.listDrawings()) {
    const a = drawing.getDrawingProperties().anchor
    if (a.kind !== AnchorKind.TwoCell) continue
    const from = ws.getCellRectPt({ firstRow: a.fromRow, firstCol: a.fromCol, lastRow: a.fromRow, lastCol: a.fromCol })
    const to = ws.getCellRectPt({ firstRow: a.toRow, firstCol: a.toCol, lastRow: a.toRow, lastCol: a.toCol })
    const left = from.x + a.fromColOffsetEmu / EMU_PER_PT
    const top = from.y + a.fromRowOffsetEmu / EMU_PER_PT
    const right = to.x + a.toColOffsetEmu / EMU_PER_PT
    const bottom = to.y + a.toRowOffsetEmu / EMU_PER_PT
    console.log(drawing.name, left, top.toFixed(1), right - left, (bottom - top).toFixed(1)) // Chart 1 48 58.3 192 145.7
  }
} finally {
  wb.dispose()
}
python
from formulon import AnchorKind, CellRect, ChartInput, ChartPlotType, DrawingAnchorInput, Workbook

EMU_PER_PT = 12700

with Workbook.create_default() as wb:
    ws = wb[0]
    ws.set_values("A1", [["Region", "Q1"], ["East", 1200], ["West", 980]])
    ws.add_chart(ChartInput(
        type=ChartPlotType.BAR, range="A1:B3",
        anchor=DrawingAnchorInput(from_row=4, from_col=1, to_row=14, to_col=5),
    ))

    drawing = ws.list_drawings()[0]
    a = drawing.get_drawing_properties().anchor
    assert a.kind == AnchorKind.TWO_CELL
    start = ws.get_cell_rect_pt(CellRect(a.from_row, a.from_col, a.from_row, a.from_col))
    end = ws.get_cell_rect_pt(CellRect(a.to_row, a.to_col, a.to_row, a.to_col))
    left = start.x + a.from_col_offset_emu / EMU_PER_PT
    top = start.y + a.from_row_offset_emu / EMU_PER_PT
    right = end.x + a.to_col_offset_emu / EMU_PER_PT
    bottom = end.y + a.to_row_offset_emu / EMU_PER_PT
    print(drawing.name, left, f"{top:.1f}", right - left, f"{bottom - top:.1f}")  # Chart 1 48.0 58.3 192.0 145.7

A one-cell anchor (AnchorKind.OneCell) has a from corner and a fixed widthEmu / heightEmu; an absolute anchor has a fixed position and size. A chart's content comes from chart.getData() (Create and edit a chart), and a picture's bytes from picture.getProperties().