Skip to content

Export to Excel

Added in Handsontable 17.1.0

Export your grid to an Excel (.xlsx) file. The ExportFile plugin writes cell types, styling, merged cells, comments, and frozen panes with the data, and formulas too with exportFormulas. It uses the built-in XLSX engine unless you configure ExcelJS - see XLSX engines.

Demo

Click Export XLSX to download the Q1 report: nested headers, a dropdown with its list, a currency column, a checkbox column, a column summary written as a live SUM, a merged total row, a custom border, a frozen first column, and a comment on Alice’s notes.

JavaScript
import Handsontable from 'handsontable/base';
import { registerAllModules } from 'handsontable/registry';
registerAllModules();
const container = document.querySelector('#example1');
const hot = new Handsontable(container, {
data: [
['Alice Martin', 'North', 142000, true, 'Exceeded Q1 target by 18%.'],
['Bob Chen', 'East', 98500, true, 'Strong pipeline for Q2.'],
['Carol Davies', 'South', 76200, false, 'Needs coaching on closing.'],
['David Kim', 'West', 115300, true, 'Cross-sell opportunity.'],
['Eva Rossi', 'North', 54800, false, 'Sick leave impacted March.'],
['TOTALS', '', null, '', ''],
],
nestedHeaders: [
[
{ label: 'Sales Representative', colspan: 2, headerClassName: 'htCenter' },
{ label: 'Results', colspan: 2, headerClassName: 'htCenter' },
{ label: 'Notes', colspan: 1, headerClassName: 'htLeft' },
],
['Name', 'Region', 'Revenue ($)', 'Hit Target?', 'Notes'],
],
columns: [
{ type: 'text' },
{ type: 'dropdown', source: ['North', 'South', 'East', 'West'] },
{
type: 'numeric',
locale: 'en-US',
numericFormat: { style: 'currency', currency: 'USD', minimumFractionDigits: 2 },
},
{ type: 'checkbox' },
{ type: 'text' },
],
columnSummary: [
{
sourceColumn: 2,
destinationRow: 5,
destinationColumn: 2,
type: 'sum',
forceNumeric: true,
},
],
mergeCells: [{ row: 5, col: 0, rowspan: 1, colspan: 2 }],
customBorders: [
{
row: 5,
col: 2,
top: { width: 2, color: '#333333' },
},
],
cell: [
{ row: 5, col: 0, readOnly: true },
{ row: 5, col: 2, readOnly: true },
],
fixedColumnsStart: 1,
rowHeaders: true,
comments: true,
colHeaders: true,
height: 'auto',
autoWrapRow: true,
autoWrapCol: true,
exportFile: true,
// licenseKey: 'your-license-key', // get a key at https://handsontable.com/pricing/
});
// Add a comment to Alice's notes cell.
hot.setCellMeta(0, 4, 'comment', { value: 'Top sales rep - review for promotion.' });
hot.render();
const exportPlugin = hot.getPlugin('exportFile');
const button = document.querySelector('#export-file');
button.addEventListener('click', async () => {
await exportPlugin.downloadFileAsync('xlsx', {
filename: 'Q1-Sales-Report',
colHeaders: true,
rowHeaders: true,
exportFormulas: true,
});
});
TypeScript
import Handsontable from 'handsontable/base';
import { registerAllModules } from 'handsontable/registry';
registerAllModules();
const container = document.querySelector('#example1')!;
const hot = new Handsontable(container, {
data: [
['Alice Martin', 'North', 142000, true, 'Exceeded Q1 target by 18%.'],
['Bob Chen', 'East', 98500, true, 'Strong pipeline for Q2.'],
['Carol Davies', 'South', 76200, false, 'Needs coaching on closing.'],
['David Kim', 'West', 115300, true, 'Cross-sell opportunity.'],
['Eva Rossi', 'North', 54800, false, 'Sick leave impacted March.'],
['TOTALS', '', null, '', ''],
],
nestedHeaders: [
[
{ label: 'Sales Representative', colspan: 2, headerClassName: 'htCenter' },
{ label: 'Results', colspan: 2, headerClassName: 'htCenter' },
{ label: 'Notes', colspan: 1, headerClassName: 'htLeft' },
],
['Name', 'Region', 'Revenue ($)', 'Hit Target?', 'Notes'],
],
columns: [
{ type: 'text' },
{ type: 'dropdown', source: ['North', 'South', 'East', 'West'] },
{
type: 'numeric',
locale: 'en-US',
numericFormat: { style: 'currency', currency: 'USD', minimumFractionDigits: 2 },
},
{ type: 'checkbox' },
{ type: 'text' },
],
columnSummary: [
{
sourceColumn: 2,
destinationRow: 5,
destinationColumn: 2,
type: 'sum',
forceNumeric: true,
},
],
mergeCells: [
{ row: 5, col: 0, rowspan: 1, colspan: 2 },
],
customBorders: [
{
row: 5, col: 2,
top: { width: 2, color: '#333333' },
},
],
cell: [
{ row: 5, col: 0, readOnly: true },
{ row: 5, col: 2, readOnly: true },
],
fixedColumnsStart: 1,
rowHeaders: true,
comments: true,
colHeaders: true,
height: 'auto',
autoWrapRow: true,
autoWrapCol: true,
exportFile: true,
// licenseKey: 'your-license-key', // get a key at https://handsontable.com/pricing/
});
// Add a comment to Alice's notes cell.
hot.setCellMeta(0, 4, 'comment', { value: 'Top sales rep - review for promotion.' });
hot.render();
const exportPlugin = hot.getPlugin('exportFile');
const button = document.querySelector('#export-file')!;
button.addEventListener('click', async () => {
await exportPlugin.downloadFileAsync('xlsx', {
filename: 'Q1-Sales-Report',
colHeaders: true,
rowHeaders: true,
exportFormulas: true,
});
});
HTML
<div class="example-controls-container">
<div class="controls">
<button id="export-file">Export XLSX</button>
</div>
</div>
<div id="example1"></div>

