Birch UI v0.1
Pricing

CSV and OpenDocument filesSpreadsheet

Read and write CSV and TSV with delimiter, quote and encoding detection and type inference, and open and save OpenDocument spreadsheets (.ods), with the exact subset each format carries.

Open .md

Besides xlsx, the package reads and writes delimited text (CSV and TSV) and OpenDocument spreadsheets (.ods), and reads legacy .xls files. All of this runs in the browser and in Node, needs no DOM, and does not use a license key.

Format Component Without the component
CSV, TSV importCsv(data, options?), exportCsv(options?) csvToJSON(data, options?), jsonToCsv(json, options?)
OpenDocument importOds(data, options?), exportOds(options?) odsToJSON(data, options?), jsonToOds(json, options?)
Excel 97-2003 (.xls), read only importXlsx(data, options?) xlsToJSON(data, options?), xlsToJSONWithReport(data, options?)

The File tab of the ribbon, a file dropped on the widget and openFile(file) pick the right import for a file by themselves. The import methods replace the workbook, like fromJSON(): the undo history is cleared and the import report of an earlier xlsx file is dropped. They take a string (CSV only), an ArrayBuffer or a Uint8Array, not a File, so read the file first:

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

input.addEventListener('change', async () => {
  const file = input.files?.[0];
  if (!file) return;
  if (/\.ods$/i.test(file.name)) await sheet.importOds(await file.arrayBuffer());
  else if (/\.(csv|tsv|txt)$/i.test(file.name)) sheet.importCsv(await file.arrayBuffer());
  else await sheet.importXlsx(file);
});

A file that cannot be read makes the call throw (or the promise reject) and emits an error event with the code import.

CSV and TSV#

TypeScript
sheet.importCsv(await file.arrayBuffer());

const csv = sheet.exportCsv();
const tsv = sheet.exportCsv({ delimiter: '\t' });

importCsv() is synchronous and loads the text as a workbook with one sheet. exportCsv() returns the active sheet as a string. To offer it as a download:

TypeScript
const blob = new Blob([sheet.exportCsv({ bom: true })], { type: 'text/csv;charset=utf-8' });
const link = Object.assign(document.createElement('a'), {
  href: URL.createObjectURL(blob),
  download: 'orders.csv',
});
link.click();
URL.revokeObjectURL(link.href);

In Node or a worker, convert through the workbook JSON:

scripts/orders-to-xlsx.ts
import { readFile, writeFile } from 'node:fs/promises';
import { csvToJSON, jsonToCsv, jsonToXlsx } from '@birchui/spreadsheet';

const workbook = csvToJSON(await readFile('incoming/orders.csv'), { sheetName: 'Orders' });

await writeFile('reports/orders.xlsx', await jsonToXlsx(workbook));
await writeFile('reports/orders.tsv', jsonToCsv(workbook, { delimiter: '\t', lineEnding: '\n' }));

What is detected#

Nothing has to be configured for an ordinary file. The reader works out:

  • The encoding, when the data is bytes. A byte order mark selects UTF-8, UTF-16 little endian or UTF-16 big endian. Without one the bytes are read as UTF-8, and if they are not valid UTF-8, as Windows-1252. Pass encoding to name another one; any label TextDecoder accepts works. A string is taken as it is.
  • The delimiter, among comma, semicolon, tab and pipe. The reader counts each candidate on the first 50 lines, ignoring quoted text, and picks the one that appears most consistently: the same number of times on every line. A first line of sep=;, which Excel writes and reads, decides the delimiter and is not loaded as data.
  • The quote character. It is " when the text contains one. A single quote is used only when there is no double quote and more than two fields are wrapped in single quotes.
  • The line ending: CRLF, LF or CR, from the first line break. The parser accepts any mix of the three, and line breaks inside quoted fields are kept.

