Birch UI v0.1
Pricing

Excel filesSpreadsheet

Import and export xlsx files with formulas, styles, conditional formatting, validation, notes and threaded comments, filters, tables, pivot tables, slicers, charts, shapes, pictures and page setup, follow the progress of an import or cancel it, check a file before you ship it, and see exactly what round-trips through LibreOffice and openpyxl.

Open .md

Workbooks open from and save to native .xlsx files, using the Excel Engine underneath. Formulas stay formulas, styles and layout come along, and the conversion runs entirely in the browser or in Node, with no server or third-party service.

In the component#

TypeScript
const input = document.querySelector<HTMLInputElement>('#open-file')!;

input.addEventListener('change', async () => {
  const file = input.files?.[0];
  if (file) await sheet.importXlsx(file);
});

document.querySelector('#download')!.addEventListener('click', () => sheet.downloadXlsx('loan-schedule.xlsx'));

const bytes = await sheet.exportXlsx();
Method Purpose
importXlsx(data, options?) Replaces the workbook with the contents of an xlsx file, given as a Blob, File, ArrayBuffer or Uint8Array. Clears the undo history and emits sheetChange and importReport. The options are password for an encrypted file, and onProgress and signal to follow or cancel the import.
exportXlsx(options?) Resolves to the xlsx file as a Uint8Array. Pass { compress: false } for a faster, larger uncompressed file, { password } to encrypt it, and { checkboxes: 'excel' } to write checkbox cells in Excel's own form instead of plain values.
downloadXlsx(fileName) Exports and starts a browser download. .xlsx is added to the name if missing.
getImportReport() The import report of the last importXlsx().

CSV, TSV and OpenDocument files have their own methods; see CSV and OpenDocument files. importXlsx() also opens legacy .xls files of Excel 97-2003, with a smaller set of features; nothing is written in that format.

If a file cannot be read or written, the promise rejects and the spreadsheet emits an error event with the code import or export, which you can show to the user:

TypeScript
sheet.on('error', ({ code, message }) => {
  if (code === 'import') toast.error(message);
});

Without the component#

xlsxToJSON() and jsonToXlsx() convert between xlsx files and the workbook JSON. They need no DOM, so they work in Node and in workers, and combine with the headless engine:

scripts/convert-budget.ts
import { readFile, writeFile } from 'node:fs/promises';
import { createFormulaEngine, jsonToXlsx, xlsxToJSON } from '@birchui/spreadsheet';

const licenseKey = process.env.BIRCHUI_LICENSE_KEY;

const workbook = await xlsxToJSON(await readFile('incoming/q3-budget.xlsx'), { licenseKey });

const engine = createFormulaEngine();
engine.fromJSON(workbook);
engine.setCell('Assumptions', 'B4', 0.035);

await writeFile('reports/q3-budget-revised.xlsx', await jsonToXlsx(engine.toJSON(), { licenseKey }));
Function Returns
xlsxToJSON(data, { licenseKey?, password?, onProgress?, signal? }) A promise of the WorkbookJSON for the file.
jsonToXlsx(json, { compress?, licenseKey?, rasterizeImage?, password?, encryptionSpinCount?, now? }) A promise of the xlsx file as a Uint8Array. now is the day that pivot date filters by period, such as thisMonth, are worked out for; the default is the current date.
xlsxToJSONWithReport(data, options?) A promise of { workbook, report }: the same WorkbookJSON plus an import report. Takes the options of xlsxToJSON().
inspectXlsx(data, options?) A promise of the import report alone.
validateXlsxPackage(bytes) A promise of the problems found in an xlsx file; see Checking a file.
isEncryptedPackage(bytes), describeEncryption(bytes) from @birchui/spreadsheet/encryption Whether a file needs a password, and how it is encrypted. See Password-protected workbooks.

Progress and cancelling#

An import reports where it is through onProgress and stops when the signal of an AbortController is aborted. Both options work the same in sheet.importXlsx(), xlsxToJSON() and xlsxToJSONWithReport().

TypeScript
const controller = new AbortController();
cancelButton.addEventListener('click', () => controller.abort());

try {
  await sheet.importXlsx(file, {
    signal: controller.signal,
    onProgress: ({ phase, fraction, sheet: name, sheetIndex, sheetCount }) => {
      progressBar.value = fraction;
      status.textContent =
        phase === 'sheets' ? `Reading ${name} (${sheetIndex! + 1} of ${sheetCount})` : `Opening the file (${phase})`;
    },
  });
} catch (error) {
  if ((error as Error).name !== 'AbortError') throw error;
}
Field Value
phase 'unzip', 'styles', 'sheets', 'features' and 'done', in that order.
fraction From 0 to 1, never decreasing. It is 0 at the first event and 1 at 'done'.
sheet, sheetIndex, sheetCount In the 'sheets' phase: the name of the sheet being read, its 0-based position and the number of sheets. There is one event per sheet.

Aborting rejects the promise with an error named AbortError, or with the error you passed to abort(reason). In the component the workbook that was open stays as it was, and an error event with the code import is emitted, as for any failed import. The importer looks at the signal between phases and between sheets, not inside one sheet, so a file with one very large sheet stops only when that sheet is done.

After each progress event the importer gives the event loop a turn, so a page that imports on the main thread can repaint its progress bar. That does not make a large import smooth; for that, run it in a worker.

Large files in a Web Worker#

Parsing a large workbook takes time, and in the page it blocks typing and scrolling. xlsxToJSON() never touches the DOM, so you can run it in a worker you create and post the JSON back. Everything stays on the device; nothing is uploaded.

src/xlsx-worker.ts
import { xlsxToJSON } from '@birchui/spreadsheet';

self.onmessage = async (event: MessageEvent<{ file: File; licenseKey?: string }>) => {
  try {
    const workbook = await xlsxToJSON(event.data.file, {
      licenseKey: event.data.licenseKey,
      onProgress: (progress) => self.postMessage({ progress }),
    });
    self.postMessage({ ok: true, workbook });
  } catch (error) {
    self.postMessage({ ok: false, message: error instanceof Error ? error.message : String(error) });
  }
};
src/open-workbook.ts
const worker = new Worker(new URL('./xlsx-worker.ts', import.meta.url), { type: 'module' });

export function openInBackground(file: File): Promise<void> {
  return new Promise((resolve, reject) => {
    worker.onmessage = ({ data }) => {
      if (data.progress) {
        progressBar.value = data.progress.fraction;
        return;
      }
      if (!data.ok) return reject(new Error(data.message));
      sheet.fromJSON(data.workbook);
      resolve();
    };
    worker.postMessage({ file, licenseKey: 'LQ1.…' });
  });
}

To keep calculating in the worker as well, load the file straight into a worker engine with loadXlsx().

An AbortSignal cannot be posted to a worker. To cancel, call worker.terminate() and create a new worker for the next file. Measured times for this setup are on the performance page.