Prerequisites

  • Register the ExportFile plugin (it is part of registerAllModules()). No other library is needed.
  • Set exportFile to any value, for example exportFile: true, and turn on the context menu to add the Export item to it. With a custom contextMenu item list, include 'export_file'. The export methods work whatever the value, unset included.
  • To run the export in Jest or Vitest, set up the test environment as Testing describes.

Example

  1. Turn the plugin on

    const hot = new Handsontable(container, {
    exportFile: true,
    // licenseKey: 'your-license-key', // get a key at https://handsontable.com/pricing/
    });
  2. Download a file

    const exportPlugin = hot.getPlugin('exportFile');
    await exportPlugin.downloadFileAsync('xlsx', { filename: 'Q1-sales', colHeaders: true, rowHeaders: true });
  3. Get a Blob instead

    const blob = await exportPlugin.exportAsBlobAsync('xlsx', { colHeaders: true }); // for example, to upload it

    The synchronous exportAsBlob('xlsx') throws, because an XLSX file is built asynchronously. Both methods also take 'csv'. Methods lists every export method.

Context menu

When the context menu is on and exportFile is set to any value, false included, an Export item with To CSV and To Excel appears in it. Only an unset exportFile keeps the item out. To Excel uses the grid’s XLSX engine - see Choose the engine.

The export covers the selected range, or the whole grid when a single cell is selected. It follows the grid’s own column and row headers and leaves hidden rows and columns out.

Right-click any cell to open the context menu.