Detection needs something to compare. With a single line, or when two delimiters fit equally well, the earlier candidate in the order comma, semicolon, tab, pipe wins, which usually means comma. When you know the delimiter, pass it.

detectCsvDialect(text) returns what was detected for a string, and readCsvDialect(data, encoding?) does the same for bytes or a string, including the encoding:

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

readCsvDialect(new Uint8Array(await file.arrayBuffer()));
// { delimiter: ';', quote: '"', lineEnding: '\r\n', encoding: 'windows-1252', hasBom: false }

A CsvDialect is { delimiter, quote, lineEnding, encoding, hasBom }. Use it to show a preview with the detected settings, or to write a file back in the dialect it came in.

parseCsv(text, options?) is the parser alone. It returns { rows, quoted, dialect }: the fields as strings, a matching grid of booleans saying which fields were quoted, and the dialect used. It does no type inference.

Types#

Fields that are not quoted are converted:

Text in the file Cell
12, -3.5, 1e3 A number.
1,234,567, 1,234.50 A number with the format #,##0 or #,##0.00.
45%, 35.25% A fraction (0.45) with the format 0% or 0.00%.
TRUE, false A boolean, in any case.
2026-03-09 A date serial with the format yyyy-mm-dd.
2026-03-09T06:00:00, 2026-03-09 06:00 A date and time serial with the format yyyy-mm-dd hh:mm:ss. A trailing Z is accepted; no time zone conversion is made.
An empty field No cell.

These stay text:

  • every quoted field, so "1,234.50" and "00123" are text;
  • identifiers with a leading zero, such as 00123;
  • numbers with more than 15 digits, which a spreadsheet number cannot hold exactly;
  • dates that do not exist, such as 2026-02-30, dates before 1900, and, unless a locale or dateOrder is given, dates not written in ISO form, such as 09/03/2026;
  • fields that start with =, unless you pass formulas: true;
  • anything else.

With decimalSeparator: ',' the roles of comma and point swap: 1.234,5 is 1234.5. This is for files from locales that write decimals with a comma; they normally use a semicolon as the delimiter, which is detected.

Dates and numbers of a locale#

locale: 'en-GB' reads 03/04/2026, 3.4.2026 and 3-4-26 as 3 April 2026, with the format dd/mm/yyyy; 'en-US' reads the same text as 4 March, with mm/dd/yyyy. The order of day, month and year and the decimal separator are taken from Intl for the tag; dateOrder ('dmy', 'mdy' or 'ymd') and decimalSeparator override them. A two-digit year below 30 is 20xx, otherwise 19xx. A date that does not exist in that order, such as 17/04/2026 under en-US, stays text. Without locale and dateOrder only ISO dates are converted, as before.

The import dialog#

A CSV, TSV or text file opened from File > Open or dropped on the grid first shows an import dialog with three lists and a preview of the first rows:

List Choices
Delimiter Detect, comma, semicolon, tab, vertical bar
Encoding Detect, UTF-8, UTF-16 LE and BE, Windows-1252, ISO-8859-1, ISO-8859-15, Windows-1250, Shift_JIS
Dates and numbers as in None (ISO dates and decimal points only), or one of eleven locales plus the spreadsheet's own locale, which is the default

The preview is read again after every change and aligns the fields it would import as numbers or dates to the end. Import replaces the workbook; Cancel leaves it alone. openFile() from code and importCsv() do not show the dialog, and csvImportDialog: false turns it off for the File tab and for drops.

Import options#

CsvImportOptions, for importCsv(), csvToJSON() and parseCsv():

