@extend-ai/react-xlsx
v0.24.4
Published
JavaScript and React viewers for XLSX workbooks
Readme
@extend-ai/react-xlsx
React components, hooks, and a vanilla JavaScript API for rendering .xlsx workbooks in the browser.
@extend-ai/react-xlsx gives you:
- A drop-in
XlsxViewerfor workbook previews - A
createXlsxViewerAPI for mounting the viewer from plain JavaScript - A provider/controller API for custom spreadsheet experiences
- Worksheet rendering with frozen panes, tables, merged cells, conditional formatting, sparklines, selection, resizing, copy/paste, and zoom
- Embedded worksheet images, shapes, form controls, charts, and chartsheet tabs
- Worksheet-backed pivot editing, refresh, PivotCharts, and XLSX import/export
- Worker-backed parsing and large-file guardrails
- Thumbnail helpers for building sheet strips, previews, and navigation UIs
- TypeScript types for viewer state, workbook metadata, charts, images, tables, and render hooks
Install
npm install @extend-ai/react-xlsxpnpm add @extend-ai/react-xlsxFor the React entry, install react and react-dom as well. They are optional peer dependencies and are not needed by the vanilla entry.
Upgrading from 0.21.x
getXlsxBytes()now returnsPromise<Uint8Array | null>andexportXlsx()returnsPromise<void>. Await these calls before consuming the bytes or handling export completion/errors.useWorkerdefaults totrue, with automatic main-thread fallback when workers are unavailable or fail. SetuseWorker={false}to disable workers for loading, charts, and export.- If you host the parser WASM yourself, deploy the
@extend-ai/react-xlsx/duke_sheets_wasm_bg.wasmasset from the same package version as the viewer. The patched runtime includes the pivot APIs. renderTableHeaderMenunow receives pivot headers as well as ordinary table headers. Checkmenu.pivotormenu.kind, or providerenderPivotTableHeaderMenuseparately.
Automatic Chart Loading
Chart rendering loads automatically when the viewer encounters charts in the active tab. Map geometry and WebGL surface rendering load separately when those chart types are needed. No extra imports or configuration are required.
The viewer starts loading chart modules while chart metadata is being hydrated. The grid stays usable while charts load. Use renderChartLoading to supply a custom component for chart metadata, chart rendering code, and map geometry loading. Its stage field is "metadata", "renderer", or "map", and its chart, rect, and defaultNode fields provide context. The component renders in the full chart rectangle and can contain ordinary HTML.
<XlsxViewer renderChartLoading={() => <LoadingSpinner />} />Surface charts use their SVG rendering while the WebGL module loads. Loaded modules are reused across tabs and workbooks.
Use a production bundler that preserves dynamic imports, and deploy all generated JavaScript chunks alongside the application. This reduces the initial browser download; all chart modules remain included in the installed package.
Spreadsheet Fonts
Workbook loading prepares shared fallbacks for Calibri, Arial, Times New Roman, Courier New, Aptos and Aptos Narrow before measuring text. Installed originals remain preferred. The loader discovers font families from bounded style, theme, drawing, chart and shared-string XML parts; unusually large parts and fonts declared only in inline worksheet text may require host-provided fonts.
Each family is a separate lazy JavaScript chunk with embedded WOFF2 data. Deploy the generated chunks alongside the viewer; no font CDN is required. The package includes dist/Office-Font-Licenses.txt.
WebAssembly Asset
Workbook parsing and calculation run through the @dukelib/sheets-wasm WebAssembly module. The module loads lazily, on the first workbook parse.
Most apps can use the default loader. If your bundler or deployment needs to host the WASM binary somewhere explicit, configure it before the first parse:
import { setWasmSource } from "@extend-ai/react-xlsx";
setWasmSource("https://cdn.example.com/duke_sheets_wasm_bg.wasm");
// or pass a URL, Request, Response, ArrayBuffer/TypedArray, or compiled WebAssembly.ModuleThe Duke WASM binary is also exposed as a package subpath:
import wasmUrl from "@extend-ai/react-xlsx/duke_sheets_wasm_bg.wasm?url";
import { setWasmSource } from "@extend-ai/react-xlsx";
setWasmSource(wasmUrl);Next.js Turbopack
Turbopack may try to treat .wasm?url imports as WebAssembly modules during static analysis. For Turbopack apps, use a plain public or CDN URL instead of importing the WASM file with ?url.
Copy the WASM file into your app's public/ directory:
cp node_modules/@extend-ai/react-xlsx/dist/duke_sheets_wasm_bg.wasm public/duke_sheets_wasm_bg.wasmThen configure the source from a shared client module before any workbook is parsed:
// app/xlsx-wasm.ts
"use client";
import { setWasmSource } from "@extend-ai/react-xlsx";
setWasmSource("/duke_sheets_wasm_bg.wasm");Import that setup module before rendering any XLSX viewer, provider, or controller:
// app/workbook-preview.tsx
"use client";
import "./xlsx-wasm";
import { XlsxViewer } from "@extend-ai/react-xlsx";
export function WorkbookPreview({ file }: { file: ArrayBuffer }) {
return <XlsxViewer file={file} height={600} />;
}If several routes use the viewer, import the same setup module from a shared client boundary such as app/providers.tsx. Calling setWasmSource() more than once with the same source is fine before initialization, but the source must not change after the first parse because the WASM module is initialized once per JavaScript context.
Configured string, URL, Request, Response, bytes, and WebAssembly.Module sources all support worker parsing. Requests retain their fetch options. The asynchronously compiled module is shared with workers so subsequent loads can reuse it. Self-hosted WASM must come from the same package build as the JavaScript bindings.
In Vite development, exclude the vanilla entry from dependency optimization so Vite can resolve the worker asset. Production builds do not need this setting:
import { defineConfig } from "vite";
export default defineConfig({
optimizeDeps: { exclude: ["@extend-ai/react-xlsx/vanilla"] }
});For the React entry, exclude the shared entries and let Vite optimize React separately:
import { defineConfig } from "vite";
export default defineConfig({
optimizeDeps: {
exclude: ["@extend-ai/react-xlsx", "@extend-ai/react-xlsx/vanilla", "@extend-ai/react-xlsx/internal"],
include: ["react", "react-dom", "react-dom/client", "react/jsx-runtime"]
}
});You can also call initWasm() (optionally with a source) ahead of time to warm the module before the first workbook is opened. Vanilla applications can import these functions from @extend-ai/react-xlsx/vanilla.
Main Entry Points
The package provides a vanilla JavaScript entry point and three levels of React API:
@extend-ai/react-xlsx/vanillaexportscreateXlsxViewer, theXlsxViewerinstance class, and utilities for JavaScript applications.
@extend-ai/react-xlsx exports:
XlsxViewerA ready-to-render workbook viewer with built-in toolbar, sheet tabs, grid rendering, charts, images, and selection state.XlsxViewerProvider+ viewer hooks Shared controller context for custom toolbars, side panels, thumbnail strips, or other UI around the workbook.useXlsxViewerControllerA lower-level controller hook for fully controlled integrations.
Quick Start
Vanilla JavaScript
Use the vanilla entry point to mount the viewer in an existing DOM element. The viewer uses a bundled Preact renderer and does not require React or JSX. The React component wraps the same viewer implementation. The instance creates a div in the regular DOM, so application styles and focus behavior continue to apply.
The examples below use a browser bundler such as Vite to resolve the package import. For Vite development, use the worker configuration above.
Open a workbook from a URL
<div id="viewer"></div>
<script type="module" src="/main.js"></script>import { createXlsxViewer } from "@extend-ai/react-xlsx/vanilla";
const viewer = createXlsxViewer(document.getElementById("viewer"), {
src: "/workbook.xlsx",
height: 600,
readOnly: true,
});The URL must be accessible to the browser. A workbook on another origin needs the appropriate CORS headers. Omit readOnly to allow editing.
You can also construct an instance directly:
import { XlsxViewer } from "@extend-ai/react-xlsx/vanilla";
const viewer = new XlsxViewer(document.getElementById("viewer"), {
src: "/workbook.xlsx",
height: 600,
});Open a local workbook
The file option accepts workbook bytes as an ArrayBuffer. This standalone example starts with an empty viewer and loads the file selected by the user:
<input id="workbook" type="file" accept=".xlsx,.xlsm,.xls" />
<div id="viewer"></div>
<script type="module" src="/main.js"></script>import { createXlsxViewer } from "@extend-ai/react-xlsx/vanilla";
const viewer = createXlsxViewer(document.getElementById("viewer"), {
height: 600,
emptyState: "Choose a workbook to preview.",
});
document.getElementById("workbook").addEventListener("change", async (event) => {
const file = event.currentTarget.files?.[0];
if (!file) return;
viewer.setOptions({ file: await file.arrayBuffer(), fileName: file.name });
});Read state and control the viewer
Subscribe to loading, errors, sheet changes, selection, and other controller updates:
const unsubscribe = viewer.subscribe((controller) => {
if (controller.error) {
console.error(controller.error);
} else if (controller.isLoading) {
console.log("Loading workbook…");
} else if (controller.sheets.length > 0) {
console.log(controller.activeSheet?.name, controller.selectedRangeAddress);
}
});Read the latest controller when invoking a command. These commands should run after the workbook has loaded:
const controller = viewer.getController();
if (controller && !controller.isLoading && controller.sheets.length > 0) {
controller.highlightRanges("A1:C5");
if (!controller.readOnly) controller.setCellValue({ row: 0, col: 0 }, "42");
if (controller.canExport) await controller.exportXlsx();
}setCellValue requires an editable workbook. await exportXlsx() exports in the parser worker and downloads the current workbook in the browser, and await getXlsxBytes() resolves to the same bytes as a Uint8Array (or null before a workbook loads) for saving elsewhere, such as uploading to your own storage.
Change options or load another workbook with setOptions:
viewer.setOptions({ isDark: true, readOnly: true });
viewer.setOptions({ src: "/another-workbook.xlsx", fileName: undefined });Supplying file clears the previous src, and supplying src clears the previous file. To release the viewer when it is no longer needed:
unsubscribe();
viewer.destroy();createXlsxViewer returns an object with these methods:
getController()returns the latestXlsxViewerController, ornullwhen no controller is available or after destruction. Read it again when invoking commands so you have the current state and methods.subscribe(listener)reports controller updates, including loading, errors, sheets, selection, zoom, edits, and the existing controller commands. If a controller is already available, the listener is called immediately. Updates can be coalesced. The return value unsubscribes the listener.setOptions(options)merges new options into the current ones. Supplyingfileclearssrc, and supplyingsrcclearsfile.fileaccepts anArrayBuffer; convert a browserFilewithawait file.arrayBuffer().reload()discards the current viewer state and reloads the current source.destroy()unmounts the viewer, releases its resources, and removes listeners. It is safe to call more than once.
subscribe also exposes isLoadDeferred and continueDeferredLoad() for deferred workbooks.
XlsxVanillaViewerOptions supports the non-React viewer options, including getCellStyle, form-control events, themes, worker settings, and highlighting. toolbar, loading/empty/error states, and the renderActiveCellOverlay, renderCellEditorOverlay, renderSelectionPopover, renderChartLoading, renderContextMenu, renderHiddenRangeMarker, renderFormControl, and renderImage callbacks accept text or DOM nodes. Their vanilla callback props omit React's defaultNode. React-specific custom scroller, image-selection, and table-header render callbacks are not available through this entry point.
The vanilla entry also exports setWasmSource, initWasm, parseXlsxRange, and workbook types. The same WASM, worker, font, and chart assets need to be served as in the React integration.
Basic viewer
Use XlsxViewer when you want the smallest integration surface.
import * as React from "react";
import { XlsxViewer } from "@extend-ai/react-xlsx";
export function WorkbookPreview() {
const [file, setFile] = React.useState<ArrayBuffer | undefined>();
const [fileName, setFileName] = React.useState<string | undefined>();
return (
<div style={{ display: "grid", gap: 12 }}>
<input
type="file"
accept=".xlsx,.xlsm,.xls"
onChange={async (event) => {
const nextFile = event.target.files?.[0];
setFile(nextFile ? await nextFile.arrayBuffer() : undefined);
setFileName(nextFile?.name);
}}
/>
<XlsxViewer
file={file}
fileName={fileName}
height={600}
emptyState="Choose a workbook to preview."
/>
</div>
);
}You can also load a remote workbook with src:
import { XlsxViewer } from "@extend-ai/react-xlsx";
export function RemoteWorkbookPreview() {
return <XlsxViewer src="/reports/quarterly-model.xlsx" height="70vh" />;
}Provider and hooks
Use XlsxViewerProvider when custom UI needs access to the active workbook, selection, zoom, charts, images, tables, or editing commands.
import {
DefaultXlsxToolbar,
XlsxViewer,
XlsxViewerProvider,
useXlsxViewerSelection,
useXlsxViewerZoom,
} from "@extend-ai/react-xlsx";
function WorkbookStatus() {
const { activeCellAddress, selectedRangeAddress } = useXlsxViewerSelection();
const { zoomScale, zoomIn, zoomOut, canZoomIn, canZoomOut } = useXlsxViewerZoom();
return (
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
<span>{selectedRangeAddress ?? activeCellAddress ?? "No selection"}</span>
<button type="button" onClick={zoomOut} disabled={!canZoomOut}>
-
</button>
<span>{zoomScale}%</span>
<button type="button" onClick={zoomIn} disabled={!canZoomIn}>
+
</button>
</div>
);
}
export function WorkbookWorkspace({ file }: { file: ArrayBuffer }) {
return (
<XlsxViewerProvider file={file} fileName="model.xlsx">
<DefaultXlsxToolbar />
<WorkbookStatus />
<XlsxViewer height="70vh" showDefaultToolbar={false} />
</XlsxViewerProvider>
);
}Controlled controller
Use useXlsxViewerController when you want to own the controller instance and pass it into several components.
import {
XlsxViewer,
useXlsxViewerController,
} from "@extend-ai/react-xlsx";
export function ControlledWorkbook({ file }: { file: ArrayBuffer }) {
const controller = useXlsxViewerController({
file,
fileName: "forecast.xlsx",
readOnlyAboveBytes: 10 * 1024 * 1024,
});
return (
<div style={{ display: "grid", gap: 12 }}>
<button type="button" onClick={controller.exportXlsx} disabled={!controller.canExport}>
Export XLSX
</button>
<XlsxViewer controller={controller} height={640} />
</div>
);
}Useful Hooks
These hooks work inside XlsxViewer or XlsxViewerProvider context.
useXlsxViewer()for full controller accessuseXlsxViewerSelection()for active cell and range state. ⌘-click (Ctrl-click on Windows) adds or removes row and column headers.selectionRangescontains all selected areas in selection order, andselectionis the active area.useXlsxViewerLayout()for row and column visibility and freeze panesuseXlsxViewerZoom()for zoom controls and limitsuseXlsxViewerEditing()for editing, persisted style writes, formulas, undo/redo, fill, merge, clipboard, and export actionsuseXlsxViewerTables()for table metadata and table sortinguseXlsxViewerPivots()for pivot metadata, mutations, charts, drill-through, and field-list visibilityuseXlsxPivotTableEditor(options?)for a shared pivot draft and custom field-pane controlsuseXlsxViewerImages()for embedded image and chart selection, movement, and resizinguseXlsxViewerCharts()for chart, chart element, formula, and chartsheet stateuseXlsxViewerThumbnails(options)for painting worksheet thumbnails into your own canvases
Pivot Tables
Worksheet-backed pivot tables are available through useXlsxViewerPivots() and the viewer controller. Create and edit reports with upsertPivotTable(), read their metadata from pivotTables, and refresh source data with refreshPivotTable() or refreshAllPivotTables(). Pivot changes, detail worksheets, and linked PivotCharts participate in undo/redo and XLSX export. Report layout and filter changes use the saved cache until an explicit refresh.
Create, edit, refresh, and export
Sources can use a worksheet range, table, or supported static name. The source must have unique, nonempty column headers. Field indexes are zero-based source column indexes; worksheet cell addresses passed as objects also use zero-based rows and columns. The destination worksheet must already exist.
import type { XlsxViewerController } from "@extend-ai/react-xlsx";
async function createSummary(controller: XlsxViewerController) {
const pivot = controller.upsertPivotTable({
name: "Summary",
source: { sheet: "Data", range: "A1:C100" },
target: { sheet: "Report", cell: "A3" },
rows: [{ field: 0, sort: "ascending", subtotals: true, collapsed: [] }],
values: [{ field: 2, name: "Total", aggregation: "sum", showAs: "normal" }],
layout: "compact",
rowGrandTotals: true,
columnGrandTotals: true,
});
controller.upsertPivotTable({ ...pivot, layout: "tabular", repeatLabels: true });
controller.refreshPivotTable(pivot.id);
return await controller.getXlsxBytes();
}Pass an existing id to update a report. Source edits do not silently refresh pivots. refreshOnLoad opts into refresh when a workbook opens; failures retain saved results and appear in refreshError. Invalid configurations, overlapping reports, occupied destinations, protected sheets, and unsupported features reject mutations without replacing the original workbook. Direct edits to pivot results, paste, fill, merge, and ordinary table sorting are blocked; source data and cell formatting remain editable.
| Controller / useXlsxViewerPivots() member | Purpose |
| --- | --- |
| pivotTables | All pivot definitions, fields, members, headers, toggles, charts, output ranges, and unsupported-feature reasons. |
| getPivotSourceFields(source) | Inspect source fields and typed member keys. |
| getPivotTableAtCell(cell, sheetName?) | Find the report containing a cell. |
| upsertPivotTable(input) | Create or update a report; returns its metadata. |
| refreshPivotTable(id) / refreshAllPivotTables() | Rebuild caches and results from source data. Refresh-all is one undoable transaction. |
| removePivotTable(id) | Remove a report and detach its PivotCharts. |
| pivotDrillDown(id, row, col) | Read source records behind a result cell. |
| showPivotDetails(id, row, col) | Create a details worksheet and return its name. |
| togglePivotGroup(id, toggle) | Expand or collapse a row/column group from pivot.toggles. |
| createPivotChart(id, options?) | Create a linked chart; refresh keeps its data synchronized. |
| pivotFieldListVisible / setPivotFieldListVisible(visible) | Share visibility between default panes, custom panes, and the context menu. |
Supported settings include compact/outline/tabular layouts, repeated labels, row/column grand totals, subtotal position and functions, multiple values on rows or columns, report filters, sorting by label or value, member/label/value/top filters, numeric/date/manual grouping, calculated fields/items, number formats, formatting preservation, and Show Values As calculations. Aggregates include sum, count, count numbers, average, min/max, product, variance, and standard deviation. Filter and base-item keys come from member metadata; captions are not interchangeable with those keys. Date hierarchy levels can share a field index and are distinguished by their grouping unit.
Default and custom field panes
The built-in pane is disabled by default. Enable it with showPivotTableControls={true}. Use renderPivotTableControls to replace its content, or keep it disabled and render a separate pane using useXlsxPivotTableEditor() inside XlsxViewerProvider. Pass the same editor to pivotTableEditor so the toolbar, pane, and viewer share one draft.
import {
DefaultXlsxPivotTableFieldList,
useXlsxPivotTableEditor,
XlsxViewer,
} from "@extend-ai/react-xlsx";
function PivotWorkspace() {
const editor = useXlsxPivotTableEditor();
return (
<>
<button type="button" disabled={editor.readOnly} onClick={editor.create}>
Insert PivotTable
</button>
<XlsxViewer pivotTableEditor={editor} showPivotTableControls={false} />
{editor.open && (
<aside aria-label="PivotTable fields">
<button type="button" onClick={() => editor.setOpen(false)}>Hide field list</button>
<DefaultXlsxPivotTableFieldList editor={editor} />
</aside>
)}
</>
);
}Replace DefaultXlsxPivotTableFieldList with your own controls for complete control over the appearance. The editor provides draft, dirty, stale, sourceNeedsLoad, readOnly, error, and status; edit(updater), select(id), create(), apply(), reset(), remove(), refresh(all?), and readFields(); field placement through addField, removeField, and moveField; and details, detailContext, showDetails, and clearDetails. run(action) captures a custom synchronous action's error in the editor. viewer exposes the full controller for chart creation, export, and other actions. Draft changes become workbook mutations only when applied.
Editor options are autoSelect (defaults to true), enabled (defaults to true), and initialOpen (omit to retain automatic opening). Selecting a pivot opens the field list automatically. Clicking outside hides it temporarily; returning restores it. Explicitly closing it keeps it closed until Show Field List is chosen again. initialOpen: false opts out of automatic opening on workbook load. This visibility preference persists for the controller's lifetime and is shared with the checked Show/Hide Field List context-menu action, even when the built-in pane is disabled.
| Viewer prop | Customization |
| --- | --- |
| showPivotTableControls | Enable the built-in pane; defaults to false. |
| pivotTableEditor | Share a React editor between the viewer and external controls. |
| renderPivotTableControls | Render from { editor, controller, isDark, defaultNode }. |
| renderTableHeaderMenu | Customize both ordinary table and pivot header triggers/popovers. |
| renderPivotTableHeaderMenu | Override only pivot header triggers/popovers. |
| pivotTableHighlightColor | Override the pivot field-guide color. |
DefaultXlsxPivotTableFieldList also accepts className, style, and isDark. The playground demonstrates a separate resizable COSS field pane, ribbon controls, visual filters, and header popovers built from these APIs.
Header menus, visibility, and selection
The shared header callback receives kind: "pivot" and pivot: XlsxPivotTableHeaderMenuRenderProps for pivot headers. The dedicated callback receives that pivot context directly. It includes the report, header, selected field, members, filters, sort state, readOnly, error, and controlled isOpen/setOpen/close actions. Use setField(depth) for multiple fields on the same header; sortBy(direction, measure?), setMembers(keys), setFilter(filter), and clearFilters() control sorting and filtering. setMembers(null) removes the member filter.
Forward triggerProps, including its ref, events, and positioning style, to the trigger. Forward popupProps, including its ref and events, to the popup. Use an anchored popover library or the trigger's client rectangle for positioning; place nested popup portals within the popup element so outside-click handling preserves them. defaultNode retains the default UI. Cell-attached controls follow scrolling and zoom and clip at frozen-pane boundaries. Pivot popovers close when their trigger leaves the visible pane; custom ordinary-table popovers should hide when their own anchor is clipped.
pivotFieldListVisible controls the field guides shown for the active report. They outline its row, column, and data regions while preserving the active-cell border. Header menus remain available when the field list is hidden. Custom context menus receive togglePivotFieldList with the current checked state and can invoke it through runAction.
Types and vanilla JavaScript
The React and vanilla entries export the pivot model and operation types: XlsxViewerPivots, XlsxPivotTable, XlsxPivotTableInput, source/target/field/member types, axis/value/filter/grouping/calculated-item types, aggregation and Show Values As unions, chart input/metadata/type unions, drill-down results, and header/toggle metadata. Editor types include XlsxPivotTableEditor, XlsxPivotTableEditorOptions, XlsxPivotFieldArea, and XlsxPivotTableControlsRenderProps; header customization uses XlsxPivotTableHeaderMenuRenderProps. The React entry also exports DefaultXlsxPivotTableFieldListProps.
Vanilla viewers access the same pivot methods through viewer.getController(). showPivotTableControls, renderPivotTableControls, renderPivotTableHeaderMenu, and pivotTableHighlightColor are available in vanilla options. Render callbacks return DOM content; their contexts omit the React defaultNode. React hooks and the React default field-list component belong to the React entry.
Compatibility
This targets worksheet-backed XLSX pivots. Data Model/OLAP/external connections and unsupported native slicer/timeline dependencies are preserved without editing and reported in unsupportedFeatures. Visual member/date filters edit pivot filters; they do not create standalone Excel slicer/timeline objects. Pivot styles approximate Excel palettes, and exact Excel visual parity is not established. Refresh dependent reports in source order; refresh-all does not automatically sort dependency chains.
Exports contain native pivot definitions, cache definitions/records, relationships, and PivotChart associations. See pivot table APIs and compatibility for calculation limits and the detailed compatibility boundary.
Worksheet Layout
useXlsxViewerLayout() and the viewer controller expose the same commands for the active worksheet. In editing mode, layout changes participate in undo and redo and persist in XLSX exports.
In read-only mode, set allowFreezeInReadOnly to allow freezing and unfreezing or allowHideInReadOnly to allow hiding and unhiding rows and columns. Both options default to false and also apply when readOnlyAboveBytes activates read-only mode. Set them on the controller when supplying your own. Each worksheet keeps its view until the workbook is reloaded. Exports and edit history retain the workbook layout.
| Command | Default target | Explicit target |
| --- | --- | --- |
| hideRows() / unhideRows() | Rows covered by the current selection, including separate areas | One zero-based row index or two inclusive indices, as in hideRows(2, 4) |
| hideColumns() / unhideColumns() | Columns covered by the current selection, including separate areas | One zero-based column index or two inclusive indices, as in unhideColumns(1) |
| freezePanes() | Rows above the selected row header, columns to the left of the selected column header, or both axes at the active cell | A zero-based cell address. freezePanes({ row: 2, col: 1 }) keeps rows 1–2 and column A visible |
| unfreezePanes() | The active worksheet | — |
Read canChangeVisibility and canChangeFreezePanes to enable layout menus. Use canFreezePanes to enable a freeze command for the current selection and frozenPanes for the current row and column counts, or null when unfrozen. To unhide a block from the grid, select headers on both sides and choose Unhide. For hidden leading rows or columns, select the first visible header.
Hidden row and column markers
The row and column headers mark each contiguous hidden range with a thick line in the selection border color. Click the line or right-click it and choose Unhide to reveal that range. In read-only mode, allowHideInReadOnly enables unhiding for the current session. Otherwise, the line is a visual indicator.
Use renderHiddenRangeMarker to replace the line. It receives the axis ("row" or "column"), inclusive zero-based start and end, a localized label, readOnly, canUnhide, and an unhide() action for that range. React also supplies defaultNode. Return null to omit a marker. Vanilla JavaScript accepts the same option and can return a DOM node or text.
import type { XlsxHiddenRangeMarkerRenderProps } from "@extend-ai/react-xlsx";
function renderMarker({ axis, label, canUnhide, unhide }: XlsxHiddenRangeMarkerRenderProps) {
const icon = axis === "row" ? "↕" : "↔";
return canUnhide
? <button type="button" aria-label={label} onClick={unhide}>{icon}</button>
: <span role="img" aria-label={label}>{icon}</span>;
}
<XlsxViewer src={url} renderHiddenRangeMarker={renderMarker} />Both grid modes mount markers alongside virtualized headers. Keep the renderer reference stable to reuse its content while scrolling or changing the selection.
Merging Cells
The controller and useXlsxViewerEditing() expose mergeSelection(mode?) and unmergeSelection(). The merge modes are:
| Mode | Behavior |
| --- | --- |
| "cells" (default) | Merge the entire selection and preserve the anchor's alignment. |
| "center" | Merge the entire selection and persist horizontal center alignment. |
| "across" | Merge each selected row separately, preserving each row's anchor alignment. |
The playground Merge menu and the editable viewer's context menu expose all three modes. Merge and alignment changes participate in undo/redo and persist in XLSX exports. Unmerge works when selecting any cell within a merged range.
General alignment follows the underlying value type: numbers align right, text aligns left, and booleans and errors align center. Explicit horizontal and vertical alignment is preserved for both merged and ordinary cells.
Form Control Editing
When readOnly={false}, Duke-backed checkboxes, option buttons, dropdowns, list boxes, scrollbars, and spinners are interactive. Changes update linked cells immediately, participate in undo/redo, and are written by exportXlsx() / download().
Buttons do not execute Excel macros. Provide onFormControlAction to handle a button activation in your application. Labels and group boxes are display-only.
<XlsxViewer
file={file}
onFormControlAction={({ control }) => {
console.log("Activated", control.name);
}}
onFormControlChange={({ control, previousControl }) => {
console.log(previousControl.state, "->", control.state);
}}
/>The controller also exposes addFormControl(input, sheetIndex?), updateFormControl(controlIndex, patch, sheetIndex?), removeFormControl(controlIndex, sheetIndex?), and getFormControlItems(controlIndex, sheetIndex?). XlsxFormControlInput uses the same XlsxImageAnchor union as images and charts, with an optional editAs value for two-cell anchors. Captions accept either a string or rich text runs:
const controlIndex = controller.addFormControl({
anchor: {
kind: "two-cell",
from: { col: 1, row: 1, colOffsetEmu: 0, rowOffsetEmu: 0 },
to: { col: 3, row: 2, colOffsetEmu: 0, rowOffsetEmu: 0 }
},
editAs: "twoCell",
kind: {
kind: "checkbox",
caption: {
runs: [{ text: "Include forecast", font: { bold: true, name: "Aptos", size: 10 } }]
},
state: "checked"
}
});Migrating To 0.15
XlsxFormControlAnchorwas removed. Pass anXlsxImageAnchortoXlsxFormControlInput.anchorinstead.- Read controls now expose
captionasXlsxFormControlCaption; uselabelwhen you only need flattened display text. - Mutation captions accept either a plain string or
XlsxFormControlCaptionrich text runs. firstInGroupis read-only. Duke recomputes option-button grouping when controls are written.
Chart Selection And Formulas
Chart interactions follow Excel's selection progression: clicking a chart selects the chart frame, clicking a plotted item or legend entry again selects the series, and clicking an item in an already-selected series selects that point. selectedChartElement exposes the current chart, series, legend entry, or point selection through the controller and useXlsxViewerCharts().
When a series, legend entry, or point is selected, selectedFormula returns an Excel-style =SERIES(...) formula and selectedFormulaTarget is { kind: "chartSeries", chartId, seriesId, seriesIndex }. Use setSelectedFormula(...) for a formula bar that edits either the active cell formula or the selected chart series formula. Use getChartSeriesFormula(chartId, seriesIndex) and setChartSeriesFormula(chartId, seriesIndex, formula) when you need direct chart-series formula control.
Thumbnail Hook
useXlsxViewerThumbnails returns paint functions for each worksheet so you can build your own sheet strip or navigation UI.
import * as React from "react";
import {
XlsxViewerProvider,
useXlsxViewerThumbnails,
type XlsxSheetThumbnail,
} from "@extend-ai/react-xlsx";
function SheetThumbnail({ thumbnail }: { thumbnail: XlsxSheetThumbnail }) {
const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
React.useEffect(() => {
thumbnail.paint(canvasRef.current);
}, [thumbnail]);
return (
<canvas
ref={canvasRef}
width={thumbnail.width}
height={thumbnail.height}
style={{ width: thumbnail.width, height: thumbnail.height }}
/>
);
}
function SheetThumbnailStrip() {
const { thumbnails } = useXlsxViewerThumbnails({
includeHeaders: true,
resolution: { maxWidth: 180, maxHeight: 120 },
});
return (
<div style={{ display: "flex", gap: 12, overflowX: "auto" }}>
{thumbnails.map((thumbnail) => (
<SheetThumbnail
key={thumbnail.workbookSheetIndex}
thumbnail={thumbnail}
/>
))}
</div>
);
}
export function ThumbnailExample({ file }: { file: ArrayBuffer }) {
return (
<XlsxViewerProvider file={file}>
<SheetThumbnailStrip />
</XlsxViewerProvider>
);
}Notes:
resolutionaccepts either a single max dimension or{ maxWidth, maxHeight }.- Thumbnails preserve worksheet aspect ratio and paint into your supplied
<canvas>. - The current implementation renders a bounded top-left worksheet preview, including loaded embedded worksheet images, shapes, and form controls, but does not include charts.
Range Highlighting
Pass an A1 reference or an array of references to highlightedRanges to draw blue bounding boxes with a thin border matching the selection outline and a subtle fill. The highlights are separate from the current selection and do not change workbook formatting. It works in both canvas and DOM rendering, including frozen panes, hidden rows/columns, merged cells, and zoom.
<XlsxViewer
file={file}
highlightedRanges={["'Sheet 1'!$B$3:$E$8", "'Sheet 1'!G3:J8", "'Sheet 2'!B10:D14"]}
autoScrollToHighlightedRanges={true}
highlightClassName="my-range-highlight"
/>autoScrollToHighlightedRanges defaults to true: a new set of ranges reveals the first range and switches to its worksheet. Other ranges remain highlighted on their respective sheets. Set it to false to leave both the current scroll position and active sheet unchanged. Navigation happens once per set of ranges or auto-scroll option change, so manual scrolling remains free afterward. A range larger than the viewport reveals its top-left portion; whole-row and whole-column references scroll only the relevant axis.
Set highlightedRanges={null} or highlightedRanges={[]} to clear all highlights. Omit the prop to manage highlighting through the controller instead. If any prop reference is invalid or unresolved, the previous highlights are cleared. Equivalent arrays do not repeat navigation on parent re-renders. An unqualified reference is bound to the active worksheet when applied, and stays on that worksheet when the user switches tabs.
Controller API
The same API is available through useXlsxViewer() and useXlsxViewerController():
const accepted = controller.highlightRanges(["B3:E8", "G3:J8"], { autoScroll: false });
controller.highlightRanges("'Sheet 1'!A40:D48");
controller.highlightRanges("B3:E8", { sheetIndex: 1 });
controller.clearHighlightedRanges();highlightRanges(references, options?) accepts a string or a readonly array of strings and returns true when every reference resolves to a loaded, visible worksheet. It returns false for invalid references, unavailable worksheets, or a workbook that is still loading, leaving all current highlights and navigation unchanged. Validation is atomic; a partially valid array is never applied. autoScroll defaults to true; sheetIndex is a zero-based index into controller.sheets and applies only to unqualified references. Each successful call replaces all previous highlights; an empty array clears them. Calling again can reveal the same first range again. controller.highlightedRanges is an array of parsed references with their resolved sheet names and workbook sheet indexes. Only its first entry can have autoScroll: true. Loading another workbook clears the array.
CSS Customization
Style .react-xlsx-range-highlight globally, or use highlightClassName for a scoped override. Appearance is CSS in both renderers, so ordinary CSS properties work without !important:
.my-range-highlight {
border: 1px solid #0284c7;
background: rgb(2 132 199 / 10%);
border-radius: 3px;
}The defaults also accept inherited --xlsx-highlight-border, --xlsx-highlight-fill, and --xlsx-highlight-radius custom properties on the viewer or any ancestor. Position and dimensions are managed by the viewer; the overlay ignores pointer events. Use [data-xlsx-range-highlight="1"] to style a particular range by its zero-based index in the input array. A range crossing frozen panes may have several clipped overlay elements, each carrying the same class and index.
Parsing References
parseXlsxRange(reference) validates a reference without loading a workbook. It returns { kind, range: { start, end }, sheetName } with normalized, zero-based coordinates, or null for invalid input. kind is "cells", "rows", or "columns"; sheetName is null for an unqualified reference.
Supported references include single cells (A1), rectangles (B2:E8), absolute or mixed references ($B2:E$8), entire rows (2:8), entire columns (B:E), and optional worksheet prefixes. Sheet names with spaces or punctuation must be single-quoted; embedded apostrophes are doubled ('Owner''s Data'!A1). Letter case, reversed endpoints, surrounding whitespace, and an optional leading = are accepted. Coordinates are checked against Excel's worksheet limits.
Each string must contain one rectangular A1 reference, not named ranges, structured table references, unions, R1C1 notation, external workbooks, or references spanning multiple worksheets. Whole-row/column highlights cover the displayed grid and extend as it grows.
Examples
See @extend-ai/react-xlsx in action in these live Extend UI examples. Click a screenshot to open the demo and integration docs.
XLSX Viewer
Explore workbook navigation, sheet tabs, zoom, and charts.
XLSX Editor
Try the experimental editor with cell formatting, formulas, undo/redo, and export.
Context Menus
Right-click a chart, image, worksheet cell, row header, column header, or the top-left corner to open the context menu. Right-clicking inside a selection preserves the range. Shift+F10 or the context-menu key opens it at the active cell; arrow keys navigate and Escape dismisses it.
Viewer mode (readOnly) offers Copy and selection actions. Editor mode also offers Cut, Paste, Edit cell, Clear contents, Undo/Redo, Merge/Unmerge, and sorting when the target belongs to a table. Actions use the existing controller and undo history. Row and column selections span the displayed grid, matching header selection. Worker-backed viewers copy tab-separated text; editable workbooks also preserve structured cell data when the browser supports custom clipboard formats. Clipboard commands require browser clipboard access; failed operations display an error and Cut only clears cells after copying succeeds.
Row and column headers have their own menus. In editing mode they offer Cut, Copy, Paste, Clear Contents, Row Height or Column Width, Hide, and Unhide. Sizing uses logical pixels and applies to all selected headers in one undo step. Read-only headers offer Copy and optionally sizing with allowResizeInReadOnly and Hide and Unhide with allowHideInReadOnly. Shift+F10 opens the same menu for a header selection.
Chart and image menus start with Undo and Redo, followed by a separator. Drawing Cut and Copy are not offered; copying worksheet cells remains supported. Bring to Front and Send to Back contain the one-step layer commands. Charts also have a nested Change Chart Type menu, grouped by family; options that require a different series count are disabled. Drawing positions, sizes, layer order, and chart types participate in undo/redo and are preserved by download() and exportXlsx().
Pasting drawings from Excel uses browser clipboard APIs and places their top-left corner at the active cell. See Pasting from Excel for supported representations and browser requirements. The controller, useXlsxViewerCharts(), and useXlsxViewerImages() expose pasteDrawingFromClipboard(), arrangeDrawing(kind, id, order), and changeChartType(id, type).
Customize the existing menu with contextMenuClassName, contextMenuStyle, and CSS variables, or replace its contents with renderContextMenu:
<XlsxViewer
file={file}
contextMenuClassName="spreadsheet-menu"
contextMenuStyle={{ "--xlsx-menu-radius": "6px" }}
renderContextMenu={({ context, defaultNode, closeMenu }) => (
<>
{defaultNode}
<button type="button" role="menuitem" onClick={() => {
inspectSelection(context.selection);
closeMenu();
}}>
Inspect selection
</button>
</>
)}
/>The hook receives context (target kind, cell, selection, sheet index/name, read-only state, and the targeted chart or image), actions, runAction, closeMenu, viewport position, isDark, busy, error, and defaultNode. Return defaultNode to keep built-in buttons while adding your own content. The viewer owns the portal, viewport-edge positioning, outside-click dismissal, and keyboard navigation for elements with role="menuitem"; return menu contents without another portal. runAction returns Promise<boolean> and rejects unavailable or disabled commands. Handle custom commands in your own callback and call closeMenu afterward.
Actions can contain recursive children; custom renderers should render them as nested submenus, including checked, disabled, and separatorBefore. The playground uses Coss UI primitives for these menus.
Default styling uses a compact, conventional context menu and follows the document theme. Submenus inherit the same style variables and custom class. Override .react-xlsx-context-menu, .react-xlsx-context-menu-item, .react-xlsx-context-menu-separator, and .react-xlsx-context-menu-shortcut, set --xlsx-menu-radius and --xlsx-menu-padding to resize the menu while keeping item corners concentric (items use the radius minus the padding), or set --xlsx-context-menu-background, --xlsx-context-menu-color, --xlsx-context-menu-border, --xlsx-context-menu-hover, --xlsx-context-menu-muted, and --xlsx-context-menu-danger through contextMenuStyle. The menu is portaled to the document body, so use its class rather than a viewer-descendant selector. The table header sort menu uses the same classes, so contextMenuClassName and contextMenuStyle restyle it too. Set enableContextMenu={false} to retain the browser's native context menu.
Pasting from Excel
Excel-to-viewer paste runs entirely in the browser. No native helper, local clipboard server, host adapter, or operating-system detection is required. Enable editing, select the destination cell, copy an object in desktop Excel, and press Cmd+V on macOS or Ctrl+V on Windows in the worksheet. The cell context menu also offers Paste.
import { XlsxViewer } from "@extend-ai/react-xlsx";
export function WorkbookEditor({ buffer }: { buffer: ArrayBuffer }) {
return <XlsxViewer file={buffer} readOnly={false} height={600} />;
}The result depends on what Excel and the browser expose on the clipboard:
| Clipboard content | Paste result | | --- | --- | | Excel drawing package containing a supported chart | Editable chart with its cached series data and formatting preserved in XLSX export | | Excel drawing package containing a picture, shape, or supported shape group | Drawing inserted at the selected cell | | Image representation, including artwork without a supported editable package | Picture; the appearance is retained, but chart data and individual shape editing are unavailable | | Worksheet cells | Cell values and formulas, using the existing cell paste behavior |
Current desktop Chrome or Edge is recommended for editable drawing paste because they expose web custom clipboard formats. Excel must publish its drawing package in a browser-readable format. Other browsers, older Excel versions, and unsupported Office objects may expose only an image. Clipboard access requires HTTPS or localhost and may prompt for permission. Keyboard paste can use image data supplied by the paste event even when asynchronous clipboard reading is denied. An image fallback does not preserve editable chart data.
controller.pasteFromClipboard() handles charts, artwork, and cells. controller.pasteDrawingFromClipboard() handles drawings only; it also accepts an Office clipboard JSON string, a drawing ZIP Blob, or an image Blob supplied by your application. These methods return whether anything was pasted. Pasting participates in Undo/Redo and exportXlsx(). Chart values come from the clipboard package’s caches; the viewer does not refresh links to external workbooks.
Drawing Cut/Copy out of the viewer is intentionally unavailable. Installing this browser library does not enable editable chart copying into desktop Excel. Cell copying and XLSX download remain available. There are no native clipboard scripts or services to deploy.
The browser-only path is verified with Excel for Mac. End-to-end validation with Excel for Windows is still required; the implementation uses the same browser representations on both platforms. Clipboard APIs cannot provide an editable object when Excel or the browser does not expose it.
Custom Cell Editor Overlays
renderCellEditorOverlay adds your own decoration and actions around the live cell editor. It runs only while editing, never when merely selecting a cell. The library supplies no default menu, AI client, or animation. The separate renderSelectionPopover callback handles selections outside editing. React callbacks return React content; vanilla callbacks return DOM nodes. cellEditorStyle customizes the built-in editor's appearance without replacing its input or text measurement.
import type { XlsxCellEditorContext, XlsxCellEditorOverlayRenderProps } from "@extend-ai/react-xlsx";
function FormulaActions({ editor, generateFormula }: {
editor: XlsxCellEditorOverlayRenderProps;
generateFormula: (request: { prompt: string; context: XlsxCellEditorContext; signal: AbortSignal }) => Promise<string>;
}) {
const [busy, setBusy] = React.useState(false);
const [error, setError] = React.useState<string | null>(null);
async function generate() {
const prompt = editor.getValue();
if (prompt === null) return;
setBusy(true);
setError(null);
try {
const formula = await generateFormula({
prompt,
context: editor.context,
signal: editor.signal,
});
if (editor.getValue() === prompt) editor.preview(formula);
} catch (cause) {
if (!editor.signal.aborted) setError(String(cause));
} finally {
if (!editor.signal.aborted) setBusy(false);
}
}
return (
<div style={{ position: "absolute", top: "calc(100% + 8px)", pointerEvents: "auto" }}>
{editor.isPreview ? (
<>
<button onClick={() => editor.commit()}>Keep</button>
<button onClick={() => editor.discardPreview()}>Discard</button>
</>
) : (
<button disabled={busy} onClick={generate}>Write formula</button>
)}
{error && <div role="alert">{error}</div>}
</div>
);
}
<XlsxViewer
file={file}
cellEditorStyle={{ borderRadius: 4, boxShadow: "inset 0 0 0 2px #64748b" }}
renderCellEditorOverlay={(editor) => (
<FormulaActions editor={editor} generateFormula={callYourBackend} />
)}
/>context contains the zero-based cell, sheetIndex (an index in controller.sheets), sheetName, the saved originalValue, and the editing trigger: "double-click", "typing", "keyboard", or "context-menu". For assistance only after double-clicking and changing the text, check context.trigger === "double-click" && value !== context.originalValue. value is the current draft. editorElement is the native editor element, available for anchoring and scoped styles or effects; undo DOM changes when your component unmounts. rect is the expanded editor's rectangle in viewport pixels, updated as the input grows, the worksheet scrolls, or zoom changes.
| Member | Behavior |
| --- | --- |
| getValue() | Reads the latest draft, or null after the session ends. |
| setValue(text) | Replaces the draft without saving it. Ordinary editing commit behavior still applies. |
| preview(text) | Shows a proposed replacement and marks it for review, retaining the previous draft. |
| isPreview | Indicates that the draft is an unconfirmed preview. |
| discardPreview() | Restores the draft from before the preview and focuses the input. |
| commit(text?) | Saves the supplied input, or the current draft, and ends editing. Uses normal formula parsing and undo history. |
| cancel() | Ends editing without saving any draft or preview. |
| focus() | Returns focus to the native editor. |
| signal | An AbortSignal cancelled when the editing session ends or changes target. |
Commands return false after their session ends, so a delayed response cannot write to a different cell. For requests that depend on the draft, also compare getValue() with the submitted text before applying a result. Pass signal to your backend request. Use commit(formula) for direct application, or preview(formula) for a review flow. Previewing does not write to the workbook: Enter or commit() accepts it; Escape or leaving the editor cancels it. Tab/arrow navigation also leaves an unconfirmed preview unsaved. Repeated preview() calls preserve the draft from before the first preview.
The overlay is an unstyled portal positioned over the actual expanded input in both canvas and DOM rendering. Its container ignores pointer events: set pointerEvents: "auto" on interactive content. Place actions below it with top: "calc(100% + 8px)"; render a full-size decorative wrapper to draw a custom border around it. Your wrapper may use CSS, a canvas shader, or an animation component. The native input remains underneath, preserving caret behavior and formula highlighting. rect lets your UI choose an alternate placement near window edges. Apply sizing and scrolling to your own panels as needed.
Interactions inside the overlay keep the edit session open. Alt+ArrowDown from the editor focuses its first control. The overlay isolates keyboard events from grid navigation; your components own their roles and navigation. Return null to render no decoration or controls. Without renderCellEditorOverlay, no overlay is mounted.
Your menu items and their callbacks belong entirely to your renderer. A callback can call setValue(formula) to replace the editor text and update your component's state or the renderCellEditorOverlay prop to display different controls. Use preview(formula) when you also want the library to retain the previous draft for Discard and prevent unconfirmed changes from saving on blur. To apply immediately, call commit(formula); it saves the cell and closes the editor. There is no required menu model, review screen, or confirmation step. When using a UI component that creates its own portal, mount it into an element inside your overlay so focus and pointer interactions remain within the edit session.
All animation belongs to your rendered component, including its origin, easing, duration, and exit behavior. The library does not animate the overlay container. Anchor a popover to an element that fills the overlay, animate its opacity and scale from that anchor, and disable position transitions on its positioning element to avoid movement from an initial unpositioned location. Retain the current menu content throughout an exit animation instead of switching back to suggestions while closing. Respect reduced-motion preferences in your renderer.
Vanilla JavaScript uses the same session commands:
const viewer = createXlsxViewer(container, {
file: workbookBytes,
renderCellEditorOverlay(editor) {
const button = document.createElement("button");
button.textContent = editor.isPreview ? "Keep" : "Write formula";
Object.assign(button.style, {
position: "absolute", top: "calc(100% + 8px)", pointerEvents: "auto",
});
button.onclick = async () => {
if (editor.isPreview) { editor.commit(); return; }
const prompt = editor.getValue();
if (prompt === null) return;
button.disabled = true;
try {
const formula = await callYourBackend({ prompt, context: editor.context, signal: editor.signal });
if (editor.getValue() === prompt) editor.preview(formula);
} catch (error) {
if (!editor.signal.aborted) showError(error);
} finally {
if (!editor.signal.aborted) button.disabled = false;
}
};
return button;
},
});The render callback is called as the draft and editor geometry change. Return a stable DOM node when preserving state in custom vanilla controls. The playground opts into this API while typing in the cell editor, using animated Coss UI popovers and a text shimmer during preview. Its “Write formula (Demo formula)” callback immediately previews a deterministic formula referencing multiple ranges and switches the actions to Keep and Discard. In the starter workbook it averages the three curve columns, excluding the target cell to avoid a circular reference. Other worksheets use a deterministic three-range formula that excludes the target column. It does not call an AI backend. The effects and controls live entirely in the playground renderer.
The playground also demonstrates a Coss UI “Generate formula” context-menu submenu through renderContextMenu. Its instruction input supports formula previews and a “heatmap” demo that previews numeric-cell colors through getCellStyle, then saves them through setCellStyles only on Keep. Discard removes the temporary styles. Context-menu render props expose signal and commit(callback) so custom backend actions can reject stale menus and apply arbitrary synchronous controller changes. Mount nested menu portals inside your custom renderer and stop keyboard propagation when your UI handles navigation.
Custom Selection Popovers
renderSelectionPopover is independently opt-in and works for a cell or range selection in React and vanilla JavaScript. It is hidden during editing and supplies no default controls, styles, or animations. The callback receives context (cell, normalized selection, sheetIndex, sheetName, readOnly), the visible selection rect in viewport pixels, signal, close(), applyFormula(formula), and commit(callback) for other synchronous mutations.
applyFormula writes to the active cell with normal undo history, closes the popover, and returns false if the selection has expired or is read-only. signal aborts when the popover closes, the selection changes, or editing starts. Preview a backend result in your own component state before applying it; Discard can simply call close(). To update a range or perform another action, use commit(() => controller.setCellStyles(updates)) or another synchronous controller mutation. setCellStyles([{ cell, style }, ...]) applies individually styled cells as one undoable edit and preserves them in XLSX exports. Check the signal before applying async results.
<XlsxViewer
controller={controller}
renderSelectionPopover={(selection) => (
<YourFormulaPopover
selection={selection.context.selection}
onGenerate={(instructions) => callYourBackend({
prompt: instructions,
context: selection.context,
signal: selection.signal,
})}
onKeep={selection.applyFormula}
onDiscard={selection.close}
/>
)}
/>The unstyled portal fills the visible selection bounds. Set pointerEvents: "auto" on interactive content and position it below with top: "calc(100% + 8px)", or use your own anchored popover. Mount nested UI portals into a host inside this container. Input focus and keyboard events are isolated from the worksheet. Vanilla renderers receive the same props and return DOM nodes. Both selection and editor renderers can be configured together or used separately.
Custom Rendering
The viewer exposes render props for common UI integration points.
import { XlsxViewer } from "@extend-ai/react-xlsx";
export function CustomWorkbook({ file }: { file: ArrayBuffer }) {
return (
<XlsxViewer
file={file}
height={600}
selectionColor="#2563eb"
renderImage={({ image, style }) => (
<img
src={image.src}
alt={image.description ?? image.name ?? ""}
style={{ ...style, objectFit: "contain" }}
/>
)}
renderTableHeaderMenu={({ column, direction, sortAscending, sortDescending, triggerIcon, triggerProps }) => (
<span>
<button type="button" {...triggerProps}>
{triggerIcon}
</button>
<button type="button" onClick={sortAscending}>
Sort ascending{direction === "ascending" ? " selected" : ""}
</button>
<button type="button" onClick={sortDescending}>
Sort descending{direction === "descending" ? " selected" : ""}
</button>
<span>{column.name}</span>
</span>
)}
/>
);
}Apply triggerProps to the table-header trigger button so clicks do not leak into grid selection.
Locale and UI text
The built-in header and context menus use Sort ascending / Sort descending in English, with translations selected by locale. The toolbar, sheet and grid accessibility labels, cell editor, form-control fallback labels, loading/empty/error states, and chart fallbacks use the same locale. Changing locale or messages updates the UI without reloading the workbook.
Bundled UI languages are English (en), French (fr), German (de), Spanish (es), Italian (it), Portuguese (pt), Japanese (ja), and Simplified Chinese (zh). Regional tags use their language catalog, so fr-CA uses French. Unsupported languages fall back to English for UI text; number formatting still uses the requested locale. Supply messages to add another language or change any wording.
<XlsxViewer
file={file}
locale="fr-FR"
messages={{
sortAscending: "Ordre croissant",
sortDescending: "Ordre décroissant",
openMenuForColumn: "Options de {column}",
}}
/>messages is also accepted by useXlsxViewerController, XlsxViewerProvider, and the vanilla viewer options. With a supplied controller or provider, configure locale there so formatting and UI use the same locale. A viewer's messages prop overrides its controller's messages for that viewer. Resolved text is available as controller.messages for custom UI.
Message values are plain strings. Keep {column} in openMenuForColumn, {sheet} in worksheetGrid, hiddenSheet, and veryHiddenSheet, {size} and {limit} in fileTooLarge, and {size} in deferredLoadDescription wherever those values should appear. Values are inserted as text. Workbook content and custom render callbacks keep the text supplied by the workbook or application. Default errors use localized messages; the original error is available through controller.error and errorState.
Use renderActiveCellOverlay to render your own content over the active cell. The returned node sits in a container that exactly covers the cell (the full merge for merged cells) and moves with scrolling and zoom, so you can attach classes, data attributes, or a ref and measure it with getBoundingClientRect(). The container ignores pointer events; set pointerEvents: "auto" on your own elements to make them interactive.
<XlsxViewer
file={file}
renderActiveCellOverlay={({ cell }) => (
<div
ref={activeCellRef}
className="active-cell-anchor"
data-active-cell={`${cell.row}:${cell.col}`}
style={{ height: "100%", width: "100%" }}
/>
)}
/>Use renderFormControl to replace the built-in worksheet widgets. The callback receives the parsed control, resolved items and label, calculated style, read-only state, and activate, setState, setSelected, and setValue helpers. Apply style to the custom root and call stopPropagation from pointer/click handlers. The helpers keep Duke mutations, linked cells, undo/redo, export, and onFormControlChange in sync.
<XlsxViewer
file={file}
renderFormControl={({ checked, control, disabled, label, setState, stopPropagation, style }) => {
if (control.kind === "checkbox" || control.kind === "radio") {
return (
<label onPointerDown={stopPropagation} style={style}>
<input
checked={checked}
disabled={disabled}
onChange={(event) => setState(event.currentTarget.checked ? "checked" : "unchecked")}
type={control.kind === "radio" ? "radio" : "checkbox"}
/>
{label}
</label>
);
}
return <div style={style}>{label}</div>;
}}
/>Large Files
XlsxViewer includes guardrails for large workbooks.
import { XlsxViewer } from "@extend-ai/react-xlsx";
export function LargeWorkbookPreview({ file }: { file: ArrayBuffer }) {
return (
<XlsxViewer
file={file}
maxFileSizeBytes={50 * 1024 * 1024}
readOnlyAboveBytes={10 * 1024 * 1024}
deferLoadingAboveBytes={20 * 1024 * 1024}
fileTooLargeState={({ displa