JavaScript
import Handsontable from 'handsontable/base';
import { registerAllModules } from 'handsontable/registry';
registerAllModules();
new Handsontable(document.querySelector('#example3'), {
data: [
['Laptop Pro 15"', 'Electronics', 1299.99, 38, true ],
['Wireless Mouse', 'Accessories', 29.99, 214, true ],
['USB-C Hub 7-in-1','Accessories', 49.99, 87, true ],
['Monitor 27" 4K', 'Electronics', 449.99, 12, false],
['Mech Keyboard', 'Accessories', 119.99, 65, true ],
],
columns: [
{ type: 'text' },
{ type: 'dropdown', source: ['Electronics', 'Accessories', 'Software'] },
{
type: 'numeric',
locale: 'en-US',
numericFormat: { style: 'currency', currency: 'USD', minimumFractionDigits: 2 },
},
{ type: 'numeric' },
{ type: 'checkbox' },
],
colHeaders: ['Product', 'Category', 'Unit Price', 'Stock', 'Active?'],
rowHeaders: true,
height: 'auto',
autoWrapRow: true,
autoWrapCol: true,
contextMenu: true,
exportFile: true,
// licenseKey: 'your-license-key', // get a key at https://handsontable.com/pricing/
});
TypeScript
import Handsontable from 'handsontable/base';
import { registerAllModules } from 'handsontable/registry';
registerAllModules();
new Handsontable(document.querySelector('#example3')!, {
data: [
['Laptop Pro 15"', 'Electronics', 1299.99, 38, true ],
['Wireless Mouse', 'Accessories', 29.99, 214, true ],
['USB-C Hub 7-in-1','Accessories', 49.99, 87, true ],
['Monitor 27" 4K', 'Electronics', 449.99, 12, false],
['Mech Keyboard', 'Accessories', 119.99, 65, true ],
],
columns: [
{ type: 'text' },
{ type: 'dropdown', source: ['Electronics', 'Accessories', 'Software'] },
{
type: 'numeric',
locale: 'en-US',
numericFormat: { style: 'currency', currency: 'USD', minimumFractionDigits: 2 },
},
{ type: 'numeric' },
{ type: 'checkbox' },
],
colHeaders: ['Product', 'Category', 'Unit Price', 'Stock', 'Active?'],
rowHeaders: true,
height: 'auto',
autoWrapRow: true,
autoWrapCol: true,
contextMenu: true,
exportFile: true,
// licenseKey: 'your-license-key', // get a key at https://handsontable.com/pricing/
});
HTML
<div class="example-controls-container">
<p>Right-click any cell to open the context menu.</p>
</div>
<div id="example3"></div>

What is written

Cell typeIn the file
numericA number, with a number format built from numericFormat: currency symbols in quotes (a lone $ as it is, and a symbol several currencies share as an Excel locale token such as [$kr-414]), or the quoted ISO 4217 code, such as "ILS", where the symbol would not import as the same currency, minimumIntegerDigits as leading zeros.
date, intl-dateA date serial, with a format built from dateFormat and the cell’s locale. A date before 1900, a date that does not exist, and a value that is not an ISO 8601 YYYY-MM-DD string are written as text.
time, intl-timeA time serial. The clock follows hour12, or the locale when hour12 is not set.
intl-datetimeA date-time serial, with a format built from dateTimeFormat.
checkboxTRUE or FALSE. An empty value stays empty.
dropdown, autocompleteText, plus a list validation when source is an array. The lists live in a hidden _HotValidation sheet, which Excel lists under Unhide; do not delete it. A function source gets no list.
multiselectThe values joined with , .
Everything elseText. A number you typed into a text column is text too. A number or TRUE/FALSE the Formulas plugin computed keeps its type.