Option Default Effect
delimiter detected The field separator. Use '\t' for TSV when detection is not enough.
quote detected The quote character.
encoding detected The encoding of bytes, as a TextDecoder label such as 'iso-8859-2' or 'shift_jis'. Ignored for strings.
sheetName 'Sheet1' The name of the sheet.
inferTypes true false loads every field as text.
decimalSeparator '.', or that of locale ',' reads 1.234,5 as a number.
locale none A BCP 47 tag whose date order and decimal separator are used. See Dates and numbers of a locale.
dateOrder that of locale 'dmy', 'mdy' or 'ymd' for dates such as 03/04/2026.
formulas false true loads unquoted fields that start with = as formulas, which then calculate. Leave it off for files you do not trust.
trim false true removes spaces around unquoted text. Numbers, booleans and dates are recognised with surrounding spaces either way.
maxRows no limit Stop after this many rows, for example to build a preview.

Export options#

CsvExportOptions, for exportCsv() and jsonToCsv():

Option Default Effect
sheet the active sheet The name of the sheet to write. An unknown name throws.
range the used range A range such as 'B2:F40'. The used range starts at A1 and ends at the last row and column with a value.
delimiter ',' The field separator. '\t' writes TSV.
quote '"' The quote character. A quote inside a field is doubled.
lineEnding '\r\n' '\r\n', '\n' or '\r'. Every line ends with it, including the last.
bom false true starts the text with a byte order mark, which Excel needs to read UTF-8 correctly when a CSV file is opened by double-click.
values 'formatted' 'formatted' writes what the cell shows, with its number format: 48.40, 45%, 2026-03-09. 'raw' writes the stored value: 48.4, 0.45, 46090.
quoteAll false Quote every field. By default a field is quoted only when it contains the delimiter, the quote character, a line break, or leading or trailing space.
escapeFormulas true Guard against CSV injection; see below.

Formulas are written as their calculated values. Error values are written as their code, such as #DIV/0!. Formatting, merges and everything else that is not a value is left out, and only one sheet is written per file.

CSV injection#

A CSV file opened in a spreadsheet program is interpreted again: a text cell that starts with =, +, - or @ can be run as a formula. Text cells that start with =, +, -, @, a tab or a carriage return are therefore written with a leading apostrophe, which makes the program treat them as text. Numbers are not touched, so -5 stays -5. This is on by default; pass escapeFormulas: false when the file goes to a program that reads CSV as plain data and must see the text unchanged.

TypeScript
const guarded = sheet.exportCsv(); // "'=HYPERLINK(...)"
const exact = sheet.exportCsv({ escapeFormulas: false }); // "=HYPERLINK(...)"

importCsv() and csvToJSON() remove that apostrophe again, so text written by the guard reads back as it was. Pass unescapeFormulas: false to keep it.

The same caution applies on the way in: formulas is off by default, so a field such as =HYPERLINK(...) arrives as text.

OpenDocument spreadsheets#

TypeScript
await sheet.importOds(await file.arrayBuffer());

const bytes = await sheet.exportOds();
scripts/ods-to-xlsx.ts
import { readFile, writeFile } from 'node:fs/promises';
import { jsonToOds, jsonToXlsx, odsToJSON } from '@birchui/spreadsheet';

const workbook = await odsToJSON(await readFile('incoming/budget.ods'));

await writeFile('reports/budget.xlsx', await jsonToXlsx(workbook));
await writeFile('reports/budget-copy.ods', await jsonToOds(workbook));

exportOds() writes the whole workbook, not only the active sheet.

Option Function Default Effect
compress jsonToOds(), exportOds() true false writes a larger file faster.
maxRepeatedRows odsToJSON(), importOds() 1000 An ods file stores identical neighbouring rows and cells once with a repeat count. A row or cell with content is repeated at most this many times; raise it for files that really have longer runs of identical rows.

What an ods file carries#

The ods support is a subset, chosen to move data and basic formatting between programs. For full fidelity use xlsx or the workbook JSON.

These round-trip:

