CSV, Excel and PDF export
Letting users download the table they see as a file for Excel is a common need. Export lives in the separate @maxgrid/export package, not in the grid bundle. Pass it the grid's api and it builds a CSV, an .xlsx file or a PDF from the current column order and the sorted and filtered rows.
Functions and option types are in the API reference: exportCsv, exportXlsx, exportPdf.
For JSON and XML export and for reading text back into rows, see JSON and XML export and Import and load from a URL.
In the demo, change the department filter and switch Rows between Visible rows and All rows. The preview below updates right away.
Install and use
pnpm add @maxgrid/exportThe package is an optional install that is not part of maxgrid or the wrappers, and you import it in a bundler (Vite, webpack and so on).
import { downloadCsv, downloadPdf, downloadXlsx, exportCsv, exportXlsx } from '@maxgrid/export';
// 1) get a string
const csv = exportCsv(api);
// 2) download a file. Large data is built in chunks so the page does not freeze.
await downloadCsv('employees.csv', api);
// 3) get an Excel file, as bytes (Uint8Array) or as a download
const bytes = exportXlsx(api);
await downloadXlsx('employees.xlsx', api);
// 4) download a PDF. Korean text needs a font (see the PDF section).
await downloadPdf('employees.pdf', api, { font });api is the value createGrid returned. In React, Vue and Angular, get the GridApi and pass it the same way (Get GridApi).
Add the methods to api
Call withExport once and you can call the exports straight from api. The grid bundle contains no export code; only an app that calls this function receives @maxgrid/export.
import { withExport } from '@maxgrid/export';
const grid = withExport(api);
const csv = grid.exportCsv({ rowScope: 'all' });
await grid.downloadXlsx('employees.xlsx');
await grid.downloadPdf('employees.pdf', { title: 'Employees' });Eight methods are added: exportCsv, exportCsvAsync, downloadCsv, exportXlsx, exportXlsxAsync, downloadXlsx, exportPdf and downloadPdf. The arguments are those of the functions above without the source (api), and they read the sort, filter and selection at the moment you call them. Calling it again returns the same object, and a different property with the same name throws a TypeError. It creates no listeners or timers, so there is nothing to clean up when you destroy() the grid.
What comes out
- The first line holds the column titles. The column order follows the order the user arranged.
- Hidden columns are left out. Add them with
includeHidden: true. - Cell values are the displayed text (
formatValue). If an amount shows as4,200,000, the CSV has that too. UseapplyFormatValue: falsefor raw values. - Computed columns (
getValue) export their computed values. - Values with commas, double quotes or line breaks are wrapped in double quotes.
Dateandnullbecome strings by the default rules. Dates use the local calendar date.
Which rows are exported
Set rowScope.
| Value | Rows exported |
|---|---|
'visible' | The sorted and filtered result, in display order. This is the default |
'all' | Every row, regardless of filters |
'selected' | Only the selected rows, in display order |
exportCsv(api, { rowScope: 'all' });
await downloadXlsx('selected-orders.xlsx', api, { rowScope: 'selected' });'selected' follows screen order, not the order the rows were ticked in. A selected row that a filter hides goes at the end. With nothing selected, only the header comes out. When you pass a { columns, rows } object, give the rows in selectedRows.
In a tree or grouped grid, 'visible' is what api.getVisibleRows() returns, which is data rows. Rows hidden by collapsing are left out, and group and total lines are not included. To keep the hierarchy, see Export trees and groups below.
Options
| Option | Default | Meaning |
|---|---|---|
delimiter | , | Field separator, one character. It cannot be " or a line-break character |
newline | \r\n | Line separator, '\r\n' or '\n' |
bom | true | Prepend a UTF-8 BOM. Korean Excel then reads the text correctly |
header | true | Write the column titles on the first line |
includeHidden | false | Include hidden columns |
applyGetValue | true | Use computed columns |
applyFormatValue | true | Use formatValue |
rowScope | 'visible' | Which rows to export: 'visible', 'all' or 'selected' |
hierarchy | off | true exports tree and group rows as they appear on screen. { indent } sets the indent text |
sanitizeFormulas | true | Prefix ' to strings that would be read as a formula |
errorPolicy | 'blank' | What to do when a callback throws. 'blank' empties that cell and goes on, 'abort' stops |
onError | none | Called for each cell error under 'blank'. Without it, the first error of each export goes to console.warn |
locale | 'ko' | Language of error and warning messages ('ko' or 'en'). Use the grid's locale |
downloadCsv and exportCsvAsync also accept chunkSize (default 5000 rows) and signal (to cancel).
Export to Excel (.xlsx)
exportXlsx and downloadXlsx build an .xlsx file with the same api, row scope and column rules. The difference from CSV is that cells have types.
- Numbers and
true/falsebecome number and boolean cells, so Excel can sum them right away. - A
Datebecomes a date-formatted cell. A column withkind: 'date'gets the date only, any other column gets the time too. Excel's serial numbers are off by one day before 1 March 1900 (and cannot go past year 9999), so such dates, whether aDateor a string, go out as the same localYYYY-MM-DDtext. If there are any, you are told once per export (throughonErrorwhen given, otherwise a console warning). - Since 1.5.0, a
kind: 'week'column is written as aYYYY-Wwwtext cell (not a date cell). ADatevalue becomes the ISO week text of the day it belongs to. - Since 1.4.0, the
YYYY-MMstring of akind: 'month'column becomes a date cell on the first day of that month with the formatyyyy-mm. WithdateAsText: trueit is written as text. - Since 1.2.0, the strings
YYYY-MM-DD,HH:mmandYYYY-MM-DD HH:mmin columns withkind: 'date','time'or'datetime'also become date and time cells, so Excel can sort and filter them as dates (in 1.1.0 adatestring was a text cell). A value that cannot be read (2026-02-30,25:99,2026-11-12T09:05:00Z) or text decorated byformatValuegoes out as text as it is. PassdateAsText: trueif you want text. - A column with
formatValuewrites the displayed text (₩4,200) as a text cell. If you need to sum it, export numbers withapplyFormatValue: false. - Strings are never read as formulas, so
sanitizeFormulasis not needed. - The first row is a bold header that stays in place when you scroll. Column widths follow the column's
width, or the content length when there is none.
| Option | Default | Meaning |
|---|---|---|
sheetName | 'Sheet1' | Sheet name, up to 31 characters. [ ] : * ? / \ are replaced with _ |
freezeHeader | true | Freeze the header row. Ignored when header: false |
dateAsText | false | Export date, time and datetime columns as text (the same text as CSV) instead of date cells (1.2.0) |
The rest (rowScope, includeHidden, applyFormatValue, hierarchy, errorPolicy and so on) works as in CSV. delimiter, newline, bom and sanitizeFormulas do not exist for xlsx.
await downloadXlsx('orders.xlsx', api, { sheetName: 'March orders', applyFormatValue: false });exportXlsx is synchronous and writes an uncompressed ZIP, so the file is larger than the CSV (about 7 times for a four-column table of 5,000 rows). When size matters, use exportXlsxAsync: it compresses each file with deflate, making it about 10 times smaller for the same table (scripts/pdf-size-claims.test.mjs checks the ratios; compress: false turns it off, and signal cancels). downloadXlsx always downloads the compressed file, and writes it uncompressed where CompressionStream is missing.
A sheet holds up to 1,048,576 rows and 16,384 columns, a cell up to 32,767 characters; beyond that it throws a RangeError. Even within those limits, a sheet whose XML goes past about 200 MB (about 400 MB for the whole file) stops with the same RangeError before it reaches the browser's string limit. You meet this with many columns and very many rows; export CSV then. For several hundred thousand rows, downloadCsv freezes the page less.
Put several sheets in one file
Since 1.2.0
sheets and xlsxSheet are available since 1.2.0. A 1.1.0 file has one sheet.
ordersApi and branchesApi are the api values of two grids. A source may also be a { columns, rows } object.
Put xlsxSheet(name, source, options) values in sheets to add sheets after the first one. The first sheet is still set by the first argument and sheetName.
import { downloadXlsx, xlsxSheet } from '@maxgrid/export';
await downloadXlsx('orders.xlsx', ordersApi, {
sheetName: 'Orders',
sheets: [xlsxSheet('Branches', branchesApi)],
});- The source is an
apior{ columns, rows }. Each sheet can have its own row type. header,includeHidden,applyGetValue,applyFormatValue,rowScope,hierarchy,errorPolicy,onError,localeandfreezeHeaderare inherited from the outer options. Change them per sheet in the third argument ofxlsxSheet. Options tied to the row type (cellStyle,merges,cellImage,numberFormats) are not inherited, so give them per sheet.- The first sheet keeps the old rules (an empty name becomes
Sheet1, a name over 31 characters is cut). An extra sheet with an empty name or one over 31 characters throwsTypeError.[ ] : * ? / \and control characters become_, and so do apostrophes at the start or end of a name. - Names that differ only in case are the same name, and a repeat throws
TypeError. The nameHistory, which Excel reserves, is not allowed either. Names are checked before the file is built, so nothing is produced when one is wrong. - Up to 255 sheets. If one sheet goes over the row or column limit, the whole file fails with
RangeError. - Without
sheetsthe file is the same as before.exportXlsxAsyncanddownloadXlsxtake the same options.
See the gallery example xlsx-multi-sheet.
Number formats
Since 1.2.0
numberFormats is available since 1.2.0. In 1.1.0 the display text from formatValue is exported as a string cell.
api is the value the grid returned.
Pair a column id with an Excel format code in numberFormats and the number cells of that column get the format. The number itself is exported, not the display text, so sums and sorting work in Excel.
import { downloadXlsx } from '@maxgrid/export';
await downloadXlsx('orders.xlsx', api, {
numberFormats: {
price: '#,##0', // 1234567 -> 1,234,567
rate: '0.0%', // 0.153 -> 15.3%
amount: '"$"#,##0.00;[Red]-"$"#,##0.00', // currency, negatives in red
},
});| Format code | Looks like |
|---|---|
#,##0 | 1,234,567 |
#,##0.00 | 1,234,567.00 |
0.0% | 15.3% (value 0.153) |
"₩"#,##0 | ₩1,234,567 |
$#,##0.00 | $1,234,567.00 |
- For a column with a format, number values skip
formatValueandaggregateFormatand are exported as the original number (an empty value stays an empty cell). A non-number value (text, a date and so on) gets no format and goes out as the display textformatValuemakes.getValuestill applies. Use a percent format on ratio values such as0.153. - The format goes only on finite number cells. Strings, booleans and headers stay as they are, and
null,NaNandInfinitybecome empty cells. ADategets no format and is exported as a local calendar date, as before. The aggregate numbers in group rows and total rows get the format. - If an id in
numberFormatsmatches no column (a typo), no format is applied and you are told once per export (throughonErrorwhen given, otherwise a console warning). The id of a hidden column is not treated as a typo. With several sheets, give it per sheet. At most 200 different format codes can be used (Excel's custom-format limit). - A format code that is empty, over 255 characters, contains a control character, leaves a quote or bracket open, or has more than 4 sections (
;) throwsTypeError, and no file is produced. Excel interprets the rest of the syntax, so open a new code once in Excel to check it.
See the gallery example xlsx-number-format.
Header groups and merged groups (xlsx only)
Since 1.5.0
headerGroups and mergedGroups are available since 1.5.0. Both are off by default, and without them the file is byte-identical to 1.4.0. CSV, PDF, JSON and XML do not have these options.
ex.exportXlsx({ headerGroups: true }); // on-screen header groups as a multi-row header
ex.exportXlsx({ mergedGroups: true }); // grouping.merged group cells as vertical merges| Option | Value | Behavior |
|---|---|---|
headerGroups | boolean (default false) | Writes the header as one row per group layer. A group title is written once and merged horizontally over its visible children; column headers merge vertically down to the last row |
mergedGroups | boolean (default false) | For grids with grouping.merged, merges each group column cell over the rows of its group. The value is in the first cell and no group header lines are written |
- What
headerGroupschanges:freezeHeaderfreezes below the whole header block (3 rows if the block has 3). Row numbers in your datamergesstay data-relative and sit below the header rows in the sheet. Image positions and the row limit (1,048,576 rows) count the header rows too.headerStyleapplies to every cell of the block, andrightToLeftandnumberFormatskeep working. - What follows the screen: a collapsed group exports only its first visible column, as on screen (its sub-group row disappears, and the columns hidden by the collapse are left out with their data), and
headerSpan.rowsandheaderSpan.colsare honored as on screen. Hidden columns followincludeHidden. If the columns of one group are apart, each piece is merged. - Grids only: groups are read from the
api. With a{ columns, rows }pair both options are ignored. mergedGroups: ignored unless the grid usesgrouping.merged. With three group levels each column merges the consecutive rows whose values up to that column are all equal. A summary row breaks the merge.- Several sheets: like
freezeHeader, sheets inherit both options from the outer call, andxlsxSheetcan change them per sheet in its third argument. They can also live inexportDefaults.xlsx.
Header groups example, Merged groups example
Cell colors and merging (xlsx and PDF)
cellStyle, headerStyle and merges work the same in xlsx and PDF.
await downloadXlsx('sales.xlsx', api, {
headerStyle: { background: '#1f3864', color: '#ffffff' },
// Style cell by cell. Return nothing for the default look.
cellStyle: ({ kind, column, row }) =>
kind === 'data' && column.id === 'amount' && row.amount > 3_000_000
? { color: '#c00000', background: '#fff2cc', bold: true }
: undefined,
// Data row and column numbers (0-based, header excluded): join the first two cells of the third row.
merges: [{ row: 2, column: 0, colSpan: 2 }],
});cellStylereceives{ kind, column, columnIndex, rowIndex, value, row }.kindis'header','data','group'or'summary', androwIndexis-1for the header.valueis the exported value, so it is the displayed text whenformatValueran. Readrow(the source row of a data line) when you need the original number.- Colors accept
#RGBor#RRGGBBonly. Any other format throws aRangeError(a value returned by your callback followserrorPolicy). headerStyleis laid over the default header (bold, light grey background).- In
merges,rowcounts data rows without the header (0-based) andcolumncounts exported columns. A range outside the table or overlapping another throws aRangeErrorbefore anything is built. A merged area keeps only the value of its top-left cell. - Both xlsx and PDF support
rowSpan(vertical) andcolSpan(horizontal). In a PDF, rows joined vertically are kept together on one page. When such a block is taller than a page, the merge is not applied: the rows are drawn separately andonWarninggetsmerge-ignored.
Formulas and total formulas (xlsx only)
Since 1.6.0
formulas, xlsxFormulas and footerFormulas are available since 1.6.0. All are off by default, and without them the file is byte-identical to 1.5.0.
Export Excel formulas instead of values so Excel recalculates when you edit. The original value is stored as the cached result, so viewers that do not recalculate still show numbers.
const columns = [
{ id: 'qty', title: 'Qty', kind: 'number', aggregate: 'sum' },
{ id: 'price', title: 'Price', kind: 'number' },
// The row number (n) is the sheet row. With startRow it shifts by the same amount.
{
id: 'amount',
title: 'Amount',
kind: 'number',
aggregate: 'sum',
xlsxFormula: (row, n) => `B${n}*C${n}`,
},
];
ex.exportXlsx({ formulas: true, footerFormulas: true });
// When you cannot change the column definitions: { formulas: true, xlsxFormulas: { amount: (row, n) => `B${n}*C${n}` } }| Option | Value | Behavior |
|---|---|---|
formulas | boolean (default false) | Writes the data cells of columns that have a formula function as formulas |
xlsxFormulas | { [columnId]: (row, rowNumber) => text } | A formula function per column id. It wins over the column's xlsxFormula. Return the text without the leading = |
footerFormulas | boolean (default false) | Writes sum, avg, min, max and count in total and subtotal rows as formulas like SUM(C2:C101) (not SUBTOTAL). Total and subtotal rows only exist in a hierarchy export, so it is switched on with this option unless you set hierarchy yourself |
- If a formula function throws or returns a non-string,
errorPolicyapplies and the cell is written as a value. - In a grouped table the total row cannot be told apart from subtotals, so it is not converted. A group row uses only the data rows of that group as its range.
Cell notes (xlsx only)
Since 1.6.0
notes is available since 1.6.0. It is off by default.
Export the grid's cell notes (cellNotes, setCellNote) as Excel notes (comments).
api.setCellNote(1, 'score', 'Raised by 5 points after the re-review.');
ex.exportXlsx({ notes: true });- Only notes on exported cells are written. Notes on filtered-out rows or hidden columns are not.
- It works only when you pass the grid (
api). With a columns and rows pair, or when there are no notes, no notes part is written.
Sheet protection (xlsx only)
Since 1.6.0
protect is available since 1.6.0. Sheets are not protected by default.
This is not security
The password is stored as Excel's old 16-bit hash, so anyone can remove it easily. Use it to prevent accidental edits; it cannot hide or safeguard values.
ex.exportXlsx({
protect: { password: 'abc', lockedColumns: ['code', 'name'], allowSort: true },
});| Option | Value | Behavior |
|---|---|---|
password | string (255 chars or less) | The unprotect password. Without it the sheet is protected without a password |
lockedColumns | array of column ids | Locks only those columns and unlocks the other body cells. If omitted, every cell is locked. The header is always locked |
allowSort | boolean (default false) | Allows sorting while protected |
allowFilter | boolean (default false) | Allows the auto filter while protected |
Protection applies to the first sheet only.
Extra cells and the start row (xlsx only)
Since 1.6.0
extraCells and startRow are available since 1.6.0. By default the table starts at row 1 and there are no cells outside it.
Use them to put a title or a date above the table.
ex.exportXlsx({
startRow: 3, // the header starts at row 3
extraCells: [
{
ref: 'A1',
value: 'Sales by region',
style: { bold: true, color: '#1F4E79', fill: '#DDEBF7' },
},
{ ref: 'A2', value: new Date(2026, 10, 25), style: { numFmt: 'yyyy-mm-dd' } },
],
});| Option | Value | Behavior |
|---|---|---|
startRow | integer 1 to 1,048,576 (default 1) | The row where the table (header, body, merges, freeze, images) starts. The row number given to xlsxFormula shifts too |
extraCells | { ref, value, style? }[] | ref is A1 notation; value is text, number, boolean or Date. style takes bold, color, fill (#RRGGBB) and numFmt |
A cell that overlaps the table, or the same cell twice, is an error (thrown before anything is built).
Export to PDF
exportPdf and downloadPdf build a table PDF from the same api, row scope and column rules. The PDF writer is built in, so there is no dependency, and the file is made in the browser (nothing is sent to a server).
import { downloadPdf, exportPdf } from '@maxgrid/export';
const bytes = await exportPdf(api, { orientation: 'landscape' }); // Uint8Array
await downloadPdf('orders.pdf', api, { pageSize: 'Letter', title: 'March orders' });Unlike CSV, both are asynchronous. They build chunkSize rows (2,000 by default) at a time, yield to the page in between, and can be cancelled with signal (the promise rejects with signal.reason).
- The header row repeats at the top of every page, and a page number such as
1 / 3sits at the bottom centre. - Column widths follow each column's
width(100 when missing) as a ratio of the page width. With many columns the text gets narrow, so useorientation: 'landscape'or a smallerfontSize. - Numbers are right-aligned (an explicit
alignwins). Dates use the local calendar date, and any column that is notkind: 'date'also shows the time (2025-03-04 09:05). - Long text wraps at spaces and between Korean characters (
overflow: 'wrap', up tomaxCellLineslines, then...).'ellipsis'keeps one line. A row is never split across pages. rowScope('visible','all','selected') andhierarchywork as in xlsx. Group and total rows come out as grey bands, and rows inside a tree or group are indented 10 pt per level. Collapsed branches are left out, so callapi.expandAll()first.formatValue,errorPolicyandonErroralso work as in CSV and xlsx.
| Option | Default | Meaning |
|---|---|---|
pageSize | 'A4' | Paper: 'A4' or 'Letter' |
orientation | 'portrait' | 'portrait' or 'landscape' |
margin | 36 | Margin on all four sides, in pt |
fontSize | 9 | Body font size, in pt |
font | auto-detect | TTF bytes or koreanFont. false keeps Helvetica only |
cellStyle | none | Cell colors and bold (same as xlsx) |
headerStyle | none | Header look |
merges | none | Cell merging (horizontal and vertical) |
cellImage | none | Cell images (PNG, JPEG) |
imageHeight | 48 | Height of an image cell, in pt |
title | none | Title drawn above the first page and stored in the document info |
author | none | Author in the document info |
pageNumbers | true | Draw page numbers |
overflow | 'wrap' | Long text: 'wrap' or 'ellipsis' |
maxCellLines | 6 | Most lines in one cell |
compress | true | Compress streams. Falls back to uncompressed where it is not supported |
maxRows | 100000 | Row limit. More rows throw a RangeError. The hard ceiling is 1,000,000 |
onWarning | none | Warning callback. Without it, the first warning goes to console.warn |
chunkSize | 2000 | Rows built per chunk |
signal | none | Cancel signal |
Korean text and fonts
The default PDF font (Helvetica) has no Korean glyphs, so Korean needs a font inside the PDF. The package @maxgrid/export-font-ko supplies one: the unmodified Noto Sans KR (SIL OFL 1.1), loaded only when a PDF with Korean text is built. Neither the grid bundle nor @maxgrid/export contains the font.
pnpm add @maxgrid/export-font-koimport { koreanFont } from '@maxgrid/export-font-ko';
await downloadPdf('employees.pdf', api, { font: koreanFont, title: 'Employees' });koreanFontreads the font file (about 10.4 MB) once, when it is first needed, and remembers it. A table with no Korean never reads it. The PDF embeds only the glyphs the document uses, so it stays small (for a table with four columns — number, name, department, amount — about 8.7 KB for 3 rows and 223 KB for 5,000 rows; for two columns and 100 rows with 2,000 different Hangul syllables, about 300 KB).scripts/pdf-size-claims.test.mjsbuilds the same tables and checks these within ±5%. More columns and more varied text make it larger.- Where bold is needed (header, total rows,
bold: true), the PDF embeds weight 700 of the variable font as a second subset. Regular text uses weight 400. - To load the font from somewhere else, use
createKoreanFont({ url: '/fonts/NotoSansKR%5Bwght%5D.ttf' }). The file is in the package'sfonts/folder, unrenamed and unprocessed. - With a script tag, load
maxgrid.export-font-ko.min.js(it creates the globalMaxGridExportFontKo). It fetches the font from the../fonts/folder next to that file and, if it is not there, from the same version of the package on jsDelivr. Load the file from the npm path on jsDelivr or unpkg (https://cdn.jsdelivr.net/npm/@maxgrid/export-font-ko@<version>/dist/maxgrid.export-font-ko.min.js); it is not on the docs-site CDN.
When you do not pass font, this is what happens.
- The PDF is built with Helvetica first. If it holds only English letters and digits, that is the result and the font package is never touched.
- If some characters cannot be drawn, the export looks for a font package: the Korean font when Hangul (or kana) is missing, the Simplified Chinese font (
@maxgrid/export-font-sc) when Han characters are missing, and both in a chain when both are needed. It checks the globalsMaxGridExportFontKoandMaxGridExportFontScfrom script tags first, then the package names.getValue,formatValueandcellStylerun once more in that case. Bundlers (Vite, webpack) do not follow this name, so in a bundled app passfont: koreanFontyourself. - If it finds none, the characters become
?andonWarninggets{ code: 'missing-glyph', characters, suggest: '@maxgrid/export-font-ko' }once (console.warnwhen there is noonWarning). The message says how to install it. - If it finds the package but cannot read it (a network error, for example), the export does not stop: it builds with Helvetica and reports
code: 'font-unavailable'with the reason.
Pass font: false to turn auto-detection off. With locale: 'en' the warnings are in English.
To use your own font, pass the bytes of a TrueType (.ttf) file as font.
const font = new Uint8Array(await (await fetch('/fonts/MyFont.ttf')).arrayBuffer());
await downloadPdf('orders.pdf', api, {
font,
onWarning: (warning) => console.warn(warning.message),
});- Only the glyphs the document uses are embedded (a subset). Copying and searching text work.
- A variable font (
wghtaxis) uses 400 for regular and 700 for bold. A font without the axis has no bold face, so bold text is drawn by overprinting the glyphs. - The supported format is a
.ttfwith TrueType outlines (glyf). OpenType CFF (.otf),.ttccollections and.woffare rejected with aRangeError. - A character that the font does not have becomes
?and is reported throughonWarning. - The font file is treated as untrusted input and every length and position is range-checked. A broken file ends in a
RangeErrorbefore anything is built. - Check the licence of your own font. Make sure its terms allow embedding part of it in a PDF. The font in
@maxgrid/export-font-kois under the SIL OFL 1.1; the notices are on the license page.
Simplified Chinese and other characters missing from the font
The font in @maxgrid/export-font-ko (Noto Sans KR) has no characters that exist only in Simplified Chinese (简, 际, 说), so they become ? in the PDF. Install the Simplified Chinese font package @maxgrid/export-font-sc (the unmodified Noto Sans SC, SIL OFL 1.1) next to it and pass the fonts as a chain in font. For each character the PDF uses the first font that has it, so a table with Korean and Simplified Chinese together comes out in one PDF.
pnpm add @maxgrid/export-font-scimport { downloadPdf } from '@maxgrid/export';
import { koreanFont } from '@maxgrid/export-font-ko';
import { simplifiedChineseFont } from '@maxgrid/export-font-sc';
// A later font is used only for characters the earlier one lacks. Put koreanFont first for a table with Korean.
await downloadPdf('订单.pdf', api, {
font: [koreanFont, simplifiedChineseFont],
onWarning: (warning) => console.warn(warning.code, warning.characters),
});simplifiedChineseFontreads its file (about 17.8 MB) once, the first time it is needed. A table without Simplified Chinese never reads it, and the PDF embeds only the glyphs it uses. This font has no Hangul. With both (font: [koreanFont, simplifiedChineseFont]), the glyphs of both fonts go into one PDF. Two columns and 3 rows (a Korean and a Simplified Chinese name) take about 9.7 KB; the same table with 100 rows holding 2,000 different Hangul syllables and 2,000 different Han characters takes about 828 KB (the same test checks it).- A table with only Simplified Chinese can pass
font: simplifiedChineseFontalone. Some Korean-form and Simplified characters share a code point but are drawn differently (直, 骨), so put the font for the document's main language first. - When you pass no
font, a missing Hangul loads the Korean font and a missing Han character loads the Simplified Chinese font, and the PDF is rebuilt once. With a script tag, loadmaxgrid.export-font-sc.min.jsfrom jsDelivr or unpkg (it creates the globalMaxGridExportFontSc), and pin an exact version:https://cdn.jsdelivr.net/npm/@maxgrid/export-font-sc@<version>/dist/maxgrid.export-font-sc.min.js. This file and the font file are not on the docs-site CDN (grid.maxmine.com/cdn,cdn.maxmine.com); the font is fetched from thefonts/folder of the same jsDelivr package. The loader checks the font's size and SHA-256; where SHA-256 is unavailable (for example anhttp:page) it checks the size only, andMaxGridExportFontSc.verifiedreports'size'. - Characters that neither font has (Arabic, Hebrew, Thai, emoji and so on) still become
?. - To use your own font, pass its
.ttfbytes: it can sit in the chain too, as infont: [koreanFont, ttfBytes].
The characters of the missing-glyph warning names the characters that no font had. When a Simplified Chinese font is needed and missing, the warning's suggest names @maxgrid/export-font-sc. CSV and Excel do not use a font, so they are not affected. Check the licence of your font as described above.
The first time, the fonts are downloaded
A font file is downloaded once, the first time a PDF has Hangul or Simplified Chinese. The Korean font is 10,414,588 bytes (about 10.4 MB) and the Simplified Chinese font 17,772,300 bytes (about 17.8 MB), so about 28.2 MB together. On a 10 Mbps connection that is about 23 seconds for the file size alone (a calculation that ignores compression); from the second one on the browser remembers the files and PDFs are made right away. Show a "building" message on screen and tell people it can take a while.
When a font cannot be downloaded (offline, server error) and you passed the font in font yourself, the export function ends with an error. No PDF is made, and the error's message says why. With auto-detection (no font), there is no error: the PDF is made with the default Latin font and a font-unavailable warning is reported.
try {
await downloadPdf('订单.pdf', api, { font: [koreanFont, simplifiedChineseFont] });
} catch (error) {
// When a font cannot be downloaded, no PDF is made and you land here. The message says why.
showMessage(
`The fonts could not be downloaded: ${error instanceof Error ? error.message : error}`,
);
}With a script tag, the font files are not on the docs host CDN. Put them in a fonts/ folder next to the script yourself; if you do not, they are downloaded from jsDelivr (npm). If you put them somewhere else, tell the loader before first use with MaxGridExportFontSc.config.url.
When your server or CDN serves the font files, do not put an immutable cache header on error responses (503, 404 and so on). The browser would remember the failed response for a long time, so pressing the button again keeps failing even after the server is back. With nginx, send Cache-Control: public, max-age=31536000, immutable for the font files only on success (200) responses, and set the CDN not to cache error responses.
Cell images (xlsx and PDF)
cellImage picks an image for each cell. Return PNG or JPEG bytes, or a base64 data: URL. An image cell usually needs no text, so leave the column's value empty.
const logos = new Map<string, Uint8Array>(); // image bytes your app already fetched
await downloadPdf('partners.pdf', api, {
imageHeight: 40, // height of an image cell in pt; the row height follows it
cellImage: ({ column, row }) => (column.id === 'logo' ? logos.get(row?.code ?? '') : null),
});- You pass the bytes. An address such as
https://…throws aTypeError. The library never fetches anything (this avoids server-side request forgery and CORS problems). - The format is decided by the first bytes (the signature), not by a file name or MIME type. Anything that is not PNG or JPEG (SVG, GIF and so on) is rejected.
- There are size limits:
maxImageBytesper image (5 MB by default), 20,000 px per side, 16 million pixels in total, andmaxImagesdifferent images (500 by default). The same image (the same object or string) is stored once in the file. - A bad image skips only that cell and follows
errorPolicy(by defaultonError, or one console warning).'abort'stops the export. - An image is fitted inside the cell width and
imageHeight, keeping its proportions, and is never enlarged beyond its own size. - Supported: JPEG (baseline and progressive, 8-bit) and PNG (gray, RGB, palette, and 8-bit with alpha). Interlaced PNG, 16-bit PNG with alpha and CMYK JPEG cannot be drawn in a PDF, so that cell is skipped. Transparency in a palette PNG comes out opaque in a PDF.
- xlsx stores the image bytes as they are. A PDF stores JPEG and PNG without alpha as they are, without re-encoding; only PNG with alpha is split into color and alpha (this needs
DecompressionStream).
Large data
When there are more rows than maxRows (100,000 by default), a RangeError is thrown before anything is built. The page count and memory grow with the rows, so for several hundred thousand rows CSV or xlsx is a better fit. You can raise the limit, but 1,000,000 rows is the hard ceiling.
Save as PNG
Since 1.6.0
exportPng and downloadPng are available since 1.6.0.
Turn the grid into an image from an api extended with withExport. It uses the browser canvas and adds no dependency.
const blob = await ex.exportPng({ scope: 'all', scale: 2, background: '#ffffff' }); // Blob
await ex.downloadPng('sales.png', { scale: 3 });| Option | Value | Behavior |
|---|---|---|
scope | 'view' | 'all' (default 'view') | 'view' is the current screen, 'all' is every row after sorting and filtering (up to 5000 rows) |
scale | 1 | 2 | 3 (default 2) | Multiplier of the screen size |
background | CSS color | Colour painted behind and under the grid. Cells, stripes and the header keep their theme colours. Falls back to the grid background, then white |
filename | string | Default file name |
onError | function | Receives warnings such as skipped images and truncated rows. Without it, console.warn |
- Background:
backgroundonly paints behind and under the grid. Text, stripes and the header keep the grid's theme colours, so for a dark background export from a grid that uses a dark theme or the text will not be readable. - Fonts: only same-origin (self-hosted) fonts are drawn. Fonts from other origins may fall back to the default font.
- Images: cross-origin images without CORS headers would taint the canvas, so they are skipped and reported through
onError. - Canvas size limit: a side over 16,384 px or more than 100 million pixels throws a
RangeError. With many rows, lowerscaleor usescope: 'view'.
Print
Since 1.6.0
api.print is available since 1.6.0.
Builds a print table in a hidden iframe and opens the browser print dialog. Other elements of the page do not leak into the printout.
await ex.print({
scope: 'all',
orientation: 'landscape',
title: 'Order list',
header: 'MaxGrid · Orders',
footer: 'Page {page} of {pages}',
rowsPerPage: 24,
});| Option | Value | Behavior |
|---|---|---|
scope | 'view' | 'all' (default 'view') | The visible rows, or every row after sorting and filtering |
orientation | 'portrait' | 'landscape' (default 'portrait') | A4 paper orientation |
title | string | Title at the top of every page |
header, footer | string | Page header and footer. {page} and {pages} are the page number and the page count |
repeatHeader | boolean (default true) | Repeats the table header on each page |
fitWidth | boolean (default true) | Fits the table to the paper width |
rowsPerPage | integer 1 to 1000 (default 38 portrait, 24 landscape) | Rows on one page |
Browser settings may block the print dialog.
Set the export per column
A column's export changes how it is exported only. The on-screen formatValue and format stay as they are.
| Setting | Effect |
|---|---|
export.value(value, row) | Text or number used instead of formatValue and format in CSV, Excel and PDF; null is an empty cell |
export.xlsx.numeric | true exports number cells (summary rows too); false turns off the call's numberFormats |
export.xlsx.numberFormat | Excel format code for this column; giving it exports number cells |
export.xlsx.date | 'text' writes this column's dates as text; 'cell' keeps date cells even with the call's dateAsText |
export.xlsx.text | true writes numbers as text cells too (leading zeros kept) |
{ id: 'code', export: { xlsx: { text: true } } },
{ id: 'amount', format: { number: { decimals: 0, grouping: true, prefix: '₩' } },
export: { xlsx: { numeric: true } } }, // builds the code "₩"#,##0 and writes number cells
{ id: 'status', export: { value: (v) => (v === 'paid' ? 'Paid' : 'Open') } },- With
numeric: trueand nonumberFormat, the code is built fromformat.number.decimalsdecides the digits; without it the code isGeneral. A prefix or suffix becomes quoted text, andnegative: 'parens'makespositive;(positive). When there is nothing to build, number cells are written without a format. - Column settings win over the call's
numberFormatsanddateAsText. A bad format code throws aTypeErrorthat names the column id. numericandtextcannot both betrue(invalid-option).export.valuemay return only a string, a finite number ornull. Any other value is handled like a throw: the cell is left empty andonErroris told.- If
export.valuethrows, that cell is empty andonErroris told.
Set export defaults once
Write default options per format in exportDefaults, and api.exportCsv(), exportXlsx(), exportPdf() and the download* methods start from them.
createGrid(el, {
/* ... */
exportDefaults: { csv: { delimiter: ';', bom: false }, xlsx: { sheetName: 'Orders' } },
});An option passed on the call overrides the default, key by key. A key passed as undefined counts as not passed. Defaults are per format, so CSV defaults do not touch Excel. When you pass a plain table object instead of api, there are no defaults. An unknown option name throws a TypeError when you export. An extra sheet made with xlsxSheet starts from the exportDefaults of its own source grid, then the outer call, then the sheet options.
Stored-format date columns
A date column with format.date.stored is exported as the standard value (2026-03-05), not the string held in the row (20260305). A stored value that does not fit the shape becomes an empty cell.
Export trees and groups
hierarchy: true exports the lines as they appear on screen. (PDF follows the same rules.)
- Tree parents and children, group rows and the total row are all included. The first column is indented by depth: with spaces in CSV (two by default) and with cell indent formatting in xlsx.
- A group row puts the label and row count in the first column, such as
Sales (2), and the aggregate values in the aggregate columns.aggregateFormatis used when present. The total row works the same way. - Collapsed branches are left out. Call
api.expandAll()first to export everything. - It only applies with
rowScope: 'visible'(the default).'all'and'selected'export flat rows. - Formula protection applies to the text before the indent is added.
- Since 1.2.0 the names of the total row ("Total"), of a group subtotal ("A Subtotal") and of an empty group ("(Empty)") follow the grid
locale(in Korean합계,A 소계,(비어 있음)). Passtextsto change them.{label}is the group name.
exportCsv(api, {
hierarchy: true,
texts: { summaryTotal: 'All', summarySubtotal: '{label} sum', summaryEmpty: 'Unsorted' },
});api.expandAll();
await downloadXlsx('org-chart.xlsx', api, { hierarchy: true });
exportCsv(api, { hierarchy: { indent: ' ' } });Open in Korean Excel
Excel reads UTF-8 CSV files without a BOM as CP949 and garbles Korean. With bom: true (the default) that does not happen. If another program dislikes the BOM, turn it off with bom: false. For Excel in a locale that uses ; as the separator, use delimiter: ';'.
Block formula injection
Excel can run a cell as a formula when its value starts with =, +, -, @, a tab or a carriage return. Exporting user input as it is can therefore run a malicious formula, so by default (sanitizeFormulas: true) a ' is placed in front of such strings. Plain numbers such as -5 are left alone.
To decide per column, pass a function. Returning true adds the ', and false keeps the text as it is.
exportCsv(api, {
sanitizeFormulas: (text, column) => column.id !== 'formula', // leave only the formula column untouched
});Even when you trust your data, leaving this on is the safer choice.
Large data and cancelling
exportCsv is synchronous, so hundreds of thousands of rows can freeze the page for a moment. Use the asynchronous versions then. They build chunkSize rows at a time and yield to the page in between.
const controller = new AbortController();
cancelButton.onclick = () => controller.abort();
try {
await downloadCsv('big.csv', api, { signal: controller.signal });
} catch (error) {
if (!controller.signal.aborted) throw error; // rethrow anything that is not a cancel
}exportCsvAsync(api, options)returns the string throughawait.exportCsvChunks(api, options)yields pieces forfor await. Use it to stream to a server.- When cancelled, the promise rejects with
signal.reason.
File names
downloadCsv, downloadXlsx and downloadPdf clean the file name: path characters (/ \ : * ? " < > |), control characters and Windows reserved names (con, nul and so on) are replaced, and the extension (.csv, .xlsx or .pdf) is guaranteed. Building the name from user input is safe. Call sanitizeFilename on its own when you only want the cleaned name. Calling downloadCsv where there is no DOM, such as during server rendering, rejects. Importing the package is safe on a server.
Common pitfalls
Korean text is garbled. The file was built with bom: false, or another tool stripped the BOM. Build it again with the defaults.
I filtered the grid but everything is exported. Check that you did not pass rowScope: 'all'. The default is visible rows only.
I want to export only the selected rows. Use rowScope: 'selected'. If the file holds only the header, no row was selected.
The tree export is missing rows. Collapsed branches are left out. Call api.expandAll(), then export with hierarchy: true.
Excel will not sum a column. A cell with formatValue applied is text. Export with applyFormatValue: false to get number cells.
A cell fails and the export still finishes. The default errorPolicy is 'blank', so only that cell is emptied and one warning goes to the console. Use 'abort' to stop at the first failure.
Korean text shows as ? in the PDF. There is no font, or the font lacks the character. Install @maxgrid/export-font-ko and pass font: koreanFont, or pass .ttf font bytes. In a bundled app auto-detection cannot reach the package, so pass it yourself.
The PDF text is too small. The columns were fitted to the page width. Try orientation: 'landscape', a smaller fontSize or margin, or fewer columns.
The PDF is huge or throws a RangeError. There are more rows than maxRows. Filter them down, or use CSV or xlsx.
Not available yet. Links and vertical text in PDF, complex scripts such as Arabic, and GIF, SVG or WebP images.