XLSX Import & Export
Render any .xlsx, CSV, or TSV blob as a fully featured OGrid, edit and format it, and save it back out as a real .xlsx workbook. Multi-sheet workbooks get tabbed navigation, formulas evaluate live, cells show the workbook's own styles and number formats, and Excel-style cell references (A1, B2…) are on by default.
Two packages ship this:
| Package | When to use |
|---|---|
@alaarab/ogrid-react-xlsx | React apps with a bundler (Vite, Next.js, Webpack, etc.). |
@alaarab/ogrid-react-xlsx-browser | Static HTML pages, SharePoint Framework drops, or any no-bundler context. Self-contained ESM with local lazy chunks. |
Both expose the same component surface — XlsxWorkbookGrid, XlsxGrid, and an imperative mount() helper.
React (with a bundler)
npm i @alaarab/ogrid-react-xlsx
- Full workbook
- Single sheet
import { XlsxWorkbookGrid } from '@alaarab/ogrid-react-xlsx';
function Preview({ file }: { file: Blob }) {
return <XlsxWorkbookGrid blob={file} height={520} />;
}
import { XlsxGrid, workbookFromBlob } from '@alaarab/ogrid-react-xlsx';
import { useEffect, useState } from 'react';
import type ExcelJS from 'exceljs';
function SingleSheet({ file }: { file: Blob }) {
const [wb, setWb] = useState<ExcelJS.Workbook | null>(null);
useEffect(() => { workbookFromBlob(file).then(setWb); }, [file]);
if (!wb) return null;
return <XlsxGrid workbook={wb} sheetName="Summary" density="compact" />;
}
XlsxWorkbookGrid props
| Prop | Type | Default | Description |
|---|---|---|---|
blob | Blob | — | The raw .xlsx/CSV/TSV file. Parsed inside the component. Use this OR workbook. |
workbook | ExcelJS.Workbook | — | A pre-parsed workbook. Use this OR blob. |
streaming | boolean | true for Blobs ≥ 1 MiB without onDocument | Progressive value preview, progress and cancellation; false uses the eager formatted view. CSV/TSV use the existing loader. |
streamOptions | { workerFactory?, chunkSize?, maxSharedStringsBytes? } | 256 rows / 32 MiB shared strings | Override worker hosting or the streaming budgets. workerFactory: null uses the fallback. |
onLoadProgress | (percent: number) => void | — | Worksheet compressed bytes consumed, from 0 to 100. Metadata and shared-string parsing precede worksheet progress. |
onStreamedWorkbook | (workbook: StreamedXlsxWorkbook) => void | — | Completed preview, with toBlob() and loadDocument() for lazy editing. |
height | number | string | '100%' | Container height. |
initialSheet | string | first sheet | Which sheet to show on mount. |
density | 'compact' | 'normal' | 'comfortable' | 'compact' | Row height. |
onSheetChange | (name: string) => void | — | Fired when the user clicks a sheet tab. |
headerRow | 'auto' | 'header' | 'none' | 'auto' | Whether to promote row 1 to the header. 'auto' detects strings-only top rows; 'header' forces it; 'none' uses A/B/C letters. |
limits | { maxRows?, maxCols?, maxCells?, maxFileBytes?, maxUncompressedBytes? } | 1,048,576 rows / 1,000 cols / 5,100,000 cells; 50 MiB file / 200 MiB inflated ZIP | Per-sheet mapping caps and file parsing checks. A notice shows when mapping or CSV parsing is limited. |
onTruncated | (notice: XlsxTruncationNotice) => void | — | Reports the displayed sheet name, loaded row/column counts, full extent when known, and parseTruncated for CSV. |
editable | boolean | false | Allow editing values, formulas, rows and columns through the grid menus. Off, the grid is a read-only preview. |
circleInvalidData | boolean | false | Outline cells that fail their Excel validation rules. |
toolbar | boolean | editable | Show the formatting toolbar above the grid. |
exportFileName | string | — | Adds an Export .xlsx button to the toolbar that downloads the edited workbook under this name. |
onDocument | (doc: XlsxWorkbookDocument) => void | — | Receives the document after loading. Supplying it disables automatic streaming to preserve host-managed export; explicit streaming={true} defers delivery until Enable editing. |
XlsxGrid takes the same editable, circleInvalidData, toolbar and exportFileName props, plus an optional document to share one XlsxWorkbookDocument between grids.
Editing, formatting and saving
import { XlsxWorkbookGrid, type XlsxWorkbookDocument } from '@alaarab/ogrid-react-xlsx';
function Editor({ file }: { file: Blob }) {
const docRef = useRef<XlsxWorkbookDocument | null>(null);
const save = async () => {
const blob = await docRef.current?.toBlob(); // or docRef.current?.download('book.xlsx')
if (blob) await upload(blob);
};
return (
<>
<button onClick={save}>Save</button>
<XlsxWorkbookGrid blob={file} editable onDocument={(doc) => { docRef.current = doc; }} />
</>
);
}
With editable, cells take values and formulas (=SUM(B1:B3); typed numbers become numbers, as in Excel). Cell and column menus insert and delete rows or columns. The toolbar applies to the selected range: bold, italic, underline, strikethrough, fill color, font color, font family, font size (8–72), a borders menu (all, outside, inside, top, bottom, left, right or none, with line style and color), left/center/right alignment, a number format menu (General, Number, Currency, Percent, Date), and merge/unmerge. The cell context menu also has Freeze panes / Freeze top row / Freeze first column / Unfreeze panes. Edits, formatting and structure changes share one chronological workbook undo history (Ctrl+Z / Ctrl+Y or the toolbar buttons). Undo can revert a change on another sheet; this keeps cross-sheet references consistent. Edits made in one go, like a paste, undo as one step. Switching sheet tabs keeps each sheet's edits.
XlsxWorkbookDocument is the editable model behind the grid. Build one yourself (new XlsxWorkbookDocument(workbook, { headerRow })) to drive edits from code: setCellValues, applyStyle, mergeCells, unmergeCells, insertRows, deleteRows, insertColumns, deleteColumns, undo, redo, then toWorkbook() / toBlob() / download().
doc.insertRows('Orders', 0, 2); // two blank data rows below a promoted header
doc.deleteRows('Orders', [1, 3]); // noncontiguous data indexes, one undo step
doc.insertColumns('Orders', 2); // blank column before C
doc.deleteColumns('Orders', 2, 1);
Indexes are zero-based grid positions. Inserted rows and columns start blank, with default formatting. Existing cells, styles, notes, hyperlinks, merges, validation coverage, conditional-format ranges, heights, widths, hidden state and frozen boundaries move with the edit. Local and cross-sheet A1 references (absolute and relative), whole-row/column references and defined range names shift, including on unopened sheets. Deleted references become #REF!; partially deleted ranges shrink. A defined range name whose entire range is deleted is removed because ExcelJS cannot retain an error-valued name. Shared formulas expand into individual formulas. The input workbook stays unchanged.
Grid formulas count rows under the promoted header, so with a header row B1 in the grid is B2 in Excel. Export translates formulas back to sheet coordinates and adds the _xlfn. prefix Excel requires for newer functions such as CONCAT and XLOOKUP.
What round-trips
Export starts from a copy of the source workbook and writes back only what changed. Images round-trip through ExcelJS. For files loaded with blob or workbookFromBlob, chart and pivot parts are restored from the original ZIP after ExcelJS writes the edited cells.
| Feature | Shown in the grid | Editable | Saved on export |
|---|---|---|---|
| Values (numbers, text, dates, booleans) | Yes | Yes | Yes |
| Row and column insertion/deletion | Yes | Cell and column menus; document API | Yes, including shifted references and worksheet metadata |
Dynamic array formulas and A1# spill references | Computed spill values; child cells are read-only | Edit the anchor formula | Array refs and cached outputs preserved; refs shift with structural edits |
| Formulas, including cross-sheet references | Yes, evaluated live | Yes | Yes, with the latest result; Excel recalculates on open after edits |
| Formulas the engine can't evaluate (unknown functions, references into the promoted header row) | Cached result | Overwrite only | Yes, original formula unchanged |
| Font: bold, italic, underline, strikethrough, color, size, family | Yes | Bold, italic, underline, color, size and family | Yes |
| Solid fill | Yes | Yes | Yes |
| Pattern and gradient fills | Approximated by their main color | No | Yes |
| Borders | Yes (style, width, color) | Yes (all / outside / inside / edges, style and color) | Yes |
| Horizontal / vertical alignment, wrap text, indent | Yes | Left/center/right | Yes |
Number formats: decimals, thousands, currency, percent, dates and times, scientific, [Red] sections, conditions | Yes | General / Number / Currency / Percent / Date | Yes, any format string |
| Theme and indexed colors | Yes, resolved against the workbook theme | — | Yes |
| Other style properties (protection, text rotation, …) | No | No | Yes, kept when a cell's style is edited |
| Column widths | Yes | Yes (resize) | Yes |
| Hidden columns | Hidden | No | Yes |
| Row heights | Yes, scaled from sheet heights | Yes (resize) | Yes; shift with rows |
| Merged cells | Yes | Merge / unmerge | Yes; shift, expand or shrink with structure edits |
| Frozen panes | Frozen rows and columns shown | Freeze via the cell context menu | Yes; boundaries shift with structure edits |
| List data validation | Dropdown editor when one list rule covers every loaded row of a column | No | Yes, every validation kept |
| Other data validation (number, date, length, custom) | No | No | Yes |
| Every sheet, in order, with names and tab colors | Tabs with color | No | Yes |
| Cell notes | Yes | Yes | Yes; shift with their cells |
| Conditional formatting | Supported rules render in the grid | No | Yes; ranges and rule formulas shift |
| Defined range names | Used by the workbook; named formulas show cached results | No | Yes; ranges shift |
| Rich text, hyperlinks, print setup | Rich text and hyperlinks as plain text | Overwriting replaces with plain text | ExcelJS-supported content kept; cell hyperlinks shift |
| Anchored images (PNG, JPEG, GIF) | Yes, above the cells; follows scrolling and cell sizes | No | Yes |
| Charts | Title placeholder at the anchor | No | Original chart XML, drawings, relationships and dependent parts preserved |
| Pivot tables | Saved result cells | Cell values only; no pivot editor | Pivot definitions, cache definitions and records preserved; Excel refreshes on open |
| Header row (row 1) when promoted to column names | As column headers | No | Yes, unchanged |
Images, charts and pivot tables
Images sit over their anchored cells and follow column widths, saved row heights, sorting and scrolling, including virtual scrolling. Media whose anchor cells are hidden, filtered out, off the current page, or outside the loaded limits is hidden. Images and chart placeholders are display-only; select and edit the underlying cells as usual.
Charts show Chart: Sales by Region — opens in Excel rather than an interactive chart. On export, chart parts and their drawing relationships are restored with new relationship IDs where needed, alongside ExcelJS's image drawings. Pivot tables show their saved cells; their caches are marked refreshOnLoad so Excel rebuilds them from the edited source data or their preserved external connections. Pivot number formats and differential styles are merged into the exported workbook's style tables, and their IDs are remapped. Cached chart values may remain stale until Excel recalculates.
To preserve charts and pivots, load the original bytes through blob or workbookFromBlob, then save with document.toBlob(), document.download() or xlsxBlobFromWorkbook(await document.toWorkbook()). A workbook parsed directly with workbook.xlsx.load() has already lost the unsupported parts. Raw workbook.xlsx.writeBuffer() also bypasses preservation.
The fixture above is generated by packages/react-xlsx/src/__tests__/fixtures/mediaWorkbook.ts and contains both a mixed image/chart drawing and a chart-only sheet, plus a pivot table. Its edit/export path is checked by re-reading with ExcelJS, inspecting ZIP relationships and content types, and opening with LibreOffice headless.
Known gaps:
-
Image move, resize and delete controls, chart rendering, and pivot authoring are not implemented. Worksheet background images and absolute (non-cell) chart anchors are not displayed.
-
Images and chart placeholders retain their original worksheet anchor coordinates when rows or columns are inserted or deleted, including through
XlsxWorkbookDocument. Chart series, pivot locations and pivot source references also retain their original A1 ranges. Their parts survive structure edits and undo, but their anchors and references are not shifted. A changed sheet extent produces an export warning; equal-size structural changes do not. Adjust media and pivot ranges in Excel after structural edits. -
Preservation targets worksheet charts and pivots in
.xlsx; other unsupported ExcelJS features (such as slicers, chart sheets, macros and drawing shapes) are not restored. -
Rows render at their saved heights (scaled to the grid's row height), but rows without a saved height don't grow to fit wrapped text. See Wrap Text.
-
The toolbar reads the selection from the rendered cells. With row virtualization, a selection taller than the visible window only formats the rows on screen.
-
Sorting a column sorts formula cells by their formula text, not their result.
-
Text that starts with
=in the source file is treated as a formula. -
Sheets cut down by
limitssave the loaded part's edits; the rest of the sheet is kept as it was. -
Structural edits also move the unloaded part of a truncated sheet, but the grid remains subject to its load caps. Structured table references, table extents, 3D references and drawing/chart anchors are not structurally rewritten. Use Excel for structural edits in workbooks that depend on these features.
-
The eager path, editing, edited export and structural snapshots use ExcelJS's full in-memory workbook. Streaming preview avoids that model. Structural undo retains workbook snapshots and can be expensive on dense sheets.
-
Excel's locale short date (
m/d/yyyy, built-in format 14) displays asYYYY-MM-DD. Other number formats render in en-US style.
Untrusted files
Only populated cells are read, and each sheet is capped by limits. sheetToGridData(sheet, { maxRows, maxCols, maxCells }) applies the same caps and returns truncated: { rowCount, columnCount } (the full size) when it cut the sheet.
Large files
Blobs of at least 1 MiB without onDocument open as a progressive value preview by default. Use streaming to opt smaller files in. Rows become visible as chunks arrive, with Loading… 42% and Cancel. Changing the Blob or unmounting terminates the worker. Without Workers, or if construction is blocked by CSP, the same SAX reader runs in small tasks on the main thread. SSR renders the loading state; parsing begins on the client.
Preview shows text, numbers, dates, booleans and cached formula results. Formatting, merges, validations, notes, live recalculation and sorting become available after Enable editing when editable is set. This prepares the full ExcelJS document in the worker and transfers rows and pre-mapped data back in batches. onDocument then receives that document. Supplying this callback disables automatic streaming, so existing read-only consumers still receive a full document. Explicit streaming={true} opts into deferred delivery. Set streaming={false} when you need the complete formatted view immediately. Pre-parsed workbook and XlsxGrid retain their existing behavior.
An unedited streamed export returns the original Blob byte-for-byte, preserving every ZIP part, including media and features ExcelJS cannot interpret. After editing, export uses the existing document path, preserving styles, merges, validations, conditional formatting, notes, images, charts, pivots and dynamic-array metadata. Loading and editing a full document still require memory proportional to that workbook; edited serialization and structural operations retain ExcelJS's existing costs. Streaming preview does not promise constant memory for retained grid values.
The parser reads the ZIP directory and 8 KiB compressed slices, without retaining an inflated worksheet string or creating ExcelJS cells. The main thread acknowledges each chunk before delivery continues and supplies only the viewport to OGrid. Shared strings are retained for lookup, capped at 32 MiB of decoded UTF-16 text plus entry pointers by default; an oversized table is rejected. ZIP checks enforce both declared sizes and actual inflated bytes.
The default mapping cap remains 1,048,576 worksheet rows, 1,000 columns and 5,100,000 rectangular cells per sheet, allowing 100,000 × 50 plus a header. Input is capped at 50 MiB and total uncompressed ZIP bytes at 200 MiB. A far-away cell can hit the rectangle cap; dense styles or long strings can hit byte/string budgets. Lower limits for memory-constrained devices. Truncation limits the preview and editable mapped area; unedited export preserves the complete original file. Rows and columns outside the edited area retain their original values on edited export.
For non-React consumers:
import { streamWorkbook } from '@alaarab/ogrid-react-xlsx';
const controller = new AbortController();
const preview = await streamWorkbook(file, {
signal: controller.signal,
onProgress: (percent: number) => console.log(percent),
onChunk: async (chunk) => { /* append chunk.rows; awaited for backpressure */ },
});
const original = await preview.toBlob();
const doc = await preview.loadDocument(); // lazy full load in the worker
// doc.setCellValues(...); then preview.toBlob() includes those edits.
preview.sheets and chunk rows use zero-based worksheet coordinates, including row 1; header promotion applies when the document is mapped. chunk.complete marks a sheet's final extent. workerFactory supports custom CSP/hosting requirements; the normal package uses the literal new Worker(new URL('./xlsxWorker.js', import.meta.url), { type: 'module' }) pattern for Vite, webpack 5 and Next.js client components. Keep the emitted worker and lazy chunks when copying the browser package.
Measurements on the same Linux x64 laptop (Core i9-13900H, 32 GiB RAM), Chromium 153.0.8010.12, ExcelJS 4.4.0, 2026-10-08. Each row used a fresh browser process and identical input for both paths. Times start after downloading the fixture and importing the API, and include lazy preview/worker startup. First rows means DOM cells followed by an animation frame; total means the complete preview or full editable document. Peak RSS sums the browser process tree, sampled every 100 ms, including worker heaps and shared pages; it is not comparable to a single Node/Bun process RSS. These single runs under shared machine load are illustrative.
| Workbook (data rows × columns) | File | Full: first / total | Stream: first / total | Full / stream peak browser RSS |
|---|---|---|---|---|
| Numeric 10k × 20 | 1.30 MiB | 1.00 / 1.00 s | 0.50 / 1.25 s | 508 / 495 MiB |
| Numeric 100k × 50 | 14.06 MiB | 15.11 / 15.11 s | 1.14 / 22.63 s | 1,896 / 784 MiB |
| Styled 20k × 30 (font, fill, number format on every cell) | 4.29 MiB | 4.05 / 4.05 s | 0.56 / 2.77 s | 717 / 585 MiB |
Streaming favors early interaction and lower memory; total throughput can be slower, especially with dense numeric data. The dense full load's longest main-thread task was 8.47 s; the streamed run's was 0.26 s (including initial UI mounting). The prior Bun 1.4.0 dense baseline took 33.6 s to parse plus 3.37 s to map at 3,900 MiB RSS; the new parser-only run delivered its first chunk in 0.18 s, completed in 23.29 s and peaked at 405 MiB while discarding delivered rows. That parser-only memory figure excludes retained grid data.
Reproduce with the benchmark script; generate fixtures once, then run each browser measurement separately after a build:
bun packages/react-xlsx/scripts/benchmark-streaming.mjs --generate /tmp/ogrid-stream-fixtures
node packages/react-xlsx/scripts/benchmark-streaming.mjs --browser full /tmp/ogrid-stream-fixtures/100k50.xlsx
node packages/react-xlsx/scripts/benchmark-streaming.mjs --browser stream /tmp/ogrid-stream-fixtures/100k50.xlsx
@alaarab/ogrid-react-xlsx requires React 18 or 19.
Format support
Supported formats: .xlsx, .csv, .tsv (backed by ExcelJS).
Browser bundle (no bundler)
For SharePoint Framework, static HTML, or any page that can't (or won't) run a JS bundler, install @alaarab/ogrid-react-xlsx-browser. Its entry is dist/ogrid-xlsx.js, with React, ReactDOM, ExcelJS and all OGrid dependencies included. Optional UI, drag behavior and media live in sibling chunks loaded on demand; no package imports or bundler are needed.
npm i @alaarab/ogrid-react-xlsx-browser
Copy every .js and .css file from dist/ into the same vendor/ directory you serve statically:
The worker is a separate self-contained asset with no external imports.
vendor/
ogrid-xlsx.js
*.js # Keep the generated relative chunks alongside the entry
ogrid-xlsx.css
xlsxWorker.js
...other .js and .css chunks from dist/
Then drop this into any HTML page:
<link rel="stylesheet" href="/vendor/ogrid-xlsx.css" />
<div id="grid" style="height: 520px"></div>
<script type="module">
const { mount } = await import('/vendor/ogrid-xlsx.js');
const file = await fetch('/data/report.xlsx').then(r => r.blob());
const unmount = mount(document.getElementById('grid'), { blob: file });
// When you're done — React 19 does not auto-unmount on DOM removal:
// unmount();
</script>
Imperative mount()
mount(node: Element, opts: MountOptions): () => void
Returns an unmount function. Always call it before removing the host node — React 19 won't clean up event listeners or state if you just node.remove().
MountOptions accepts the same fields as XlsxWorkbookGrid props (blob / workbook, initialSheet, density, height, onSheetChange, headerRow).
When to pick this over the React package
| Use the React package when | Use the browser bundle when |
|---|---|
| You already have a Vite / Webpack / Next.js build. | You're shipping into a static page, SPFx web part, or CDN drop. |
| You want tree-shaking and a single dependency graph. | You don't have (and don't want) a JS bundler. |
| You're integrating into an existing React tree. | You want one <script type="module"> import. |
Exporting grid data
To save a workbook you imported, use the document's toBlob() (see above). To export any grid's rows as a new workbook, exportToXlsx mirrors exportToCsv's call shape — pass rows, lightweight column defs, a value accessor, and a filename:
import { exportToXlsx } from '@alaarab/ogrid-react-xlsx';
await exportToXlsx(
rows,
[
{ columnId: 'name', name: 'Name' },
{ columnId: 'salary', name: 'Salary' },
],
(item, columnId) => item[columnId],
'people.xlsx',
);
Values export as native Excel types: numbers, dates, and booleans round-trip without stringification. To emit live formulas (Excel recalculates them on open), pass the same {col, row, formula} array sheetToGridData produced on import:
await exportToXlsx(rows, columns, getValue, 'sheet.xlsx', {
sheetName: 'Data',
formulas: initialFormulas, // e.g. from the imported workbook
});
Promoting a header row is a lossy transformation for formulas that reference
that row. For example, importing LEN(A1) with row 1 promoted produces
LEN(#REF!); importing COUNTA(A1:A3) and exporting it again produces
COUNTA(A2:A3). The grid can show the original cached result, but Excel
recalculates the changed formula after export. Export cannot reconstruct the
removed references. Use headerRow: 'none' when mapping the source workbook
to preserve those references in the grid data, or retain the original workbook
when you need a lossless worksheet round trip. Exporting grid data always adds
a column-header row and shifts its local formula references accordingly.
For full control (multi-sheet assembly, styling), build the workbook yourself with workbookFromGridData(rows, columns, getValue, options) — it returns an ExcelJS.Workbook you can add sheets to before serializing with xlsxBlobFromWorkbook(wb).
Related
- Formulas — the engine that evaluates
=SUM(A1:A5)cells lifted out of the workbook - Cell References — A/B/C column headers and the name box, on by default for xlsx grids
- CSV Export — round-trip data back out of the grid
Data validation
Imported validations apply to their original cells and ranges: list, whole, decimal, date, time, text length, and custom formulas. Lists use per-cell dropdowns, including live range and defined-name sources. Input messages and stop, warning, and information alerts follow the workbook's settings.
With editable, select cells and use Data validation… in the context menu to edit rules through Settings, Input message, and Error alert tabs. Validation changes join the document's undo history and export as Excel validations; untouched and unloaded rules are preserved. See Data Validation for the model and enforcement behavior.