Feature Notes
Sheets Names and the hidden state.
Values Text (with line breaks), numbers, booleans, dates, times, percentages and currency amounts.
Formulas Converted between Excel syntax and OpenFormula in both directions. The calculated value is stored next to the formula.
Cell styles Bold, italic, underline, strikethrough, text colour, font size and family, fill colour, horizontal and vertical alignment, wrap, borders, rotation and the unlocked flag.
Number formats By category: number with its decimals and thousands grouping, percent, currency, date, date and time, and time. The exact format code is not preserved: a date comes back as yyyy-mm-dd, a date and time as yyyy-mm-dd hh:mm:ss, a time as hh:mm:ss.
Layout Merged cells, column widths, row heights, hidden rows and hidden columns.
Defined names Workbook-level names.
Data tables Written as MULTIPLE.OPERATIONS formulas, which is how LibreOffice stores them, and read back from a full block of such formulas.

These are not carried in an ods file. On export they are left out, and on import they are not read:

  • charts, pictures, pictures in cells, embedded files and shapes;
  • conditional formatting and data validation;
  • notes and comments (annotations in a file are skipped on import);
  • tables, pivot tables, slicers and filters;
  • frozen panes and other view settings, page setup;
  • rich text runs inside a cell (the text is kept, the per-run formatting is not);
  • sheet-scoped defined names;
  • sheet and workbook protection;
  • formulas with structured references such as Orders[Amount]: OpenFormula has no form for them, so the cell is written with its calculated value only.

Export to ods from a workbook that uses these and they are gone from the file. Nothing warns about it, so keep the workbook JSON or an xlsx file as the master copy.

Formula conversion#

toOpenFormula() and fromOpenFormula() are the converters the ods functions use:

TypeScript
import { fromOpenFormula, toOpenFormula } from '@birchui/spreadsheet/ods';

toOpenFormula("=SUM(A1:B2,'Rates 2026'!$B$1)"); // "of:=SUM([.A1:.B2];[$'Rates 2026'.$B$1])"
fromOpenFormula('of:=IF([.A1]>0;"yes";"no")'); // '=IF(A1>0,"yes","no")'
toOpenFormula('=SUM(Orders[Amount])'); // undefined

toOpenFormula() returns undefined for a formula it cannot express: one with a structured reference, an invalid reference or a syntax error. Function names are passed through unchanged, so a function that the other program does not have shows an error there.

Legacy .xls files#

.xls files written by Excel 97 to 2003 (the BIFF8 format) can be opened. There is no .xls export: save as xlsx.

TypeScript
import { readFile } from 'node:fs/promises';
import { createFormulaEngine, xlsToJSONWithReport } from '@birchui/spreadsheet';

const { workbook, report } = xlsToJSONWithReport(await readFile('archive/budget-2003.xls'));
const engine = createFormulaEngine();
engine.fromJSON(workbook);
console.log(report.dropped); // what the file holds that was not read

xlsToJSON(data, options?) returns the workbook JSON and xlsToJSONWithReport() adds a report in the shape of the xlsx import report. Both are synchronous and take a Uint8Array or an ArrayBuffer. In the component, importXlsx() recognises a legacy workbook by its content and opens it the same way, and so do xlsxToJSON(), xlsxToJSONWithReport() and inspectXlsx(); the file name does not matter.

What is read:

Feature Notes
Sheets Names, order, hidden and very hidden sheets, and the active sheet. Chart sheets, macro sheets and dialog sheets are skipped and counted in the report.
Values Numbers, text, booleans and errors, including text stored in the shared string table across several records.
Dates A date is a number with a date format, as in xlsx. Workbooks in the 1904 date system are converted to the 1900 system: 1,462 days are added to every number in a cell with a date format.
Formulas Converted from the stored tokens back to text: constants, cell and area references, shared formulas, references to other sheets of the workbook and 3-D references across sheets, operators, parentheses, omitted arguments, array constants, defined names and function calls. The last calculated value is kept next to the formula.
Array formulas Read as a formula on the first cell of the range that spills, as legacy array formulas are in xlsx.
Defined names Workbook and sheet names that refer to cells or constants. The built-in names for print areas and print titles are not read.
Number formats The format codes of the file, and the built-in codes by number.
Cell styles Font name, size, bold, italic, underline, strikethrough, superscript and subscript, font colour; fill colour and pattern; horizontal and vertical alignment, wrap, indent, rotation, shrink to fit; borders with style and colour, including diagonals; the unlocked and hidden-formula flags. Colours come from the file's palette.
Layout Merged cells, column widths, row heights that were set by hand, hidden rows and columns, and frozen panes.
Data tables One- and two-variable what-if tables become data tables.

