Functions
builtinFormatCodefrom @apertura/formula
function builtinFormatCode(id: number): string | undefined
The format code of a built-in id, or `undefined` when the id is not reserved.
columnFromLabel
function columnFromLabel(letters: string): number
`A` becomes 0, `AA` becomes 26.
columnLabel
function columnLabel(index: number): string
0 becomes `A`, 26 becomes `AA`.
compileFormatfrom @apertura/formula
function compileFormat(code: string): CompiledFormat
Compiles a format code, or returns the cached compilation.
createEvaluationContext
function createEvaluationContext(document: XlsxDocument, options?: EvaluationOptions): Promise<WorkbookContext>
Builds an evaluation context over a workbook.
Every sheet is loaded, because a formula on one sheet may read any other and
the engine's questions are synchronous. That is the one place where
calculation is at odds with the viewer's laziness, and it is why calculation
is asked for rather than assumed.
createEvaluator
function createEvaluator(document: XlsxDocument, options?: EvaluationOptions): Promise<Evaluator>
A ready-made evaluator over a workbook, for callers that want one call.
createPredicateEvaluator
function createPredicateEvaluator(document: XlsxDocument, options?: EvaluationOptions): Promise<(formula: string, sheet: number, row: number, column: number) => CellValue>
A function that answers "is this predicate true here".
The shape the renderer wants: it has a formula and a cell, and needs a value.
Everything else — building the context, loading the sheets, turning a result
back into a cell value — happens once, here, rather than at the call site.
dateToSerialfrom @apertura/formula
function dateToSerial(date: Date, date1904?: boolean): number
The inverse: a `Date` as the serial number Excel would store for it.
emptyStylesheet
function emptyStylesheet(): Stylesheet
An empty stylesheet, for a workbook that has no `styles.xml` at all.
evaluateFormula
function evaluateFormula(evaluator: Evaluator, formula: string, position: CellPosition): CellValue
Computes the value of one formula.
The entry point for everything that has no cached answer: a conditional
formatting predicate, a data validation, a cell whose `<f>` came without a
`<v>`.
formatCellReference
function formatCellReference(address: CellAddress): string
`{ row: 0, column: 0 }` becomes `A1`.
formatGeneralfrom @apertura/formula
function formatGeneral(value: number): string
Excel's `General`.
Not "the number as JavaScript prints it": Excel keeps about eleven
significant digits and falls back to scientific notation outside a fixed
range, which is why `0.1 + 0.2` shows as `0.3` in a spreadsheet and as
something longer in a console.
formatRange
function formatRange(range: CellRange): string
formatValuefrom @apertura/formula
function formatValue(value: string | number | boolean | Date | null, code: string | undefined, options?: FormatOptions): FormattedValue
Formats a value the way Excel would with the given code.
`code` is the format string, not the id: resolving an id through the
workbook's `numFmts` and the built-in table happens in the style layer, which
is the only place that knows both.
indexedColorfrom @apertura/formula
function indexedColor(index: number, palette?: readonly string[]): string | undefined
Looks up an indexed colour, falling back to the default palette.
isDateFormatfrom @apertura/formula
function isDateFormat(code: string | undefined): boolean
Whether a format code shows a date or a time rather than a number.
isTextFormatfrom @apertura/formula
function isTextFormat(code: string | undefined): boolean
Whether the code contains a text section, which is what makes it apply to strings.
normalizeRange
function normalizeRange(range: CellRange): CellRange
Puts the corners in order, so a range written backwards still works.
openXlsx
function openXlsx(source: ByteSource, options?: OpenOptions): Promise<XlsxDocument>
Opens an Excel workbook.
packAddress
function packAddress(row: number, column: number): number
Packs a cell position into one number.
A `Map` keyed by `${row},${column}` allocates a string per lookup, and the
renderer does one per visible cell per frame. The column fits in fourteen
bits and the row in twenty, so both fit in a double with room to spare.
parseCellReference
function parseCellReference(reference: string): CellAddress | undefined
`A1` becomes `{ row: 0, column: 0 }`; anything else returns `undefined`.
parseDrawing
function parseDrawing(root: XmlElement, resolve: RelationshipResolver): DrawingObject[]
parseRange
function parseRange(reference: string): CellRange | undefined
Parses `A1:C5`, `A1` or a whole-column/row range such as `A:C` or `2:4`.
Whole-column ranges are what an autofilter and most conditional formatting
rules are written as, so refusing them would lose the feature rather than one
odd file. They come back bounded by the sheet limits.
parseRangeList
function parseRangeList(reference: string): CellRange[]
Parses a space-separated list of ranges, as `sqref` attributes hold.
parseSharedStrings
function parseSharedStrings(parser: XmlPullParser): SharedString[]
Streams the shared string table.
parseSheet
function parseSheet(parser: XmlPullParser, context: SheetContext): ParsedSheet
parseStyles
function parseStyles(root: XmlElement | undefined, theme: ThemeColors | undefined): Stylesheet
parseTable
function parseTable(root: XmlElement): SheetTable | undefined
`xl/tables/tableN.xml`.
A table is a named, styled range with a header row, an optional totals row
and filter buttons. It matters to a viewer because the banded style comes
from the table rather than from the cells: strip the table and the rows lose
their alternating fill.
parseTheme
function parseTheme(root: XmlElement): ThemeColors
parseWorkbook
function parseWorkbook(root: XmlElement): WorkbookProperties
rangeContains
function rangeContains(range: CellRange, row: number, column: number): boolean
rangesIntersect
function rangesIntersect(a: CellRange, b: CellRange): boolean
readRichText
function readRichText(parser: XmlPullParser): SharedString
Reads one `<si>` or `<is>` subtree.
Must be called while positioned on the container's start element; it
consumes through the matching end element.
Phonetic guides (`<rPh>`) are skipped. They hold the reading of a Japanese
word and are shown above the text, not in it — concatenating them produces a
cell that reads the same thing twice.
serialToDatefrom @apertura/formula
function serialToDate(serial: number, date1904?: boolean): Date | undefined
Converts a serial number to a JavaScript `Date` in UTC.
serialToDatePartsfrom @apertura/formula
function serialToDateParts(serial: number, date1904?: boolean): DateParts | undefined
Converts a serial number to calendar parts.
Returns `undefined` for values Excel itself refuses to show as a date:
negative serials in the 1900 system produce `#####`, not a date before the
epoch.
translateFormula
function translateFormula(formula: string, rowDelta: number, columnDelta: number): string
Rewrites a formula as if it had been filled from one cell to another.
Relative references move with the cell and absolute ones (`$A$1`) do not,
which is the whole distinction the dollar signs exist for. A reference that
would move off the sheet becomes `#REF!`, as it does in Excel.
unpackAddress
function unpackAddress(packed: number): CellAddress
Interfaces
Alignment
interface Alignment
textRotation
number
Rotation in degrees, 0..90 anticlockwise and 91..180 for clockwise 1..90.
The value 255 is Excel's flag for stacked (vertical) text.
indent
number
Indent steps; each is three characters wide.
readingOrder
number
0 context, 1 left-to-right, 2 right-to-left.
AutoFilter
interface AutoFilter
filteredColumns
readonly number[]
Columns that currently filter, by offset within the range.
BorderEdge
interface BorderEdge
Cell
interface Cell
A cell.
Row and column are stored flat rather than in a nested address object: a
large sheet has millions of these, and the object that would hold two
numbers costs more than the numbers.
styleIndex
number
Index into the workbook's `cellXfs`.
formula
string | undefined
The formula without its leading equals sign, when the cell is computed.
formulaKind
"normal" | "array" | "shared" | "dataTable" | undefined
How the formula applies: a plain one, an array formula, a shared master.
formulaRange
CellRange | undefined
The range an array formula spills into.
richText
readonly RichTextRun[] | undefined
Formatting runs, for a shared string that has more than one.
CellAddress
interface CellAddress
Zero-based cell position.
CellFormat
interface CellFormat
A fully resolved format: what a cell actually looks like.
CellRange
interface CellRange
A rectangular range, inclusive on both ends and zero-based.
CellStyleRecord
interface CellStyleRecord
One `xf` as written, before its parent style is folded in.
xfId
number | undefined
Index into `cellStyleXfs`: the named style this format is based on.
alignment
Partial<Alignment> | undefined
quotePrefix
boolean
Text stored with a leading apostrophe: a number the author wanted as text.
Color
interface Color
A colour as a workbook writes it.
Four ways of saying the same thing, and a file will use all four. `rgb` is
literal; `theme` points into the theme's colour scheme and is what a modern
file uses so that changing the theme restyles the workbook; `indexed` is the
pre-2007 palette; `auto` means "whatever the window text colour is". `tint`
lightens or darkens whichever of them was given.
rgb?
string | undefined
`AARRGGBB` as stored, alpha first.
tint?
number | undefined
-1..1: negative darkens, positive lightens.
ColorScale
interface ColorScale
values
readonly ConditionalValue[]
Column
interface Column
A `<col>` element: formatting for a span of columns.
width
number | undefined
Width in Excel "characters"; `undefined` means the sheet default.
ConditionalFormatting
interface ConditionalFormatting
rules
readonly ConditionalRule[]
ConditionalRule
interface ConditionalRule
dxfId
number | undefined
Index into `dxfs`: the formatting to apply when the rule matches.
format
DifferentialFormat | undefined
extensionId
string | undefined
`x14:id`: the name of the rule's other half, in the extension block.
ConditionalValue
interface ConditionalValue
A conditional formatting threshold (`cfvo`).
type
"percent" | "num" | "max" | "min" | "formula" | "percentile" | "autoMin" | "autoMax"
greaterOrEqual
boolean
Whether the icon-set band includes its lower bound.
DataBar
interface DataBar
gradient
boolean
Excel 2010 extensions: a solid bar, a border, a different colour for negatives.
direction
"context" | "leftToRight" | "rightToLeft"
axisPosition
"none" | "automatic" | "midpoint"
Where zero sits: `automatic` puts it where the values put it.
DataValidation
interface DataValidation
DatePartsfrom @apertura/formula
interface DateParts
Whole and fractional parts of a serial number, in calendar terms.
DefinedName
interface DefinedName
A defined name: a range or a formula the workbook gave a name to.
localSheetIndex
number | undefined
Sheet index when the name is local to one sheet.
DifferentialFormat
interface DifferentialFormat
A differential format: the parts a conditional rule or a table style changes.
Everything is optional by construction — a rule that paints the background
red must leave the font alone, and the only way to say that is to say nothing.
font
Partial<Font> | undefined
border
Partial<Border> | undefined
alignment
Partial<Alignment> | undefined
DrawingAnchorPoint
interface DrawingAnchorPoint
An image, chart or shape anchored to the grid.
DrawingObject
interface DrawingObject
kind
"image" | "chart" | "shape" | "diagram"
anchor
"twoCell" | "oneCell" | "absolute"
How the object behaves when rows and columns are resized.
to
DrawingAnchorPoint | undefined
widthEmu
number | undefined
Size in EMU, for one-cell and absolute anchors.
xEmu
number | undefined
Absolute position in EMU, for absolute anchors.
mediaPartName
string | undefined
The package part holding the image, for an image.
text
string | undefined
Text drawn inside a shape.
shape
ShapeAppearance | undefined
How a shape is painted, when the object is one.
chart
ChartDefinition | undefined
The chart, when the object is one.
Parsed rather than referenced: `c:chartSpace` is the same part in a
workbook as in a document, and the renderer that draws it is shared.
EvaluationOptions
interface EvaluationOptions
now?
(() => Date) | undefined
The clock `TODAY` and `NOW` read. Fixed in tests, the real one otherwise.
Fill
interface Fill
foreground
Color | undefined
The pattern's ink. For a solid fill this is the whole story — and note that
it is `fgColor` that carries it, not `bgColor`, which is the trap in this
part of the format.
Font
interface Font
size
number | undefined
Size in points.
vertAlign
"baseline" | "superscript" | "subscript"
scheme
string | undefined
`major` or `minor`: which theme font this one follows.
FormatOptionsfrom @apertura/formula
interface FormatOptions
date1904?
boolean | undefined
The workbook's 1904 date system flag.
locale?
string | undefined
BCP 47 locale for month and weekday names; overridden by `[$-…]` in the code.
palette?
readonly string[] | undefined
The workbook's own indexed palette, when it overrides the default.
FormattedValuefrom @apertura/formula
interface FormattedValue
The result of formatting a value with a format code.
text
string
The text as Excel would display it.
color
string | undefined
Colour requested by the format code (`[Red]`), as CSS.
fill
string | undefined
The character of a `*` fill token, when the code has one.
Excel repeats it until the cell is full — the usual use is `_(* #,##0_)`,
the accounting format, where it pushes the number to the right edge.
kind
"number" | "boolean" | "error" | "date" | "text" | "empty"
What the value turned out to be; the renderer aligns on it.
GradientFill
interface GradientFill
GradientStop
interface GradientStop
Hyperlink
interface Hyperlink
target
string | undefined
Resolved target for an external link.
location
string | undefined
In-workbook destination, as `Sheet2!A1` or a defined name.
IconSet
interface IconSet
values
readonly ConditionalValue[]
NamedCellStyle
interface NamedCellStyle
A named style, as the style gallery lists it.
PageSetup
interface PageSetup
orientation
"default" | "portrait" | "landscape"
marginsInches
{ left: number; right: number; top: number; bottom: number; header: number; footer: number; } | undefined
printTitleRows
string | undefined
Rows and columns repeated on every printed page.
Pane
interface Pane
A frozen or split pane.
frozenColumns
number
Columns frozen at the left.
frozenRows
number
Rows frozen at the top.
splitX
number
Split position in twentieths of a point, for a split rather than a freeze.
ParsedSheet
interface ParsedSheet
What the sheet part yields, before the parts it points at are resolved.
hyperlinks
(Hyperlink & { relationshipId: string | undefined; })[]
dimensions
{ rowCount: number; columnCount: number; }
drawingId
string | undefined
Relationship ids of the parts that have to be read separately.
Protection
interface Protection
RichTextRun
interface RichTextRun
One formatting run of a rich string.
The font is inline rather than an index: a shared string writes its
formatting into itself (`<rPr>`) instead of pointing at the font table, so a
cell whose text is half bold carries two runs with two fonts of their own.
font
Partial<Font> | undefined
Row
interface Row
cells
readonly Cell[]
Cells in column order; absent columns are simply not there.
heightPoints
number | undefined
Height in points, when the row carries one.
customHeight
boolean
Set when the height was chosen by the author rather than by the content.
styleIndex
number | undefined
Style applied to the whole row; only meaningful with `customFormat`.
outlineLevel
number
Grouping depth, 0..7.
ShapeAppearance
interface ShapeAppearance
What a shape looks like.
A shape says its appearance in two places and they compose: `xdr:spPr` is
what the shape itself states and has the last word, and `xdr:style` is what
it takes from the theme — as *references* (`a:fillRef`, `a:lnRef`,
`a:fontRef`) that carry a colour of their own. That colour is what the
reference is for: the first fill styles of every theme are a plain solid fill
of the placeholder colour, so the colour in the reference is the fill in the
overwhelming majority of files.
geometry
DiagramGeometry | undefined
`a:prstGeom/@prst`: `rect`, `roundRect`, `ellipse`, an arrow, a callout.
filled
boolean
`a:noFill`: the author turned the fill off, which is not the same as none stated.
outline
DiagramOutline | undefined
textColor
DiagramColor | undefined
Colour of the text inside, from `a:fontRef` or the first run's own colour.
fontSize
number | undefined
Point size of the first run, `a:rPr/@sz` in hundredths.
textBox
boolean
`xdr:cNvSpPr/@txBox`: the object is a text box rather than an autoshape.
It decides what the text does when the file says nothing: a text box sets
its text at the top left, an autoshape centres it both ways.
verticalAlignment
"center" | "top" | "bottom" | undefined
`a:bodyPr/@anchor`: where the text sits in a box taller than it needs.
insets
{ left: number; top: number; right: number; bottom: number; }
Text insets in EMU, `a:bodyPr/@lIns` and friends.
Every shape has them whether or not it says so: DrawingML's defaults are a
tenth of an inch left and right and half that above and below, and text set
hard against the edge of its box is how a reader sees their absence.
wrap
boolean
`a:bodyPr/@wrap`: `none` keeps the text on one line.
horizontalAlignment
"left" | "center" | "right" | "justify" | undefined
`a:pPr/@algn` of the first paragraph.
SharedString
interface SharedString
A shared string: its plain text, and its runs when it has more than one.
runs
readonly RichTextRun[] | undefined
Sheet
interface Sheet
A workbook sheet. Contents are loaded on demand.
id
number
Sheet identifier within the workbook, `sheetId`.
state
"visible" | "hidden" | "veryHidden"
partName
string
Name of the package part holding the sheet contents.
data
SheetData | undefined
The parsed sheet, once it has been loaded.
load
() => Promise<SheetData>
Parses the sheet. The result is cached.
SheetContext
interface SheetContext
Everything the sheet parser needs from the workbook around it.
SheetData
interface SheetData
Parsed sheet contents.
rows
readonly Row[]
Rows in index order; empty rows are absent.
conditionalFormats
readonly ConditionalFormatting[]
dataValidations
readonly DataValidation[]
sparklines
readonly SparklineGroup[]
rowBreaks
readonly number[]
Manual page breaks, by row and column index.
dimensions
{ rowCount: number; columnCount: number; }
Bounds of the used range.
SheetFormat
interface SheetFormat
defaultRowHeight
number
Default row height in points.
defaultColWidth
number | undefined
Default column width in characters, when the sheet overrides the standard.
customHeight
boolean
Set when every row carries an explicit height.
summaryBelow
boolean
`sheetPr/outlinePr/@summaryBelow`: which side of a group its total is on.
True by default, and it decides where the fold button goes — the button
belongs to the summary, not to the group.
SheetTable
interface SheetTable
autoFilter
CellRange | undefined
Present when the table has filter buttons in its header row.
SheetView
interface SheetView
view
"normal" | "pageBreakPreview" | "pageLayout"
activeCell
string | undefined
The cell the cursor was on when the file was saved.
Sparkline
interface Sparkline
One sparkline: the range it draws, and the cell it draws in.
SparklineGroup
interface SparklineGroup
A chart the size of a cell, drawn inside it.
The group holds the look and the list holds the cells: every sparkline of a
group is drawn the same way, from a range of its own.
type
"line" | "stacked" | "column"
displayEmptyCellsAs
string
`gap`, `zero` or `span`: what a missing value does to the line.
colors
Readonly<Record<string, Color | undefined>>
`series`, `negative`, `axis`, `markers`, `first`, `last`, `high`, `low`.
StylesheetParts
interface StylesheetParts
numberFormats
ReadonlyMap<number, string>
cellXfs
readonly CellStyleRecord[]
cellStyleXfs
readonly CellStyleRecord[]
differentialFormats
readonly DifferentialFormat[]
namedStyles
readonly NamedCellStyle[]
indexedColors
readonly string[]
The workbook's own indexed palette, when it replaces the default one.
TableColumn
interface TableColumn
ThemeColors
interface ThemeColors
The colour scheme of `theme1.xml`, in the order the theme writes it.
majorFont
string | undefined
Major and minor typefaces, which fonts with `scheme="minor"` follow.
XlsxDocument
interface XlsxDocument extends AperturaDocument
fileName?
string | undefined
What the file is called, when the source knew.
`CELL("filename")` is the only thing that asks, and a surprising number of
workbooks use it: it is the one way a formula can learn the name of its own
sheet, and `INDIRECT` over that name is how a template addresses "the sheet
before this one".
date1904
boolean
The 1904 date system, chosen per workbook and changing every date in it.
activeSheetIndex
number
The sheet that was active when the file was saved.
pageCount
number
Sheet count: the cheap, meaningful equivalent of a page count.
sheet
(nameOrIndex: string | number) => Sheet | undefined
media
(partName: string) => Promise<Uint8Array | undefined>
Resolves an image part to bytes, for the renderer.
mediaUrl
(partName: string) => Promise<string | undefined>
A URL a browser can show an embedded picture from, metafiles translated.