A File is posted to the worker without copying its bytes. jsonToXlsx() works the same way for exports: post the result of sheet.toJSON() to a worker and transfer the returned Uint8Array back.

The license key is passed to the Excel Engine; a Spreadsheet key covers it. In the component, the spreadsheet's own licenseKey is used.

What round-trips#

A file takes one of three routes through the importer, and the table says which for each feature:

  • Modelled: read into the workbook JSON, editable through the API, and written again from the JSON. Import and Export say Yes.
  • Kept as is: the original bytes are carried in the preserved field of the workbook JSON and written back unchanged. You cannot edit them, and they survive toJSON() and fromJSON(). See Parts kept as they are. Pivot tables, slicers and shapes take this route only when they use something the model cannot express; the report says which and why.
  • Dropped: left out of the exported file. The import report names each one for the file at hand.

Modelled rows are checked three ways: the workbook JSON comes back identical after jsonToXlsx() and xlsxToJSON(); LibreOffice 26.8 opens the exported file, saves it again as xlsx, and the rewritten file still imports with the feature intact; and openpyxl 3.1.5 loads the exported file and finds the feature where it expects it. The notes say where one of those programs loses something. Microsoft Excel itself is not part of the automated checks; see How this is verified.

Cells and formulas#

Feature Import Export Kept as is only Notes
Numbers, text, booleans Yes Yes LibreOffice rewrites booleans as =TRUE() and =FALSE().
Error values, typed or returned by a formula Yes Yes, as error cells
Dates, including the 1904 date system Yes, as serials with their number format Yes, in the 1900 system
Formulas with cached results Yes Yes openpyxl drops cached results when it saves.
Shared formulas Yes, expanded for every cell with the relative references shifted Written as one formula per cell Checked against the expansion openpyxl and LibreOffice make of the same file.
Dynamic array formulas Yes, with the spill range in spill Yes, as a dynamic array with Excel's cell metadata See Dynamic arrays in files. openpyxl keeps the formula and range and drops the metadata.
Legacy array formulas (Ctrl+Shift+Enter) Yes, as a formula that spills Written as a dynamic array The curly-brace form is not kept.
Newer functions such as XLOOKUP, LET and LAMBDA Yes Yes, with the prefixes the file format expects
Structured references, Sales[Amount], [@Amount] Yes Yes
Rich text in a cell: bold, italic, underline, strikethrough, colour, size, font, superscript and subscript per run Yes, in richText Yes Phonetic guides are dropped. LibreOffice also sets the cell font from the first run.
Pictures placed in cells Yes, in cellImages Yes, as rich values with their value metadata See Pictures in cells. LibreOffice and openpyxl show the #VALUE! fallback.
In-cell checkboxes Yes, as the checkbox cell control As TRUE/FALSE values by default; as Excel checkboxes with { checkboxes: 'excel' } The 'excel' mode is not verified in Excel. See Cell controls.
Linked data types The fallback value No Reported as dropped, together with any pictures in cells of the same workbook.
Defined names, workbook-wide and sheet-scoped Yes Yes LibreOffice returns them in alphabetical order.
External workbook links Yes The link parts are kept; formulas that use them do not calculate here.

Formatting#

Feature Import Export Kept as is only Notes
Fonts: bold, italic, underline (single, double, accounting), strikethrough, colour, size, family, superscript, subscript Yes Yes
Solid fills Yes Yes
Gradient fills, linear and path, with every stop Yes, in fillGradient Yes LibreOffice replaces a gradient with one blended colour.
Pattern fills, all 17 patterns with both colours Yes, in fillPattern Yes LibreOffice replaces a pattern with a solid colour.
Borders: all 13 line styles on four sides, colours Yes Yes LibreOffice returns black border colours as automatic.
Diagonal borders, rising, falling or both Yes Yes
Alignment, wrap, indent, shrink to fit, reading order Yes Yes
Justify, distributed, fill and centre across selection Yes, in horizontal and vertical Yes LibreOffice drops centre across selection.
Text rotation from -90 to 90 degrees, and stacked text Yes, in rotation Yes
Number formats Yes Yes Escapes other programs add, such as yyyy\-mm\-dd, are removed on import.
Theme colours with tint, on fonts, fills, borders and rich text Yes: the resolved colour plus the theme index and tint Yes, as theme references while the colour is unchanged The theme part of the file is kept as is and written back.
Named cell styles such as Good or Heading 1 Yes, in cellStyles and styleName Yes LibreOffice renames built-in styles and adds its own; the names are read back.
Default font of the workbook Yes, in defaultFont Yes
Custom table styles, the colour palette, style extensions Yes
Conditional formatting: value, formula and text rules, blanks and errors, dates in a period, top/bottom, above/below average, duplicates and unique values, colour scales, with "stop if true" and ranges of several areas Yes, in priority order Yes See Conditional formatting in files. LibreOffice drops "stop if true" and returns rules for blank and non-blank cells as formula rules.
Data bars: colour, limits by number, percent, percentile, formula, lowest or highest value, gradient or solid fill, border, negative fill and border, axis position and colour, direction, bar only Yes Yes, as the Excel 2007 rule with its Excel 2010 extension rule LibreOffice drops the border colours and the direction. openpyxl drops the extension, which leaves colour, limits and bar only.
Icon sets: all twenty sets, thresholds by number, percent, percentile or formula, "at or above" or "above", reverse order, icon only, custom icons Yes Yes 3Stars, 3Triangles, 5Boxes and rules with custom icons are stored in the Excel 2010 extension only, as Excel does. openpyxl drops those rules; LibreOffice keeps them and drops "above" on their thresholds.
Other conditional formatting stored only in the Excel 2010 extension, such as a rule whose formula refers to another sheet Yes Kept in the same extension as the rules written from the model.
Merged cells, column widths, row heights, hidden rows and columns Yes Yes

Sheets and the workbook#

Feature Import Export Kept as is only Notes
Sheet order, names, the active sheet, tab colours Yes Yes
Hidden and very hidden sheets Yes, hidden and veryHidden Yes LibreOffice turns very hidden into hidden.
Frozen panes Yes Yes
Split panes Yes, in view.split Yes LibreOffice moves the split by a few units.
Zoom, gridlines, headings, zeros, formulas view, right-to-left, page break preview Yes, in view Yes LibreOffice drops the headings and zeros options.
Active cell and selection Yes Yes LibreOffice keeps the active cell only.
Workbook window: first tab, tab bar width, scroll bars Yes, in the workbook's view Yes LibreOffice drops the scroll bar options.
Calculation: iterative limits, manual mode, precision as displayed Yes Yes A workbook with formulas always asks for a full calculation on load.
Document properties: title, subject, author, keywords, description, category, status, last modified by, created, modified, company, manager Yes, in properties Yes openpyxl rewrites company and manager. LibreOffice rewrites the keyword separators.
Custom document properties: text, numbers, yes/no Yes Yes Dates come in as text.
Sheet protection, allowed actions and password hash; locked and hidden cells Yes Yes
Workbook structure protection Yes Yes LibreOffice drops it.
Row and column outline groups, collapsed groups, summary position Yes Yes LibreOffice drops the summary position.
Page setup: orientation, paper size, scale, fit to page, margins, header and footer, gridlines, headings, centring, page breaks, print area, print titles Yes Yes
Printer settings, header and footer pictures, sheet background Yes
Protected ranges, scenarios, custom views, ignored error markers, watch cells, phonetic settings Yes References inside them are not adjusted when rows or columns are inserted.
Chart sheets, dialog sheets, macro sheets Yes Written after the worksheets.