Bold, italic, and underline come from the rendered cell, or from the cell’s custom class for a cell outside the rendered viewport. Font color and background are written only for a cell whose className holds a class other than the alignment classes. The font color is the rendered cell’s own, written when it differs from what a plain cell in the same grid shows, so a color the cell inherits from its container is not. The background comes from the CSS rules that match the class on a .handsontable td, so a background a renderer sets inline, or one from a rule scoped to an element outside the grid (such as #orders td.overdue), is not written. Alignment comes from the htLeft, htCenter, htRight, htJustify, htTop, htMiddle, and htBottom classes, and borders from the CustomBorders plugin (1 px thin, 2 px medium, 3 px and up thick). A border color can be a hex value (#RGB or #RRGGBB), rgb(), hsl(), or a named color such as 'red', and a border added from the context menu is written as black. An eight-digit hex value is read as Excel ARGB (AARRGGBB), not CSS #RRGGBBAA. Font size and family are not written.

Read-only cells get a gray fill unless their class sets a background, and gray text unless their class sets a font color. The sheet is protected without a password and only read-only cells are locked, unless the export includes a columnSummary destination cell: then the sheet is not protected, because those cells are read-only only to stop edits in the grid. The grid’s readOnlyStyling option does not change the file. Header cells get the headerStyle fill and border. If your license does not include styles from the XLSX add-on, header cells are written with no fill, border, or alignment.

Frozen panes: fixedRowsTop and fixedColumnsStart are written; fixedRowsBottom and fixedColumnsEnd are not. A right-to-left grid, through layoutDirection or a right-to-left page, exports a right-to-left sheet. Comments are written from each cell’s comment meta. password cells are written as text.

Details on number formats and dates: XLSX engines. Details on formulas and error cells: Formulas, arrays, errors, and defined names.

Dropped features

When the file cannot hold something the grid has, the export writes the rest and prints one console warning that names the engine and what it left out. Every key is explained in the Dropped features reference.

Options

Pass these options as the second argument of downloadFileAsync('xlsx', options) or exportAsBlobAsync('xlsx', options).

OptionTypeDefaultDescription
filenamestring'Handsontable [YYYY]-[MM]-[DD]'File name without the extension. The placeholders become the current date.
colHeadersbooleanfalseWrite the column headers, every layer of nested headers included. Headers are written as stored; set textExtractor to write the displayed text.
rowHeadersbooleanfalseWrite the row headers as the first column. The column is frozen only when the export includes a row from fixedRowsTop or a column from fixedColumnsStart.
exportHiddenRows, exportHiddenColumnsboolean | 'hide'falsefalse leaves hidden rows or columns out, true writes them visible, 'hide' writes them hidden in the sheet.
rangenumber[]whole grid[startRow, startColumn, endRow, endColumn] in visual indexes.
exportFormulasbooleanfalseWrite Formulas cells and ColumnSummary destination cells (every summary type except custom, which is written as its value, and so is a summary that sets includeSummaryResults) as live Excel formulas instead of their values. A range that does not start at row 0 and column 0 makes references point at the wrong cells. Give the columns they read type: 'numeric': a number in a text column is written as text and sums to 0. Without the Formulas plugin, any text that starts with = becomes a live formula, so keep this off for a grid that holds text you did not write. Array formulas are written as Excel dynamic arrays, and named expressions as defined names. Error cells are written as Excel errors with or without this option, when the Formulas plugin is on. Details and limits: XLSX engines.
sheetsobject[]-Export several grids into one workbook: [{ instance, name, ...options }]. Only the listed grids are written, and each entry inherits the top-level options and can override colHeaders, rowHeaders, exportHiddenRows, exportHiddenColumns, range, exportFormulas, headerStyle, and conditionalFormatting (the SheetOptions type does not declare the last two yet). filename, compression, and engine apply to the whole workbook. See Multi-sheet export.
headerStyleobject | null{ backgroundColor: '#F2F2F2', border: { style: 'thin' } }Fill and border of the header cells. An object replaces the whole default, so pass both keys to keep one; null writes unstyled headers. Set a border color with border: { color: '#4472C4' }. Both colors accept a hex value (#RGB or #RRGGBB), rgb(), hsl(), or a named color such as 'whitesmoke'. The alpha component is dropped, an eight-digit hex value is read as Excel ARGB (AARRGGBB), not CSS #RRGGBBAA, and a value the export cannot read, 'transparent' included, is written as black, so leave backgroundColor out for no fill. fontColor and border.argb are not applied. headerStyle also styles the row headers and the corner cell.
conditionalFormattingobject[][][{ rows: [first, last], cols: [first, last], rules }]. rows and cols are offsets into the exported data, after range and hidden-row or hidden-column exclusion, and rules are ExcelJS-compatible rule objects (shape). Put a rule’s formatting in its style key; a format key is ignored. Which rule kinds each engine writes: Compare the engines.
protectionobject | nullundefinedSheet protection of read-only cells. Unset protects a sheet that has a read-only cell, with no password. { password: 'q4-budget' } protects it with that password. null protects no sheet, and read-only cells export unlocked. An empty password sets none. See Protect read-only cells.
compressionboolean | 1-9compressedUnset or true compresses the entries with DEFLATE; false stores them uncompressed. A number from 1 to 9 sets the DEFLATE level on an engine that supports it: see Compare the engines.
engineobject | null-Engine for this call only. See Choose the engine.

What your license unlocks

Formulas, styles, layout, number formats, comments, conditional formatting, data validation, and sheet protection in the exported file are available as a bundle: the XLSX add-on. Every key issued before 19.0 includes all of it.

When your tier leaves out part of the add-on, the export writes the rest of the workbook and prints one console warning that names what it skipped. Without number formats, for example, a date cell exports as the text the grid shows, such as 01/15/2024. When your tier does not include Excel export at all, the export methods throw, supportsExportFormat('xlsx') returns false and the To Excel context menu item is hidden, so check it before you offer an Excel download.

Protect read-only cells

An export protects a sheet that has a read-only cell and locks those cells, so Excel does not let users edit them. By default the sheet has no password, so anyone can unprotect it. Pass protection to set a password or turn protection off:

hot.getPlugin('exportFile').downloadFileAsync('xlsx', {
filename: 'q4-budget',
protection: { password: 'q4-budget' },
});
  • protection: { password: '...' } protects the sheet with that password. With the sheets option, every protected sheet gets the same password. A protection key on a sheets entry is ignored, and the export prints one console warning: ExportFile: the "protection" option applies to the whole workbook; the value set on a sheet entry was ignored.
  • protection: null protects no sheet, and read-only cells export unlocked.
  • An empty password sets no password.
  • A sheet with no read-only cell is not protected, so a password writes nothing. A sheet with a columnSummary destination cell is not protected either.
  • A protection value that is not an object or null rejects the export with ExportFile: the "protection" option has to be an object or null. A password that is not a string rejects it with ExportFile: the "protection.password" option has to be a string. Excel accepts a password of at most 255 characters, so a longer one rejects the export with ExportFile: the "protection.password" option has to be at most 255 characters long. The messages never contain the value.

The password is stored as a salted SHA-512 hash, and Excel asks for it when a user unprotects the sheet. The built-in engine computes the hash with crypto.subtle, which the browser exposes only in a secure context (https or localhost). On a plain http:// page, an export that protects a sheet with a password rejects with Sheet password hashing needs crypto.subtle, which is only available in a secure context (https or localhost). The hash runs 100,000 SHA-512 rounds for every protected sheet, so a multi-sheet export with a password takes noticeably longer. This is a guard against accidental edits, not encryption: the cell values stay readable in the file. If your license does not include sheet protection from the XLSX add-on, the option is ignored.

Multi-sheet export

Pass the sheets option to write several grids into one workbook, one per entry, each with its instance and the name of its tab. A sheet name is cut to 31 characters and stripped of the characters Excel forbids. With exportFormulas, a same-sheet reference is shifted by the header rows and the row-header column, but not by the start of range: with a range that does not start at row 0 and column 0, references point at the wrong cells. A formula that names another sheet in the same export is written as typed, so it points as many rows up as that sheet has header rows, and one column left when that sheet has row headers.

With the sheets bar, an export writes the active sheet only. To name its worksheet after the tab, list the grid in sheets with the tab’s name.

Q1 Sales

Q2 Sales

JavaScript
import Handsontable from 'handsontable/base';
import { registerAllModules } from 'handsontable/registry';
registerAllModules();
const q1Data = [
['Alice Martin', 'North', 142000, true],
['Bob Chen', 'East', 98500, true],
['Carol Davies', 'South', 76200, false],
['David Kim', 'West', 115300, true],
['Eva Rossi', 'North', 54800, false],
];
const q2Data = [
['Alice Martin', 'North', 158000, true],
['Bob Chen', 'East', 112400, true],
['Carol Davies', 'South', 89100, true],
['David Kim', 'West', 97600, false],
['Eva Rossi', 'North', 63200, true],
];
const sharedConfig = {
columns: [
{ type: 'text' },
{ type: 'dropdown', source: ['North', 'South', 'East', 'West'] },
{
type: 'numeric',
locale: 'en-US',
numericFormat: { style: 'currency', currency: 'USD', minimumFractionDigits: 2 },
},
{ type: 'checkbox' },
],
colHeaders: ['Name', 'Region', 'Revenue ($)', 'Hit Target?'],
rowHeaders: true,
height: 'auto',
autoWrapRow: true,
autoWrapCol: true,
exportFile: true,
// licenseKey: 'your-license-key', // get a key at https://handsontable.com/pricing/
};
const hotQ1 = new Handsontable(document.querySelector('#example2-q1'), {
...sharedConfig,
data: q1Data,
});
const hotQ2 = new Handsontable(document.querySelector('#example2-q2'), {
...sharedConfig,
data: q2Data,
});
document.querySelector('#export-sheets').addEventListener('click', async () => {
const exportPlugin = hotQ1.getPlugin('exportFile');
await exportPlugin.downloadFileAsync('xlsx', {
filename: 'Annual-Sales-Report',
sheets: [
{ instance: hotQ1, name: 'Q1 Sales', colHeaders: true, rowHeaders: true },
{ instance: hotQ2, name: 'Q2 Sales', colHeaders: true, rowHeaders: true },
],
});
});
TypeScript
import Handsontable from 'handsontable/base';
import { registerAllModules } from 'handsontable/registry';
registerAllModules();
const q1Data = [
['Alice Martin', 'North', 142000, true ],
['Bob Chen', 'East', 98500, true ],
['Carol Davies', 'South', 76200, false],
['David Kim', 'West', 115300, true ],
['Eva Rossi', 'North', 54800, false],
];
const q2Data = [
['Alice Martin', 'North', 158000, true ],
['Bob Chen', 'East', 112400, true ],
['Carol Davies', 'South', 89100, true ],
['David Kim', 'West', 97600, false],
['Eva Rossi', 'North', 63200, true ],
];
const sharedConfig: Handsontable.GridSettings = {
columns: [
{ type: 'text' },
{ type: 'dropdown', source: ['North', 'South', 'East', 'West'] },
{
type: 'numeric',
locale: 'en-US',
numericFormat: { style: 'currency', currency: 'USD', minimumFractionDigits: 2 },
},
{ type: 'checkbox' },
],
colHeaders: ['Name', 'Region', 'Revenue ($)', 'Hit Target?'],
rowHeaders: true,
height: 'auto',
autoWrapRow: true,
autoWrapCol: true,
exportFile: true,
// licenseKey: 'your-license-key', // get a key at https://handsontable.com/pricing/
};
const hotQ1 = new Handsontable(document.querySelector('#example2-q1')!, {
...sharedConfig,
data: q1Data,
});
const hotQ2 = new Handsontable(document.querySelector('#example2-q2')!, {
...sharedConfig,
data: q2Data,
});
document.querySelector('#export-sheets')!.addEventListener('click', async () => {
const exportPlugin = hotQ1.getPlugin('exportFile');
await exportPlugin.downloadFileAsync('xlsx', {
filename: 'Annual-Sales-Report',
sheets: [
{ instance: hotQ1, name: 'Q1 Sales', colHeaders: true, rowHeaders: true },
{ instance: hotQ2, name: 'Q2 Sales', colHeaders: true, rowHeaders: true },
],
});
});
HTML
<div class="example-controls-container">
<div class="controls">
<button id="export-sheets">Export XLSX</button>
</div>
</div>
<p><strong>Q1 Sales</strong></p>
<div id="example2-q1"></div>
<p><strong>Q2 Sales</strong></p>
<div id="example2-q2"></div>

Methods

Each export method takes the format first, 'csv' or 'xlsx', and an options object second.

Hooks

The ExportFile plugin runs no hooks of its own. To act on the file before it reaches the user, get it with exportAsBlobAsync() instead of downloadFileAsync().

Related guides

Configuration options

Plugins