Export to CSV
Export your grid’s values to the CSV format, as a downloadable file, a Blob, or a string. CSV holds values only: no formulas, styling, or number formatting, so a formula cell exports its computed result.
Prerequisites
- Register the
ExportFileplugin (it is part ofregisterAllModules()). The export methods work without anyexportFilesetting; setexportFileto any value, for exampleexportFile: true, to add the Export item to the default context menu; with a customcontextMenuitem list, include'export_file'. - The first two examples hide rows and columns
1,3, and5, with indicators on, so you can see which export includes them.
Steps
Download a file
downloadFile('csv', options)builds the file and starts the download. This example includes the hidden rows and columns.TypeScript /* file: app.component.ts */import { Component, ViewChild } from '@angular/core';import { GridSettings, HotTableComponent, HotTableModule} from '@handsontable/angular-wrapper';@Component({standalone: true,imports: [HotTableModule],selector: 'app-example1',template: `<div class="example-controls-container"><div class="controls"><button (click)="exportFile()">Download CSV</button></div></div><hot-table[settings]="hotSettings!" [data]="hotData"></hot-table>`,})export class AppComponent {@ViewChild(HotTableComponent, {static: false}) hotTable!: HotTableComponent;readonly hotData = [['Spring Launch', 'Email', 'North America', '1240', '4.2%', '$12000', 'Q1 2025'],['Partner Webinar', 'Paid Search', 'EMEA', '860', '6.1%', '$9400', 'Q1 2025'],['Summer Upsell', 'Social', 'APAC', '1520', '3.7%', '$13800', 'Q2 2025'],['Product Video', 'Email', 'North America', '980', '5.4%', '$8600', 'Q2 2025'],['Back-to-School', 'Display', 'LATAM', '1110', '4.8%', '$10100', 'Q3 2025'],['Holiday Teaser', 'Affiliate', 'EMEA', '1340', '5.9%', '$12700', 'Q4 2025'],['Loyalty Drive', 'SMS', 'APAC', '790', '7.3%', '$6200', 'Q4 2025'],];readonly hotSettings: GridSettings = {colHeaders: true,rowHeaders: true,hiddenRows: { rows: [1, 3, 5], indicators: true },hiddenColumns: { columns: [1, 3, 5], indicators: true },height: 'auto',autoWrapRow: true,autoWrapCol: true,};exportFile() {const exportPlugin = this.hotTable.hotInstance!.getPlugin('exportFile');exportPlugin.downloadFile('csv', {colHeaders: true,rowHeaders: true,exportHiddenColumns: true,exportHiddenRows: true,filename: 'Campaigns_[YYYY]-[MM]-[DD]',});}}/* end-file *//* file: app.config.ts */import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';import { registerAllModules } from 'handsontable/registry';import { HOT_GLOBAL_CONFIG, HotGlobalConfig } from '@handsontable/angular-wrapper';// register Handsontable's modulesregisterAllModules();export const appConfig: ApplicationConfig = {providers: [provideZoneChangeDetection({ eventCoalescing: true }),{provide: HOT_GLOBAL_CONFIG,useValue: {// license: 'your-license-key', // get a key at https://handsontable.com/pricing/} as HotGlobalConfig,},],};/* end-file */HTML <div><app-example1></app-example1></div>Export as a Blob or a string
exportAsBlob('csv', options)returns aBlob, for example to upload;exportAsString('csv', options)returns the text. This example leaves the hidden rows and columns out. Open the browser console to see the result.TypeScript /* file: app.component.ts */import { Component, ViewChild } from '@angular/core';import { GridSettings, HotTableComponent, HotTableModule} from '@handsontable/angular-wrapper';@Component({standalone: true,imports: [HotTableModule],selector: 'app-example2',template: `<div class="example-controls-container"><div class="controls"><button (click)="exportBlob()">Export as a Blob</button><button (click)="exportString()">Export as a string</button></div></div><hot-table[settings]="hotSettings!" [data]="hotData"></hot-table>`,})export class AppComponent {@ViewChild(HotTableComponent, {static: false}) hotTable!: HotTableComponent;readonly hotData = [['Spring Launch', 'Email', 'North America', '1240', '4.2%', '$12000', 'Q1 2025'],['Partner Webinar', 'Paid Search', 'EMEA', '860', '6.1%', '$9400', 'Q1 2025'],['Summer Upsell', 'Social', 'APAC', '1520', '3.7%', '$13800', 'Q2 2025'],['Product Video', 'Email', 'North America', '980', '5.4%', '$8600', 'Q2 2025'],['Back-to-School', 'Display', 'LATAM', '1110', '4.8%', '$10100', 'Q3 2025'],['Holiday Teaser', 'Affiliate', 'EMEA', '1340', '5.9%', '$12700', 'Q4 2025'],['Loyalty Drive', 'SMS', 'APAC', '790', '7.3%', '$6200', 'Q4 2025'],];readonly hotSettings: GridSettings = {colHeaders: true,rowHeaders: true,hiddenRows: { rows: [1, 3, 5], indicators: true },hiddenColumns: { columns: [1, 3, 5], indicators: true },height: 'auto',autoWrapRow: true,autoWrapCol: true,};// Hidden rows and columns stay out of both exports.private readonly exportOptions = {colHeaders: true,rowHeaders: true,exportHiddenColumns: false,exportHiddenRows: false,};exportBlob() {const exportPlugin = this.hotTable.hotInstance!.getPlugin('exportFile');console.log(exportPlugin.exportAsBlob('csv', this.exportOptions));}exportString() {const exportPlugin = this.hotTable.hotInstance!.getPlugin('exportFile');console.log(exportPlugin.exportAsString('csv', this.exportOptions));}}/* end-file *//* file: app.config.ts */import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';import { registerAllModules } from 'handsontable/registry';import { HOT_GLOBAL_CONFIG, HotGlobalConfig } from '@handsontable/angular-wrapper';// register Handsontable's modulesregisterAllModules();export const appConfig: ApplicationConfig = {providers: [provideZoneChangeDetection({ eventCoalescing: true }),{provide: HOT_GLOBAL_CONFIG,useValue: {// license: 'your-license-key', // get a key at https://handsontable.com/pricing/} as HotGlobalConfig,},],};/* end-file */HTML <div><app-example2></app-example2></div>Prevent CSV injection
A spreadsheet application reads a CSV cell that starts with
=,+,-, or@as a formula (OWASP: CSV injection). Set thesanitizeValuesoption when the data comes from users. This example shows the four modes.TypeScript /* file: app.component.ts */import { Component, ViewChild, ViewEncapsulation } from '@angular/core';import { GridSettings, HotTableComponent, HotTableModule } from '@handsontable/angular-wrapper';@Component({selector: 'app-example3',standalone: true,imports: [HotTableModule],template: `<div class="example-controls-container"><div class="controls"><button (click)="downloadCSVWithNoSanitization()">Download CSV with no sanitization</button><button (click)="downloadCSVWithRecommendedSanitization()">Download CSV with recommended sanitization</button><button (click)="downloadCSVWithRegexpSanitization()">Download CSV with sanitization using a regexp</button><button (click)="downloadCSVWithFunctionSanitization()">Download CSV with sanitization using a function</button></div></div><hot-table[settings]="hotSettings!" [data]="hotData"></hot-table>`,encapsulation: ViewEncapsulation.None})export class AppComponent {@ViewChild(HotTableComponent, {static: false}) hotTable!: HotTableComponent;readonly hotData = [['https://api.acme-inventory.com/live-stock', '=WEBSERVICE("https://api.acme-inventory.com/live-stock")'],['https://status.vertex-logistics.com/feed', '=WEBSERVICE("https://status.vertex-logistics.com/feed")'],['http://malicious.example/payload.exe', '=CMD("| calc.exe")'],['https://news.example.com/q2-briefing', '=HYPERLINK("http://malicious.example","Open report")'],['https://cdn.example.com/daily.csv', '+SUM(1,1)'],];readonly hotSettings: GridSettings = {colHeaders: true,rowHeaders: true,height: 'auto',autoWrapRow: true,autoWrapCol: true,};downloadCSVWithNoSanitization() {const exportPlugin = this.hotTable.hotInstance!.getPlugin('exportFile');exportPlugin.downloadFile('csv', {bom: false,columnDelimiter: ',',colHeaders: false,exportHiddenColumns: true,exportHiddenRows: true,fileExtension: 'csv',filename: 'Handsontable-CSV-file_[YYYY]-[MM]-[DD]',mimeType: 'text/csv',rowDelimiter: '\r\n',});}downloadCSVWithRecommendedSanitization() {const exportPlugin = this.hotTable.hotInstance!.getPlugin('exportFile');exportPlugin.downloadFile('csv', {bom: false,columnDelimiter: ',',colHeaders: false,exportHiddenColumns: true,exportHiddenRows: true,fileExtension: 'csv',filename: 'Handsontable-CSV-file_[YYYY]-[MM]-[DD]',mimeType: 'text/csv',rowDelimiter: '\r\n',sanitizeValues: true,});}downloadCSVWithRegexpSanitization() {const exportPlugin = this.hotTable.hotInstance!.getPlugin('exportFile');exportPlugin.downloadFile('csv', {bom: false,columnDelimiter: ',',colHeaders: false,exportHiddenColumns: true,exportHiddenRows: true,fileExtension: 'csv',filename: 'Handsontable-CSV-file_[YYYY]-[MM]-[DD]',mimeType: 'text/csv',rowDelimiter: '\r\n',sanitizeValues: /WEBSERVICE|CMD|HYPERLINK|^\+/,});}downloadCSVWithFunctionSanitization() {const exportPlugin = this.hotTable.hotInstance!.getPlugin('exportFile');exportPlugin.downloadFile('csv', {bom: false,columnDelimiter: ',',colHeaders: false,exportHiddenColumns: true,exportHiddenRows: true,fileExtension: 'csv',filename: 'Handsontable-CSV-file_[YYYY]-[MM]-[DD]',mimeType: 'text/csv',rowDelimiter: '\r\n',sanitizeValues: (value: string) => {return /WEBSERVICE|CMD|HYPERLINK|^\+/.test(value) ? 'REMOVED SUSPICIOUS CELL CONTENT' : value;},});}}/* end-file *//* file: app.config.ts */import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';import { registerAllModules } from 'handsontable/registry';import { HOT_GLOBAL_CONFIG, HotGlobalConfig } from '@handsontable/angular-wrapper';registerAllModules();export const appConfig: ApplicationConfig = {providers: [provideZoneChangeDetection({ eventCoalescing: true }),{provide: HOT_GLOBAL_CONFIG,useValue: {// license: 'your-license-key', // get a key at https://handsontable.com/pricing/} as HotGlobalConfig,},],};/* end-file */HTML <div><app-example3></app-example3></div>
Result
You can export the grid as a file, a Blob, or a string, choose what the file holds, and keep user-provided values from running as formulas.
Options
Pass these options as the second argument of any export method.
| Option | Type, default | Description |
|---|---|---|
bom | boolean, true | Prepend the UTF-8 byte order mark (EF BB BF). It is prepended to the string exportAsString() returns too. |
colHeaders | boolean, false | Include the column headers. With nested headers, every layer becomes one header line. Column headers are always quoted. See Nested headers. |
rowHeaders | boolean, false | Include the row headers as the first column. |
exportHiddenColumns, exportHiddenRows | boolean, false | Include hidden columns or rows. 'hide', which the XLSX export accepts, counts as false here. |
range | number[], whole grid | [startRow, startColumn, endRow, endColumn] in visual indexes. |
columnDelimiter | string, ',' | Column delimiter. A value that holds it, a double quote, or a line break is quoted. |
rowDelimiter | string, '\r\n' | Row delimiter. |
filename | string, 'Handsontable [YYYY]-[MM]-[DD]' | File name without the extension. The placeholders become the current date. Used by downloadFile() and downloadFileAsync(). |
fileExtension | string, 'csv' | File extension, used by the same two methods. |
mimeType | string, 'text/csv' | MIME type of the Blob. The Blob’s type also carries ;charset= and the encoding option, text/csv;charset=utf-8 by default. |
encoding | string, 'utf-8' | Charset label of the Blob and the download. The content is always UTF-8. |
sanitizeValues | boolean | RegExp | Function, false | true prefixes a value that starts with =, +, -, @, a tab, or a carriage return with ', following the OWASP rules. A RegExp prefixes the values it matches. A function receives the value and returns the replacement. Any of the three also quotes every non-empty cell. |
Nested headers
With the nestedHeaders option, colHeaders: true exports every header layer. Each layer becomes one header line, and a group label repeats across every column it spans, so a spreadsheet shows the group above each of its columns.
const hot = new Handsontable(container, { data: [[1, 2, 3, 4]], colHeaders: true, nestedHeaders: [ [{ label: '2024', colspan: 2 }, { label: '2025', colspan: 2 }], ['Q1', 'Q2', 'Q1', 'Q2'], ],});
hot.getPlugin('exportFile').downloadFile('csv', { colHeaders: true });// The file receives:// "2024","2024","2025","2025"// "Q1","Q2","Q1","Q2"// 1,2,3,4A group shrinks to the columns the export includes, so hidden columns follow exportHiddenColumns. A range that starts inside a group leaves that group’s cells empty on the parent line, so every header line keeps the data’s column count.
Headers as plain text
A column header is also its display string. A header of '<b>Total</b>' renders as Total, but the export writes the value it was given, so the file receives the literal <b>Total</b>. Set the grid’s textExtractor option to true to export the displayed text instead:
const hot = new Handsontable(container, { data: [[1, 2]], colHeaders: ['<b>Total</b>', 'Count'], textExtractor: true,});
hot.getPlugin('exportFile').downloadFile('csv', { colHeaders: true });// The file receives:// "Total","Count"// 1,2textExtractor is a grid option, not an export option. It applies to column, row, and nested headers, in CSV and in Excel. Cell values are left alone: a value such as a<b reaches the file unchanged.
Extraction turns HTML entities back into characters, so a header stored as =SUM(A1) reaches the file as =SUM(A1), which a spreadsheet reads as a formula. Set sanitizeValues when you export headers from untrusted sources. To extract headers differently per surface, pass textExtractor a function (content, source) instead of true; source is 'ExportFile.rowHeader' for a row header and 'ExportFile.columnHeader' for a column header in an export, and 'CopyPaste.columnHeader' when headers are copied. Return content for any other source.
Methods
Each export method takes the format first, 'csv' or 'xlsx', and an options object second.
downloadFile(format, options)- starts a download. Synchronous, CSV only.downloadFileAsync(format, options)- starts a download and returns aPromise. CSV and XLSX.exportAsBlob(format, options)- returns aBlob. CSV only; it throws for'xlsx'.exportAsBlobAsync(format, options)- returns aPromiseof aBlob. CSV and XLSX.exportAsString(format, options)- returns the text. CSV only.supportsExportFormat(format)-truewhen the format can be written.
Related articles
Related guides
Related blog articles
Related API reference
Configuration options
Plugins