Data tools and objects#

Feature Import Export Kept as is only Notes
Autofilter range, value lists, custom conditions, top/bottom Yes Yes
Dynamic filters such as above average or this month, with their limits Yes Yes LibreOffice drops them on tables.
Colour filters, by fill or font colour Yes, in special Yes
Icon filters Yes, in special Yes
Date group filters, by year down to second Yes, in special Yes LibreOffice rewrites a month as the days it finds.
Sort state: several levels, descending, custom lists, sort by fill colour, font colour or icon, case, left to right Yes, in sortState on sheets and tables Yes LibreOffice keeps one level and drops table sort state.
Data validation: lists, whole numbers, decimals, dates, times, text length, custom formulas, messages Yes Yes
Tables: range, header and totals rows, totals functions, style and banding, filter state, calculated columns Yes Yes LibreOffice drops the calculated column definition.
Query tables behind a table No No Reported as dropped.
Data tables (what-if analysis), one and two variables Yes Yes openpyxl keeps them. LibreOffice turns them into TABLE() formulas, which are read back as data tables.
Notes with author, size and "always show" Yes Yes LibreOffice shifts sizes by a few pixels; openpyxl ignores size and visibility.
Threaded comments with replies, authors, dates and the resolved state Yes Yes openpyxl keeps the placeholder note only.
Hyperlinks to web addresses, email addresses and places in the workbook Yes Yes LibreOffice drops tooltips.
Pictures: PNG, JPEG, GIF, BMP, TIFF, WebP, SVG, EMF and WMF with alt text, rotation, flips, crop and their one-cell, two-cell or absolute anchor Yes Yes, with the original bytes Yes, the original XML while the picture is unedited See SVG and WebP pictures and Formats. LibreOffice reads all nine and turns WebP into PNG when it saves; openpyxl drops EMF and WMF.
Linked pictures, pictures in notes, pictures on form controls Yes
Charts: column, bar, line, area, pie, doughnut, scatter, bubble, radar and combo Yes Yes LibreOffice returns automatic series colours as explicit ones.
Chart options: trendlines, error bars, data label position, content and number format, axis limits, major unit, logarithmic scale, reversed order, number format, tick label position, hidden axes, major and minor gridlines, legend position Yes Yes See Charts read from a file for what each program keeps.
Chart title and axis title fonts (family, size, bold, italic, colour), chart and plot area fill, marker shape and size Yes Yes Edited in the Format chart pane.
Chart formatting beyond the model: gradients, line styles, effects, tick-label and legend fonts, layout Yes, while the chart is unedited or the edit can be merged Ranges, titles, title fonts, series colour, marker, area fills and legend position are merged into the original chart part, whatever namespace prefix the program that wrote it used. Any other edit writes the chart from the model. See Charts read from a file.
Stock charts (high-low-close and open-high-low-close) Yes Read and written as a classic stockChart; the original part is written back while the chart is not edited.
Excel 2016 charts: waterfall (with subtotals), histogram (with bin width or count), treemap, sunburst, funnel, box and whisker Not read by LibreOffice Yes, while unedited Read from and written to extended chart parts (chartEx). An unedited chart keeps its part, its style and colour parts and its anchor byte for byte; a moved chart keeps its part; an edited chart is rewritten from the model. Not yet opened in Excel: see limitations.
Other chart kinds: surface, pie-of-pie and map charts Yes, byte for byte Kept with the drawing, with their style and colour parts, and listed in the import report as Charts of other kinds.
Sparklines: line, column and win/loss, colours, markers, axis limits Yes Yes openpyxl removes sparklines.
Shapes: rectangles, rounded rectangles, ellipses, text boxes, lines, arrows, elbow and curved connectors and thirty presets, with fill, outline, dash, arrowheads, rotation, flip and text, on one-cell, two-cell and absolute anchors Yes, in shapes Yes, as DrawingML shapes and connectors Yes, the original XML while the shape is unedited See Shapes in files. LibreOffice lays columns out wider than Excel, so shapes it rewrote come back narrower by up to 6 %.
Shapes with a hand-drawn outline, groups and SmartArt Yes Written back in their original stacking position. Pictures inside a group are also drawn, read-only.
Pivot tables on a range or table of the workbook: row, column, value and filter fields, sum, count, average, min and max, show-as, date grouping, row and column subtotals, grand totals, compact, outline and tabular layout, repeated labels, calculated fields, and label, value and date filters Yes, in pivotTables Yes, as a PivotTable with its cache and records, plus the calculated cells See Pivot tables in files. LibreOffice lays the output out again when it loads the file and drops the filters and repeated labels when it saves.
Pivot tables with a distinct count, a calculated item, one field used in two places, or a date or value filter on a date-grouped field Yes, when they come from the workbook JSON The calculated cells only The file format has no worksheet PivotTable for these, or the exporter does not write it, so the file holds a static range. The export report names each one.
Pivot tables on an external, consolidated or data model (OLAP) source, with calculated items, a calculated field that uses a function outside the model, a fixed month or fixed quarter filter, values between row fields, or hidden items of a date-grouped field Yes The report names each one with the reason. LibreOffice and openpyxl both read the kept pivot table.
Slicers on a pivot table or a table: field, caption, position and selection Yes, in slicers Yes, as slicer and slicer cache parts See Slicers in files. LibreOffice and openpyxl open the file and ignore the slicers.
Slicers with a hidden caption, their own sort order or several pivot tables; timelines Yes The pivot table such a slicer filters is kept as it is too.
Embedded files: Word, Excel and PowerPoint packages, PDFs, Outlook messages and any other file Yes, in embeddedObjects Yes, with the embedding, its icon and its legacy shape See Embedded files. LibreOffice reads them and drops them when it saves as xlsx.
Form controls, ActiveX controls, linked objects Yes Their shapes are merged into the drawing that holds the notes.
VBA macros (.xlsm) Yes The project is kept byte for byte and the file is written as macro-enabled. Macros do not run in the component.
Custom XML parts, data connections, XML maps, thumbnail Yes
Calculation chain No No Excel rebuilds it.
Digital signatures No No A signature stops being valid when the file is saved again.
Encrypted (password-to-open) files Yes, with the password option Yes, with the password option Agile encryption in both directions, Standard encryption on import. See Password-protected workbooks.
Legacy .xls files No No Only the xlsx family (.xlsx, .xlsm) is read.

