@alosha/xlsx
v0.14.0
Published
A modern TypeScript library for reading and writing XLSX spreadsheets, inspired by exceljs.
Maintainers
Readme
@alosha/xlsx
A modern TypeScript library for reading and writing XLSX spreadsheets — a fresh rewrite inspired by exceljs.
@alosha/xlsx reads and writes real .xlsx (OOXML) workbooks from a single, ESM-first
document model. The public surface is intentionally ExcelJS-shaped, so most code ports with
minimal changes — but the internals are a clean rewrite with a discriminated-union value model,
no per-cell class allocation, and a single runtime dependency (fflate).
Install
pnpm add @alosha/xlsx
# or
npm install @alosha/xlsx
# or
yarn add @alosha/xlsxRequires Node.js >= 22. The package ships ESM + CJS builds and full type declarations.
Write a workbook
import { Workbook } from "@alosha/xlsx";
const workbook = new Workbook();
workbook.creator = "Ada Lovelace";
const sheet = workbook.addWorksheet("Report");
// Address strings or (row, col) numbers both work.
sheet.getCell("A1").value = "Item";
sheet.getCell("B1").value = "Qty";
sheet.getCell("A2").value = "Widgets";
sheet.getCell("B2").value = 42;
// Number formats and formulas.
sheet.getCell("B2").numFmt = "#,##0";
sheet.getCell("B3").value = { formula: "SUM(B2:B2)", result: 42 };
// Column widths and merged cells.
sheet.getColumn(1).width = 24;
sheet.getCell("A4").value = "Total";
sheet.mergeCells("A4:B4");
// Serialize to bytes (browser-safe) …
const bytes: Uint8Array = await workbook.xlsx.writeBuffer();
// … or straight to disk (Node only).
await workbook.xlsx.writeFile("report.xlsx");writeBuffer() returns a Uint8Array and never touches node:fs, so it runs in the browser,
a worker, or an edge runtime. writeFile() is the Node convenience wrapper.
Read a workbook
load / readFile mutate the receiving workbook in place and return it (matching ExcelJS):
import { Workbook } from "@alosha/xlsx";
// From bytes you already have (fetch, upload, buffer) …
const workbook = new Workbook();
await workbook.xlsx.load(bytes); // bytes: Uint8Array
// … or from a path (Node only).
await workbook.xlsx.readFile("report.xlsx");
const sheet = workbook.getWorksheet("Report");
console.log(sheet?.getCell("B2").value); // 42
console.log(sheet?.getCell("A1").text); // "Item"
sheet?.eachRow((row, rowNumber) => {
console.log(rowNumber, row.values);
});The free-function core
The workbook.xlsx.* accessor is a thin ExcelJS-style wrapper over an environment-agnostic,
synchronous core. Reach for these when you want no magic accessor, tree-shakeable imports,
or to keep the model layer free of the serializer:
import { Workbook, writeWorkbookBuffer, readWorkbookBuffer } from "@alosha/xlsx";
const wb = new Workbook();
wb.addWorksheet("Sheet1").getCell("A1").value = "hi";
const bytes: Uint8Array = writeWorkbookBuffer(wb); // sync
const roundTripped: Workbook = readWorkbookBuffer(bytes); // syncNode-only file variants (writeWorkbookFile, readWorkbookFile) are also exported. Bundlers select
the browser build automatically; buffer and async-iterable APIs require no Node filesystem polyfills.
File APIs in that build reject with UnsupportedFeatureError.
writeWorkbookBuffer accepts a WriteOptions (useSharedStrings, useStyles); the read
functions accept ReadOptions with configurable ZIP and model allocation limits.
Reads default to 128 MiB of compressed input, 10,000 ZIP entries, 256 MiB per expanded entry, and 1 GiB of total expanded entries. Model limits are shared across all worksheets in each import:
| Option | Default | Counts |
| --- | ---: | --- |
| maxCells | 1,000,000 | Allocated cell objects, including styled blanks, merge slaves, and cells created by comments or hyperlinks |
| maxRows | 1,048,576 | Allocated row objects; gaps before a sparse row do not count |
| maxMergeCells | 100,000 | Sum of merged-range areas, including their masters; checked before enumerating each range |
| maxColumnDefinitions | 100,000 | Expanded <col min="…" max="…"> definitions, including repeated ranges |
Existing cells are counted once even when a merge also covers them. Override these for larger trusted workbooks:
await workbook.xlsx.load(bytes, {
maxInputBytes: 256 * 1024 * 1024,
maxEntries: 20_000,
maxEntryBytes: 512 * 1024 * 1024,
maxTotalBytes: 2 * 1024 * 1024 * 1024,
maxCells: 5_000_000,
maxMergeCells: 1_000_000,
});Each limit accepts Infinity to disable it. Exceeding a budget throws ReadLimitError with
code: "READ_LIMIT_EXCEEDED", limit, maximum, and actual. These options also work with
readFile, byte-stream read, and the free functions; streamed input stops at maxInputBytes.
Model budgets apply only while importing and reset on each read. They do not restrict later edits.
The limits bound ZIP bytes and model counts, not exact heap memory consumption. Excel's hard grid
limits (1,048,576 rows and 16,384 columns per sheet) still apply when an import budget is disabled.
Imports remain tolerant by default. Opt into structured diagnostics when preserving workbook features matters:
await workbook.xlsx.load(bytes, {
onWarning: (warning) => console.warn(warning.code, warning.part, warning.message),
strict: true,
});onWarning runs synchronously with a frozen ImportWarning containing code, part, feature,
message, and optional ref. The library does not log warnings itself. strict: true throws
ImportWarningError (code: "IMPORT_WARNING", .warning) after reporting the first warning;
a failed load preserves the receiving workbook. Observer exceptions propagate unchanged.
Diagnostics cover known discarded charts, tables, pivots, threaded comments, selected workbook/sheet
settings and foreign XML, missing relationship targets, and selected invalid references or part roots.
Strict mode is a known-loss check, not full schema validation or a guarantee of lossless round trips.
Numeric and string coordinates use the same bounds, including numeric ranges and row/column edits.
Out-of-range coordinates throw InvalidAddressError or InvalidRangeError. Cell numbers and cached
formula results must be finite, and Date values must be valid; assigning, importing, or serializing
invalid values throws InvalidCellValueError. The string "NaN" and explicit Excel error values
such as { error: "#NUM!" } remain supported.
decodeAddress() returns a frozen, cached object with readonly coordinates. Use { ...decoded }
when you need an editable copy. Quoted sheet references support Excel's doubled-apostrophe syntax,
for example decodeEx("'O''Brien'!$B$2") returns sheetName: "O'Brien".
Readers resolve supported OOXML namespaces by URI, independently of prefix spelling. Namespace declarations follow XML scope, relationship attributes are resolved by namespace, and foreign namespace subtrees are skipped rather than interpreted as worksheet data.
Streaming writes for large workbooks
For exports too big to hold in memory, the streaming WorkbookWriter (ExcelJS's
stream.xlsx.WorkbookWriter shape) renders and deflates each row into the output archive as you
commit it, keeping peak memory roughly flat regardless of row count — at 500k rows × 5 cols it
used ~14.2× less peak memory than the buffered writer at ~1.9× the throughput in the published benchmark
(benchmarks):
import { WorkbookWriter } from "@alosha/xlsx";
const wb = new WorkbookWriter({ filename: "big-report.xlsx" });
const ws = wb.addWorksheet("Data");
async function* exportRows() {
for await (const record of hugeDataset) {
yield [record.id, record.name, record.amount];
}
}
await ws.writeRows(exportRows()); // yields to the destination every 10,000 rows
ws.commit();
await wb.commit();Instead of a filename, pass a Node Writable ({ stream: res }) — or pass nothing and the
writer itself is an AsyncIterable<Uint8Array> of archive chunks (browser/edge-safe). Strings
default to inline (useSharedStrings: false) so committed rows retain nothing. Styles, merges,
panes/auto-filter, column widths, hyperlinks, data validation, conditional formatting, comments, and
images all stream; a streaming reader is not supported yet. See
docs/STREAMING.md
for the full guide. For a manual addRow().commit() loop, call await wb.flush() periodically:
without an await point, compressed output accumulates until the loop finishes.
Streaming shared-formula masters must declare shareType: "shared", formula, and a complete
ref before their slaves are committed. Array masters require shareType: "array", formula,
and ref. Undeclared shared masters are rejected rather than producing an empty formula.
Commit rows once, in creation order, before committing the worksheet.
Feature matrix
| Area | Read | Write | Notes |
| --- | :---: | :---: | --- |
| Cell values — string, number, boolean, date | ✅ | ✅ | 1900 and 1904 date systems |
| Formulas (with cached result) | ✅ | ✅ | shared/array formulas round-trip |
| Rich text runs | ✅ | ✅ | per-run fonts |
| Error values (#REF!, #DIV/0!, …) | ✅ | ✅ | |
| Shared strings | ✅ | ✅ | useSharedStrings toggle on write |
| Styles — fonts, fills, borders, alignment, number formats, protection | ✅ | ✅ | useStyles toggle on write |
| Merged cells | ✅ | ✅ | |
| Column width / styles / keys | ✅ | ✅ | |
| Row height / styles / outline levels | ✅ | ✅ | |
| Multiple worksheets, sheet state (visible / hidden / veryHidden) | ✅ | ✅ | |
| Workbook & sheet views (freeze/split, zoom, active tab) | ✅ | ✅ | round-trip as data |
| Sheet auto-filter range | ✅ | ✅ | ref range only; filter criteria/sort state deferred |
| Workbook metadata (creator, dates, title, …) | ✅ | ✅ | |
| Hyperlink cells (external URL/mailto) | ✅ | ✅ | real OOXML relationship, round-trips as { text, hyperlink, tooltip? }; internal location= links deferred |
| Data validation (dropdowns, constraints) | ✅ | ✅ | same-sheet ranges and inline lists; cross-sheet list refs deferred |
| Conditional formatting (cellIs, expression, text-contains family, top10, aboveAverage/belowAverage, duplicateValues/uniqueValues, colorScale, dataBar, iconSet) | ✅ | ✅ | differential styles dedup into a <dxfs> pool; x14 dataBar gradient/axis/negative-fill, timePeriod rules, and custom iconSet icons deferred |
| Streaming write (WorkbookWriter) | ❌ | ✅ | row-by-row writes with explicit shared/array formula groups; streaming read deferred — see docs/STREAMING.md |
| Embedded images (workbook.addImage + worksheet.addImage) | ✅ | ✅ | two-cell and one-cell/pixel-extent anchors; cropping/rotation, background/header-footer images, SVG, and EMF/WMF deferred |
| Charts | ❌ | ❌ | deferred |
| Comments (cell.note) | ✅ | ✅ | note/author table (comments{n}.xml) + legacy VML anchor (vmlDrawing{n}.vml); threaded/modern comments and box geometry deferred |
Migrating from ExcelJS
The API is deliberately familiar — new Workbook(), addWorksheet, getCell, getRow,
mergeCells, and the workbook.xlsx.writeBuffer / writeFile / load / readFile accessor all
behave as you'd expect. Common differences to watch for:
- Bytes, not Node
Buffer.writeBuffer()resolves to aUint8Array. In Node aUint8Arrayis accepted anywhere aBufferis (fs.writeFile,res.end, …); pass it through, or wrap withBuffer.from(bytes)if an API insists on aBuffer. worksheetsis a dense, 0-based array. No leadingundefined/ 1-based sparse hole —workbook.worksheets[0]is the first sheet. UsegetWorksheet(idOrName)for lookups by id or name — name lookups fall back to a case-insensitive match (mirroring the case-insensitive duplicate ruleaddWorksheetenforces), sogetWorksheet("report")still finds a"Report"sheet.- Clearer row inheritance. Instead of ExcelJS's
'i' | 'o' | 'i+' | 'o+'DSL,addRow/insertRowtake{ inheritFrom: "above" | "below", includeEmpty?: boolean }. - ESM-first. The package is ESM with a CJS fallback; prefer
importoverrequire.
Not everything ExcelJS does is implemented yet — check the feature matrix and limitations before porting a workbook that leans on charts or streaming reads.
Want a one-line import swap instead? @alosha/xlsx/compat is an ExcelJS-shaped drop-in — same
cell.type numbers, same style-setter precedence, same addRow/row.values/worksheet.columns
behaviour — for code that shouldn't need to change beyond import ExcelJS from "@alosha/xlsx/compat".
See docs/MIGRATION.md for the supported/deferred matrix and the seven
behavioural notes to check before porting.
Known limitations
- Internal (in-workbook) hyperlinks are deferred. External
http(s)/mailtocell hyperlinks round-trip as real OOXML relationships ({ text, hyperlink, tooltip? }). Links to a location within the same workbook (ExcelJS'slocation="Sheet2!A1"form, no external relationship) aren't written or read yet. - Streaming is write-only. The streaming
WorkbookWritersupports the sheet features above, including column widths (docs/STREAMING.md); reading is still buffer-based (the whole workbook lives in memory) — a streamingWorkbookReaderis deferred, and soExcelJS.stream.xlsx.WorkbookReaderin@alosha/xlsx/compatstill throws (ExcelJS.stream.xlsx.WorkbookWriteris a real bridge onto the streaming writer). - Embedded images support the two anchor forms ExcelJS uses day-to-day — a two-cell range
(
"B2:D6"or{ tl, br }) and a one-cell position with a pixel extent ({ tl, ext }). Image cropping/rotation/effects, hyperlinked images, header/footer (background) images, SVG, and EMF/WMF are deferred;worksheet.addBackgroundImagestays a permanent stub. - No charts. These parts are ignored on read and not emitted on write.
- Comments (
cell.note) round-trip plain-string and rich-text notes plus a multi-author<authors>table, backed bycomments{n}.xml+ a legacyvmlDrawing{n}.vmlanchor. Threaded/modern comments (xl/threadedComments/) and comment box geometry/margins/editAs/visibility are deferred — a default note-box shape is emitted and its geometry is ignored on read. - Data validation (list dropdowns, whole/decimal/date/time/text-length constraints, custom
formulas) is supported for same-sheet ranges and inline lists. A list referencing a range on
another sheet (the x14/
<extLst>form Excel uses for that case) is deferred. - Conditional formatting covers
cellIs,expression, the text-contains family (containsText/notContainsText/beginsWith/endsWith),top10,aboveAverage/belowAverage,duplicateValues/uniqueValues, and the self-visualisingcolorScale/dataBar/iconSetrules, with differential styles deduped into a shared<dxfs>pool. Deferred: the x14/<extLst>dataBar extensions (gradient fill, axis, negative-value fill) — only the ECMA-376 baseline<dataBar>is emitted —timePeriodrules, and customiconSeticons.
See BENCHMARKS.md for
write/read throughput and output-size numbers against ExcelJS, and
CHANGELOG.md for release notes.
Development
This project uses pnpm, tsup, Biome, and Vitest.
pnpm install # install dependencies
pnpm build # build ESM + CJS + type declarations
pnpm dev # rebuild on change
pnpm test # run the test suite once
pnpm test:watch # run tests in watch mode
pnpm lint # lint + format check with Biome
pnpm format # auto-format with Biome
pnpm typecheck # type-check with tsc
pnpm test:package # after build: packed ESM/CJS, downstream types, browser consumersA note on pnpm install warnings
Installing dev dependencies prints a handful of npm warn deprecated lines
(rimraf, inflight, lodash.isequal, glob, uuid, fstream). These are
transitive dependencies of exceljs, which we pull in only as a
devDependency to verify our output: the round-trip test in
tests/xlsx/write-workbook.test.ts re-opens a generated workbook with ExcelJS
to confirm it loads without a repair prompt.
None of these ship in @alosha/xlsx — the published package has a single
runtime dependency, fflate. The warnings are ExcelJS's baggage, not ours;
in fact they're a tidy illustration of why this library exists. If ExcelJS is
not installed, that one round-trip test simply skips.
License
MIT © E.Y. Silva Navarrete