What is not read. report.dropped counts these when the file contains them:

  • charts, pictures and shapes;
  • notes and comments, and hyperlinks;
  • conditional formatting and data validation;
  • pivot tables and autofilters;
  • sheet and workbook protection;
  • formatting of parts of a cell's text (the text is kept);
  • VBA macros, which are neither run nor kept;
  • chart sheets, macro sheets and dialog sheets.

These are not read either, and the report does not mention them: page setup, print areas and print titles, outline levels, sort state, zoom and other view settings, and document properties.

A formula is kept only when every part of it can be converted and every function exists in this engine. Otherwise the cell keeps its last calculated value as a plain value, and the report counts it under Formulas. A defined name that cannot be converted is left out and counted under Defined names.

Files that are refused, each with an XlsError whose message starts with "This .xls file cannot be read":

  • workbooks protected with a password to open (the stream is encrypted);
  • workbooks saved by Excel 5.0 or 95 (BIFF5) and older (BIFF2 to BIFF4);
  • files that are truncated or damaged in a way that leaves no readable workbook.

Limits#

The reader checks every record length and every offset against the file, and stops with an XlsError when a file is over one of these limits. They exist because a small damaged or hostile file can otherwise ask for a great deal of work or memory.

Limit Default Meaning
maxRecords 5,000,000 Records read from the workbook stream, over all sheets.
maxCells 5,000,000 Cells with a value or a style, over all sheets.
maxSharedStrings 2,000,000 Entries of the shared string table.
maxStringLength 32,767 Characters in one text value, name or sheet name.
maxTextBytes 256 MiB Total size of the shared strings in memory.
TypeScript
const workbook = xlsToJSON(bytes, { limits: { maxCells: 200_000 } });
await sheet.importXlsx(file, { xlsLimits: { maxCells: 200_000 } });

DEFAULT_XLS_LIMITS holds the defaults, and isXlsWorkbook(bytes) tells a legacy workbook from other files.

How this is verified#

.xls reading is checked against six workbooks that LibreOffice converted from xlsx to .xls, among them one with dates in both date systems, merged cells, formats, 3-D references, defined names and a data table. Each is read from both files, and the two results must agree on sheets, values, formulas, number formats, styles, merged cells and sizes, and calculate to the same results in the engine. With LibreOffice installed, a further check converts a workbook with a formula for every built-in function: every formula LibreOffice keeps as a formula in the .xls file, more than 1,400 of them, comes back with the same text as from the xlsx file. LibreOffice itself replaces about 130 formulas whose functions the format cannot hold with #N/A or an equivalent expression. Another test feeds the reader 900 truncated and corrupted copies of the six workbooks, and a workbook assembled record by record covers the record types LibreOffice does not write. No .xls file written by Microsoft Excel is part of the tests.

CSV is covered by unit tests, including a budget file written by LibreOffice whose formulas calculate after import.

For ods, the tests run LibreOffice 26.8 (with node packages/spreadsheet/scripts/validate-xlsx.mjs, see How this is verified):

  • LibreOffice opens the exported file, recalculates it and shows the formatted values. It then saves the file again, and the re-saved file reads back with the same formulas, values, styles, merge, column width, hidden row and hidden sheet.
  • A spreadsheet authored in LibreOffice is saved as .ods and as .xlsx, and both are read. The two results match cell for cell in values and formulas.

Neither format is tested in Microsoft Excel.

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