Details that apply to single features:

  • Print area and print titles are stored by Excel as the built-in names _xlnm.Print_Area and _xlnm.Print_Titles. They import into the sheet's pageSetup and do not appear among the workbook's defined names.
  • Fit to page follows the file format: fitToWidth: 1 alone fits the columns on one page and lets the rows run over as many pages as they need. A dimension you leave out is automatic.
  • Structured references are written fully qualified, as Excel stores them. On import, references to the table a cell belongs to are shown without the table name, as Excel shows them: =SUBTOTAL(109,[Amount]).
  • Automatic chart colours are written as theme colours, the way Excel writes them, so a series without a color stays automatic and a series whose color happens to equal the automatic one keeps it.
  • Sparkline colours equal to Excel's defaults are read as unset; they draw the same.
  • Tables without a style in the file import with style: 'None' and are written back without one.
  • Number formats are stored the way users type them. Escapes other programs add, such as yyyy\-mm\-dd, are removed on import.
  • Theme colours keep both forms. color: '#4472c4' with colorTheme: { theme: 4 } is written as the theme reference while the two agree, so the cell follows a theme change in Excel. Once you set a different color, that colour is written. The same holds for fill with fillTheme, for gradients and patterns against fill, and for horizontal against align.
  • Limits of the file format are applied on export rather than left for Excel to repair: an inline validation list is cut at 255 characters, hyperlinks longer than 2,079 characters are left out, defined names that are not valid names are left out, and a table needs at least one data row.

Filters#

A sheet's autoFilter and a table's filter hold the values shown per column and, for conditions that are not value lists, a criteria entry. Columns are numbered as sheet columns, starting at 0 for column A.

TypeScript
sheet.fromJSON({
  version: 1,
  sheets: [
    {
      name: 'Ledger',
      cells: { /* ... */ },
      hiddenRows: [2, 4, 6],
      autoFilter: {
        range: 'A1:E8',
        columns: { 2: ['Revenue', 'Staff'] },
        criteria: {
          3: { type: 'custom', conditions: [{ operator: 'greaterThan', value: '-5000' }] },
        },
      },
    },
  ],
});
Criteria Shape
Up to two conditions { type: 'custom', conditions: [{ operator, value }], matchAll? } with the operators equal, notEqual, greaterThan, greaterThanOrEqual, lessThan and lessThanOrEqual. matchAll joins them with AND instead of OR.
Top or bottom items { type: 'top', value, bottom?, percent? }
Excel's dynamic filters { type: 'dynamic', name, value?, maxValue? }, for example aboveAverage or thisMonth. value and maxValue are the limits Excel stored.

Filters by colour, icon and date group sit in a second record, special, keyed by column the same way:

Filter Shape
Fill or font colour { type: 'color', color, target? }. target: 'font' filters by font colour.
Icon { type: 'icon', iconSet, iconId? }. Without iconId it shows the cells with no icon.
Date groups { type: 'dateGroup', items, values?, blank? }, each item { grouping, year, month?, day?, hour?, minute?, second? } with grouping from year to second.

The rows a filter hides are saved as hidden rows, so the file opens showing the same rows. The component applies criteria and special filters when the workbook loads and shows them on the filter buttons and in the dropdown; see Filters and sort order from Excel files. A colour or date filter set from the component's own dropdown is stored as the list of values it lets through.

Sort state#

A sheet's sortState, and a table's, records how the range was last sorted. It does not sort anything by itself: the rows are already in that order in the file.

TypeScript
const sortState = {
  range: 'A2:E8',
  caseSensitive: true,
  conditions: [
    { range: 'C2:C8' },
    { range: 'D2:D8', descending: true },
    { range: 'B2:B8', customList: ['Rent', 'Payroll', 'Travel'] },
    { range: 'D2:D8', by: 'cellColor', color: '#c6efce' },
    { range: 'E2:E8', by: 'icon', iconSet: '3Arrows', iconId: 2 },
  ],
};

by is value (the default), cellColor, fontColor or icon. columnSort: true marks a left-to-right sort. On a sheet with a filter the sort state is written inside the filter, as Excel does. The component shows the direction on the filter button of the sorted column and writes sortState when a filtered range or a table is sorted.

Threaded comments#

Threaded comments live in the sheet's comments, separate from notes:

TypeScript
const comments = {
  C3: {
    text: 'Is the Lyon order in this number?',
    author: 'Lena Fischer',
    date: '2026-10-02T09:15:00.00',
    resolved: true,
    replies: [{ text: 'Yes, booked on 28 September.', author: 'Omar Haddad', date: '2026-10-02T10:02:00.00' }],
  },
};

They are written the way Excel 365 writes them: a thread part, a list of people, and a placeholder note that older versions of Excel and other programs show instead. If a program saved the file without the thread part, the conversation is rebuilt from the placeholder, without authors and dates.

SVG and WebP pictures#

Excel shows an SVG picture only when the file also carries a raster version of it, and it does not read WebP at all. On export:

  • An SVG picture with a fallback (a PNG or JPEG data URL on the image) is written as Excel writes it, with the raster picture and the SVG beside it. Import restores both.
  • An SVG without a fallback, and any WebP picture, is passed to a rasterizer. In browsers the export uses a canvas automatically. In Node and in workers there is no canvas, so pass your own through rasterizeImage, or call it yourself and set fallback.
  • Without a rasterizer, SVG and WebP are embedded as they are. LibreOffice shows the SVG; Excel shows a placeholder for both.
TypeScript
import { jsonToXlsx } from '@birchui/spreadsheet';
import sharp from 'sharp';

const bytes = await jsonToXlsx(workbook, {
  async rasterizeImage({ src, width, height }) {
    const input = Buffer.from(src.slice(src.indexOf(',') + 1), 'base64');
    const png = await sharp(input).resize(Math.round(width), Math.round(height)).png().toBuffer();
    return `data:image/png;base64,${png.toString('base64')}`;
  },
});

canvasImageRasterizer is the rasterizer the browser export uses, exported for when you call jsonToXlsx() yourself on a page. Pictures given as blob: or http: addresses are left out of the file; convert them to data URLs first.

Shapes in files#

The sheet's shapes are written into the drawing of the sheet as DrawingML: rectangles, rounded rectangles, ellipses and text boxes as shapes (xdr:sp), lines and arrows as connectors (xdr:cxnSp). Fill, outline colour and width, rotation, flips, the arrow head and the text with its font, size, colour and alignment are written, and all of it is read back into shapes.

  • Colours given as CSS names, rgb(), hsl() or with transparency are written as hex colours and read back that way: steelblue comes back as #4682b4 and rgba(0, 0, 255, 0.5) as #0000ff80.
  • Text with mixed formatting is kept as runs.
  • A shape that takes its colours from the theme style of the file is read with the resolved colours.
  • A shape that uses something the model has no form for (a preset outside the list, a gradient fill, vertical text, a macro, effects, the lock flags Excel sets on annotation boxes) is still read into shapes and drawn as closely as the model allows. Its original XML is kept in preserved.shapes and written back unchanged until you edit the shape; moving it rewrites only the anchor. Presets outside the list are reported under Shape outlines. A shape with a hand-drawn outline is not read into shapes; it is kept as it is and reported under Drawing objects.

Pivot tables in files#

A pivot table in pivotTables is written as a real PivotTable: a pivot cache definition with the source fields and their items, the cache records, the pivot table definition, and the pivotCaches entry of the workbook, with their relationships and content types. The calculated cells are written into the sheet as well, so a program that does not read pivot tables still shows the numbers. The cache is marked to refresh on load.

On import the definition is read back into pivotTables: source (a range or a table), destination, row and column fields, value fields with their aggregate, show-as and number format, filter fields with their selection, date grouping, subtotals and grand totals. The component calculates it again from the source data. A month grouping is stored as the year and month fields Excel uses and read back as one grouping. The selection of a slicer on a pivot table is written as hidden items of the pivot field.

How the rest of the definition is stored:

In the workbook JSON In the file
layout The compact and outline attributes of each pivotField, with compact, compactData, outline and outlineData on the definition. A file without them is compact, which is Excel's default. On import the first row field decides; layout is left out for tabular.
subtotalPosition: 'bottom' subtotalTop="0" on the pivot fields.
repeatItemLabels The Excel 2010 extension x14:pivotField fillDownLabels="1" on the row and column fields.
subtotal: false on a row or column field defaultSubtotal="0". Column subtotals are t="default" entries in colItems.
calculatedFields A cacheField with formula and databaseField="0", a pivotField that cannot be dragged to an axis, and a dataField on it for each use in values. The cache records hold the source fields only.
labelFilter, dateFilter, valueFilter A filter in the filters list of the definition, with its type (captionBeginsWith, dateBetween, thisMonth, count, valueGreaterThan and so on), stringValue1 and stringValue2, iMeasureFld for a value filter, and the autoFilter child Excel expects: custom filters, a top10 or a dynamicFilter. rowItems and colItems list only the items that pass.
  • A value filter with 'top' or 'bottom' is Excel's Top 10 filter by items. Top 10 by percent or by sum is not modelled.
  • A file whose filters carry no stringValue1 is read from the custom filter values, with the * wildcards of "begins with", "ends with" and "contains" removed.
  • A dynamic date filter is written with the first day of its period and the day after its last, worked out for now.
  • Excel calculates a calculated field with its own engine. The eleven functions the model accepts exist in Excel with the same meaning, but logical results show as TRUE and FALSE there and as 1 and 0 here.

Two cases do not produce a PivotTable:

  • Written as cells only. The file holds the calculated values, and importing it gives plain cells. jsonToXlsxWithReport() lists each such pivot under report.adjusted as { feature: 'Pivot tables', sheet, note }, where the note gives the reason. This happens for:
    • a distinct count. Excel has Distinct Count only for a PivotTable on the Data Model, and marks it there with an extension of the data field (x15:dataField isCountDistinct). ECMA-376 has no distinct count among the summary functions of a data field, and a PivotTable on a worksheet range that carries the extension is not a valid file, so none is written;
    • a calculated item;
    • a calculated field whose formula uses a function outside the eleven, or that has the name of another field;
    • one source column used in two places;
    • a date filter on a date-grouped field, or a label or value filter on a field grouped by quarter or month, where the grouped items here do not match Excel's;
    • a label filter and a date filter on the same field, which Excel does not allow;
    • a filter or slicer selection that hides every item, or a slicer on a date-grouped field.
  • Kept as it is. A pivot table in a file that the model cannot express is not read into pivotTables; its parts are written back unchanged and the component shows the cells stored in the file. This applies when the pivot reads an external, consolidated or data model (OLAP) source or another workbook, has calculated items, has a calculated field whose formula the model cannot calculate, has a filter of a kind the model lacks (top percent, top sum, a fixed month or quarter) or two label or date filters on one field, filters a field that is grouped by date, lays its values out on rows, summarises or shows values in a way the model lacks (product, running total and others), hides items of a row or column field, filters on a grouped field, has a cache that no longer matches the header row of its source, is connected to a slicer or timeline that is itself kept, or when its layout here would overwrite the cells next to it. The import report lists each one under Pivot tables with a note such as Channels is kept as it is because it has a percent filter.

LibreOffice 26.8 reads layouts and calculated fields, and writes neither the filters nor the repeated labels back. When it merges the caches of two pivots on the same range and one of them is grouped by date, it writes the wrong field index for a calculated field; such a pivot is then kept as it is on import.

A pivot table you add is written next to kept ones, with its own cache id and part names.

Slicers in files#

A slicer in slicers is written as a slicer part and a slicer cache part, the extension lists in the sheet and the workbook that point at them, the defined name Excel expects for each cache, and a frame in the drawing with a fallback rectangle for programs that have no slicers. Slicers on tables use the Excel 2013 table slicer cache; slicers on pivot tables use the pivot slicer cache with its items.

On import the target (pivot table or table), field, caption, position and selected items are read back into slicers. The names of the caches appear among the workbook's defined names as Slicer_... with the formula =#N/A, which is how the file stores them.

  • A slicer whose pivot table or table is not written (a table that does not exist, a pivot that is written as cells only) is left out of the file.
  • A slicer the model cannot hold is kept as it is, together with the pivot table it filters: one that hides its caption, has its own sort order, is connected to several pivot tables or filters a data model. Timelines are always kept as they are.
  • Slicers you add are written next to kept ones in the same extension lists.

Data tables in files#

A data table is written the way Excel writes it: the first result cell carries <f t="dataTable" ref="E2:G4" dt2D="1" dtr="1" r1="B3" r2="B2" ca="1"/>, where ref is the result range, r1 the row input cell and r2 the column input cell of a two-variable table, and every result cell holds its calculated value. A one-variable table has r1 only, with dtr="1" when the input values run along the row. On import the definition goes to dataTables on the sheet, the cached values go to the cells, and the results are calculated again when the workbook is loaded. A table whose input cell Excel marked as deleted (del1 or del2) is read as plain values.

openpyxl reads the definition and writes it back. LibreOffice has no data table of this kind: it converts each result cell to a multiple-operations formula, which it writes to xlsx as TABLE(formula, input, value, …). The importer recognises a full block of such formulas and turns it back into a data table, so a file that went through LibreOffice still has its tables; a block with gaps keeps the formulas, which show #NAME?. The cached values LibreOffice stores for these cells can be out of date, and are replaced by the recalculation on load.

Conditional formatting in files#

Rules are written in list order with priorities 1, 2, 3 and so on, and read back in priority order, whatever their order in the file. A rule on several areas is written with all of them in one sqref, and its formula is written for the first cell of the first area, which is where Excel measures relative references from.

Blank, error, date and text rules are written the way Excel writes them: the rule type (containsBlanks, timePeriod with its period, beginsWith and so on) together with the formula Excel generates for it, so programs that read only the formula get the same result. On import the rule type decides; a text rule without its text attribute takes the text from the formula.

A data bar is written twice, as Excel does: the Excel 2007 rule with colour and limits, linked to an Excel 2010 rule in the worksheet's extension list that holds the fill, border, negative colours, axis and direction. Bars are written as solid unless gradient is set, with a red negative fill and a grey axis, so a bar without options looks the same in Excel as in the grid. On import the extension rule wins where both exist. A file that has only the Excel 2007 rule gives a bar with colour and limits; a lowest or highest value limit there is read as automatic.

3Stars, 3Triangles and 5Boxes, and any rule with custom icons, exist only in the extension, with their own priority. They are read into the model from there. Rules of other types in the extension stay where they are and are written back unchanged, next to the rules written from the model. Their priorities are not renumbered, so they can clash with the new numbers when you add rules; Excel then decides the order.

validateXlsxPackage() checks that an extension-only icon set is not in the main part, that every data bar's link points at an existing extension rule, that custom icons match the size of their set and exist, and that no priority is used twice across both places.

Charts read from a file#

A chart read from a file keeps its original part. While its JSON is unchanged the part is written back as it was. When the edit is one of the following, it is merged into the original XML and everything else in the part stays as it was:

  • series ranges;
  • the chart title or an axis title: a new text goes into the first run and keeps that run's font, fill and effects; a title added to a chart or an axis that had none is written from the model; a removed title is removed;
  • a title font: only the attribute that changed (size, bold, italic, colour or family) is rewritten, on every run of that title;
  • a series colour: the fill of that series is replaced (the line of a line, scatter or radar series), its outline, shadow and data points stay;
  • a marker shape or size;
  • the chart area or plot area fill; outlines stay;
  • the legend position, or a legend added or removed. The merge does not depend on the namespace prefix the program used: it is checked on a workbook written by openpyxl and one written by LibreOffice, each with one chart of all ten types.

Any other edit, such as a new chart type, trendline or axis limit, writes a new chart part from the model. That part carries the series with their colours, markers, trendlines, error bars and data labels, the titles with their fonts, the two area fills, the legend position, stacking, the secondary axis, and the limits, unit, scale, order, number format, tick labels and gridlines of each axis. Formatting outside the model, such as gradients, line styles and tick-label fonts, is lost at that point.

What the file can hold decides a few details:

  • A data label position is written only where the chart type allows it: Excel rejects, for example, outsideEnd on a stacked column and any position on an area, doughnut or radar chart. The label is still written, without a position.
  • Trendlines are not written for stacked, pie, doughnut and radar charts. Error bars are not written for pie, doughnut and radar charts, one set is written per series, and two (x and y) for scatter and bubble charts.
  • The percentage of a data label is written for pie and doughnut charts only.
  • Axis limits, the major unit and a logarithmic base are written for value axes only.
  • When every series of a file carries the same data labels and the chart itself has none, they are read as the chart's dataLabels and dataLabelOptions.

What other programs keep of these options, measured on the workbook with every feature:

  • LibreOffice keeps trendlines with their type, order, period, forecast, name, equation and R² flags; error bars with their type, value, direction, side and custom ranges; data label positions, content and number formats; and axis limits, units, logarithmic scale, order, number formats, tick label positions, hidden axes and gridlines. It gives trendlines and error bars an explicit black line, drops "no end cap", states the default label position of column charts, stores chart-wide data labels on each series, moves a legend from the top right corner to the right side, drops major gridlines of a secondary value axis, and reverses the category axis of radar charts.
  • openpyxl reads all of these options. When it saves, it keeps one trendline per series (the last, without its name) and one set of error bars per series, and loses the tick label position none.

A scatter chart must start with c:scatterStyle, which the schema requires. Some programs leave it out; openpyxl does. Such a chart is read as it is, the element is added to the kept chart part on import, and every scatter chart is written with it. validateXlsxPackage() reports a scatter chart without it as chart-required.

Parts kept as they are#

Everything the importer does not model is carried along instead of being thrown away. The workbook JSON gets a preserved field, and so does each sheet that needs one. They hold the original parts (text as text, binary data as base64), the content types, the relationships, the worksheet and workbook elements the reader skipped, and their namespace declarations.

TypeScript
const workbook = await xlsxToJSON(await readFile('incoming/forecast.xlsm'));

workbook.preserved?.parts['xl/vbaProject.bin'];      // the macro project
workbook.sheets[1].preserved?.relationships;          // for example a control or a printer setting

await writeFile('reports/forecast.xlsm', await jsonToXlsx(workbook));

On export:

  • each kept part is written under its original name with its own relationship file, and new parts are numbered around them;
  • kept worksheet elements go back in the position the file format requires, and their relationship ids are rewritten to the new ones;
  • a workbook that carries a macro project is written with the macro-enabled content type, so save it as .xlsm;
  • parts that belonged to a sheet you removed are left out;
  • kept drawing objects are written next to the pictures, charts, shapes and slicers built from the JSON, in their original stacking position;
  • kept pivot tables and slicers keep their cache ids, and the ones built from the JSON are numbered after them;
  • a chart is written from its original part while its JSON is unchanged. If only ranges or the title changed, they are merged into the original XML. Moving or resizing a chart does not count as an edit.

What takes this route: macros, external links, form and ActiveX controls, linked objects, custom XML, printer settings, chart kinds outside the ten types, groups and SmartArt, timelines, and the pivot tables, slicers and shapes that the model cannot express (see Pivot tables in files, Slicers in files and Shapes in files). Pivot tables, slicers and shapes that the model can express are not kept this way: they are read into the JSON and written from it.

Treat preserved as opaque. It is plain JSON, so it passes through toJSON(), fromJSON(), a database column or postMessage unchanged. It can be large for files with macros or embedded objects. Kept elements are not adjusted when you insert or delete rows and columns, so a protected range or an ignored-error marker keeps pointing at its old cells. If you copy a sheet, the copy is written without the kept parts of the original.

Import report#

xlsxToJSONWithReport() returns the workbook together with a report of what happened to each feature of the file. inspectXlsx() returns the report alone.

TypeScript
import { xlsxToJSONWithReport } from '@birchui/spreadsheet';

const { workbook, report } = await xlsxToJSONWithReport(await file.arrayBuffer());

for (const entry of report.dropped) console.warn(`Not kept: ${entry.feature}`, entry.parts ?? entry.elements);
List Holds
modelled Features read into the workbook JSON, with a count. Pivot tables, slicers and shapes appear here when they were read into pivotTables, slicers and shapes.
preserved Features kept byte for byte but not editable, with the parts and elements involved and the sheet they belong to. A pivot table or slicer that is kept has a note with the reason. Shapes that are kept are listed under Drawing objects.
dropped Features that will be missing from the exported file, with a note saying why where there is a reason. A file refused by the zip limits appears here as File not opened.
adjusted Values that were changed to make the workbook consistent, with a note listing each change. Table column names that differ from their header cells appear here.

Each entry is { feature, sheet?, count?, parts?, elements?, note? }. A file can have the same feature in two lists: a workbook with one pivot table the model reads and one with its values on rows has Pivot tables under modelled with count: 1 and under preserved with the parts and the reason.

Table header cells and column names#

Excel stores the name of each table column twice: in the header cell and in the table definition. When a file disagrees with itself, or a workbook built in code names a column differently from its header cell, the header cell wins:

  • On import, a column whose header cell holds other text is renamed to that text, and structured references to the old name are rewritten. The report lists each rename under adjusted.
  • On export, a header cell is never overwritten when it holds a formula, a number or other text. The column is named after the text the cell shows, with a number appended if two columns would share a name. An empty header cell receives the column name.
  • jsonToXlsxWithReport(json) returns { bytes, report }, where report.adjusted lists the renames, the header cells that hold a formula or a value that is not text, and each pivot table written as cells only. exportXlsx({ onReport }) delivers the same report from the component.

Excel expects text in table headers. LibreOffice and openpyxl read a header cell that holds a number or a formula; Excel is expected to convert it to text when it opens the file. This has not been checked in Excel.

In the component, importXlsx() keeps the report of the file it loaded. getImportReport() returns it, the importReport event delivers it, and Review > Import report shows it to the user:

TypeScript
sheet.on('importReport', ({ report }) => {
  const kept = report.preserved.filter((entry) => entry.note);
  if (kept.length) console.info(kept.map((entry) => entry.note).join('\n'));
});

getImportReport() is undefined before the first import and after fromJSON() or update({ data }).

Checking a file#

validateXlsxPackage() inspects an xlsx file for the mistakes that make Excel offer to repair it. It needs no DOM and runs in Node, so it fits in a test or an upload handler:

TypeScript
import { jsonToXlsx, validateXlsxPackage } from '@birchui/spreadsheet';

const issues = await validateXlsxPackage(await jsonToXlsx(workbook));
for (const issue of issues) console.warn(`${issue.part}: ${issue.message} (${issue.rule})`);

It resolves to a list of { part, rule, message }, empty for a clean file. It checks, among other things:

  • that every XML part is well formed and every character is escaped;
  • the order of elements in worksheets, the workbook, styles, tables and charts, which the file format fixes;
  • that every part has a content type, every relationship has a unique id and an existing target, and every r:id in a sheet points at a relationship of the right kind;
  • cell references, row and cell order, cell types, style indexes and shared string indexes;
  • conditional formatting priorities, differential format indexes and the children each rule type needs;
  • defined name syntax and scope, sheet names, and the active tab;
  • that tables have unique names and ids, unique column names, a range as wide as their columns, and header cells whose text matches the column names;
  • that charts have their required elements and that every axis a chart group uses exists;
  • drawings and the order of the parts of a shape, notes, threaded comments and filters;
  • pivot tables: that the cache id is listed in the workbook, that the pivot fields match the cache fields, that the record count and every record index are right, that a calculated field has a formula and no records, that each filter names a row or column field, a known filter type, an id of its own and, for a value filter, a data field, and the order of the elements;
  • slicers: that each cache has its defined name and points at an existing pivot cache, sheet and field or at an existing table column.

It is a structural check, not a schema validator, and a file it accepts can still contain values Excel dislikes. The package runs it on every file its tests export.

How this is verified#

Excel compatibility, stated plainly. Exported files are verified with a structural validator, LibreOffice and openpyxl, and encrypted files with msoffcrypto-tool as well. No file has been opened in Microsoft Excel by the automated checks or by the authors. The validator encodes the rules that are known to make Excel repair a file, and slicers, which neither LibreOffice nor openpyxl reads, are checked against the file format only. Before you ship exports to Excel users, run the manual check below once.

The package ships a script that exports a workbook using every feature above and hands it to real programs:

Terminal
node packages/spreadsheet/scripts/validate-xlsx.mjs

It needs python3 with openpyxl, Pillow and olefile, and LibreOffice (soffice) on the PATH, and it runs the test files that are skipped in the normal test run. Three of them need msoffcrypto-tool as well and are skipped without it. The first works on the workbook with every feature:

  1. it exports the workbook and runs validateXlsxPackage() on it;
  2. it loads the file with openpyxl and makes about 330 assertions about cells, formulas, rich text, styles, gradients, borders, named styles, theme colours, dynamic arrays, views, document properties, filters, sort state, conditional formats with their date periods, stop flags, icon thresholds and data bar limits, validations, comments, links, tables, names, pictures, charts with their trendlines, error bars, data labels and axis scaling, shapes, pivot tables, slicers, protection, outline levels and page setup;
  3. it converts the file with LibreOffice to xlsx and to PDF, checks that the rewritten xlsx is still a valid package, and imports it again to compare each feature with the original;
  4. it imports the copy openpyxl saved and compares that too;
  5. it imports a workbook with a pivot table written by LibreOffice, a macro-enabled workbook with external links, custom XML, slicer and printer parts, and a workbook with shared formulas, exports each again, and checks with openpyxl and LibreOffice that the pivot table, its cache, the macro project and the other kept parts are still readable.

What those steps show for the three object kinds:

  • Shapes. The drawing holds the shapes and connectors with their presets, rotation, flip, text and arrow head (read from the XML in the openpyxl step, because openpyxl does not model shapes). After LibreOffice rewrites the file, every shape comes back with the same type, paint and text, anchored to the same cell, within 2 pixels in position and size.

  • Pivot tables. openpyxl loads each pivot table with its location, row, column, page and data fields, items, style, cache fields, shared items and cache records, and the cells hold the calculated values. After LibreOffice rewrites the file the four pivot tables are still pivot tables and import with the same fields, aggregates and totals; LibreOffice rewrites a table source as a cell range and lays the output out again. The copy openpyxl saved imports with the same pivot tables as well. A second workbook holds seven pivots for the layouts, column subtotals, label, value and date filters and a calculated field: openpyxl reads each of these from the definition (31 assertions) and its saved copy imports with every definition intact, less the repeated labels, which openpyxl does not keep. LibreOffice keeps all seven as pivot tables with their layout and calculated field, and drops the filters.

  • Slicers. The slicer and slicer cache parts are read from the XML and checked against the table column and pivot table they point at. LibreOffice and openpyxl have no slicers: both open the file, neither shows or keeps them, and the data the slicers filter is intact. LibreOffice keeps the fallback rectangles and the cache names.

  • Pictures, pictures in cells and embedded files. A workbook with one picture in each of nine formats (PNG, JPEG, GIF, BMP, TIFF, WebP, SVG, EMF and WMF), a picture placed in a cell and four embedded files is loaded by openpyxl, each raster picture is decoded by Pillow, and each embedded container is opened with olefile, which returns the embedded bytes. LibreOffice converts the workbook to OpenDocument with all nine pictures and all four embedded files, byte for byte, and writes the EMF and WMF bytes back unchanged when it saves as xlsx. LibreOffice does not write embedded files or pictures in cells to xlsx, and openpyxl loads neither EMF nor WMF.

The second test file covers encryption: LibreOffice and msoffcrypto-tool open workbooks encrypted here, and workbooks that LibreOffice (Standard encryption) and msoffcrypto-tool (Agile encryption) encrypted open here. The third covers OpenDocument files. The fourth is the pictures and embedded files check described above.

The normal test suite also checks every pivot table, pivot cache, slicer and slicer cache part of the workbook with every feature against the element sequences of the schemas (ECMA-376 CT_pivotTableDefinition and CT_PivotCacheDefinition with their children, and the slicer types of the Microsoft extension schema): each child must be one the schema allows, in schema order, with its required children and attributes. The sequences are written out in the test, separately from the validator.

Formula results are checked against LibreOffice in a suite of their own: see Verified against LibreOffice.

The normal test suite also imports files written by openpyxl and by LibreOffice (from CSV, from an OpenDocument sheet, a re-saved workbook, and one workbook from each program with a chart of every type) and checks that LibreOffice's cached results equal what the formula engine calculates.

Nothing here is tested in Microsoft Excel. No Excel installation is part of these checks. The file layout follows what Excel writes, and the validator covers the ordering and reference rules that are the usual cause of Excel's repair prompt, but that is not the same as opening the file in Excel. This matters most for slicers, which neither LibreOffice nor openpyxl reads, so their parts are checked against the file format only. Open a representative export in Excel before you rely on it.

Protection passwords#

Passwords are never stored. A sheet or workbook protected in Excel keeps its hash (SHA-512 with salt and spin count, or the legacy 16-bit hash), and unprotectSheet(password) checks the password against it. Protection in xlsx files stops casual edits; it is not encryption, and the cell contents are readable by anyone who has the file. To make a file unreadable without a password, encrypt it.

Charts and cached values#

Exported charts carry the values of their source cells as Excel's cached series data, so viewers that do not recalculate, such as file previews, still draw them. The series references point at the source ranges, so Excel redraws the chart from the live cells.

Dynamic arrays in files#

A formula that spills is written to its anchor cell as an array formula over its spill range, flagged with the cell metadata Excel uses for dynamic arrays (xl/metadata.xml). Excel then shows it as a dynamic array rather than a legacy array formula or a formula with an implicit @. The spilled cells are written with their cached values, as Excel writes them, so a program that does not recalculate, such as a viewer or openpyxl, shows the whole result.

The spill range comes from the spill field of the cell, which toJSON() fills in for every formula that spills. A workbook JSON you write by hand needs no spill: a formula that calls a dynamic array function such as FILTER, SORT, UNIQUE or SEQUENCE, or refers to a spill with A1#, is flagged as well.

The cached values come from the spillValues field of the anchor cell, a 2-D array that toJSON() fills in next to spill. Without it only the anchor's value is written.

On import, a dynamic array comes back as a formula with its spill range and, when the file has them, the cached spillValues; the cells of the spill are not imported as separate values, and Birch UI recalculates the spill. Excel's legacy array formulas import the same way and are written back as dynamic arrays.

Formulas Excel recalculates#

Exported files ask Excel to recalculate every formula when the file is opened, so results always match Excel's own engine, even for the rare function where the two differ.

Formula text#

Formulas inside xlsx files are stored without the leading = and with prefixes such as _xlfn. for newer functions. Birch UI converts in both directions, so the formulas in the workbook JSON always look like what users type: =XLOOKUP(A2, Codes!A:A, Codes!B:B).

  • GROUPBY and PIVOTBY are written as _xlfn.GROUPBY and _xlfn.PIVOTBY. A function name passed as an argument, as in =GROUPBY(A2:A9, D2:D9, SUM), is written as _xleta.SUM for the functions Excel offers there (SUM, AVERAGE, COUNT, COUNTA, MAX, MIN, MEDIAN, PRODUCT, CONCAT, ARRAYTOTEXT, PERCENTOF, STDEV.S, STDEV.P, VAR.S, VAR.P, MODE.SNGL); other names are written as typed. The prefix is removed on import. GETPIVOTDATA takes no prefix.
  • The spill range operator is stored as a function: =SUM(F2#) is written as SUM(_xlfn.ANCHORARRAY(F2)) and read back as F2#. The implicit intersection operator @ is stored as _xlfn.SINGLE().
  • 3-D references are stored as typed: SUM(Jan:Dec!B5), SUM('Q1 North:Q1 South'!B5).
  • NETWORKDAYS.INTL, WORKDAY.INTL and ISO.CEILING are in the function list of ECMA-376 and take no prefix. A prefix on any function is accepted on import.

Checking in Microsoft Excel#

The package ships a script that writes the workbooks worth opening in Excel, with a checklist of what to look for in each:

Terminal
node packages/spreadsheet/scripts/excel-check.mjs            # writes to packages/spreadsheet/excel-check
node packages/spreadsheet/scripts/excel-check.mjs ~/Desktop/birchui-excel-check
File What it exercises
01-kitchen-sink.xlsx Every modelled feature: styles, conditional formats, validation, tables, charts, sparklines, shapes, notes and threaded comments, names, page setup, document properties.
02-pivot-tables.xlsx Four PivotTables with their caches: a table source, date grouping in columns with a page filter, month grouping without column totals, and a compact pivot with a label filter and a calculated field.
03-slicers.xlsx A slicer on a table with two items selected and a slicer on a PivotTable.
04-encrypted.xlsx Agile encryption with 100,000 iterations; the password is birchui-check.
05-pivot-layouts-and-filters.xlsx Compact and outline layouts, column subtotals, a calculated field, label, top-items and date filters, and GETPIVOTDATA, GROUPBY and PIVOTBY formulas.
06-conditional-formats-and-charts.xlsx Rules for blanks, errors and date periods, stop if true, all twenty icon sets with custom icons, data bars with every option, and charts with trendlines, error bars, data labels and axis options.
07-data-tables.xlsx A two-variable data table and one-variable tables by column and by row over a loan model.
CHECKLIST.md The steps for each file, as a list to tick.

Open each file in Excel for Microsoft 365 or Excel 2021 and follow the checklist. If Excel offers to repair a file, save the repair log: it names the part Excel removed, which is the information a bug report needs. The folder is safe to delete, and you may want to add it to your ignore file.

↑ ↓ to move, Enter to open, Esc to close