Skip to content

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.

Live demo — drawn by the real renderer

Install and use ​

bash
pnpm add @maxgrid/export

The 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).

ts
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.

ts
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 as 4,200,000, the CSV has that too. Use applyFormatValue: false for raw values.
  • Computed columns (getValue) export their computed values.
  • Values with commas, double quotes or line breaks are wrapped in double quotes.
  • Date and null become strings by the default rules. Dates use the local calendar date.

Which rows are exported ​

Set rowScope.

ValueRows 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
ts
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 ​

OptionDefaultMeaning
delimiter,Field separator, one character. It cannot be " or a line-break character
newline\r\nLine separator, '\r\n' or '\n'
bomtruePrepend a UTF-8 BOM. Korean Excel then reads the text correctly
headertrueWrite the column titles on the first line
includeHiddenfalseInclude hidden columns
applyGetValuetrueUse computed columns
applyFormatValuetrueUse formatValue
rowScope'visible'Which rows to export: 'visible', 'all' or 'selected'
hierarchyofftrue exports tree and group rows as they appear on screen. { indent } sets the indent text
sanitizeFormulastruePrefix ' 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
onErrornoneCalled 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/false become number and boolean cells, so Excel can sum them right away.
  • A Date becomes a date-formatted cell. A column with kind: '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 a Date or a string, go out as the same local YYYY-MM-DD text. If there are any, you are told once per export (through onError when given, otherwise a console warning).
  • Since 1.5.0, a kind: 'week' column is written as a YYYY-Www text cell (not a date cell). A Date value becomes the ISO week text of the day it belongs to.
  • Since 1.4.0, the YYYY-MM string of a kind: 'month' column becomes a date cell on the first day of that month with the format yyyy-mm. With dateAsText: true it is written as text.
  • Since 1.2.0, the strings YYYY-MM-DD, HH:mm and YYYY-MM-DD HH:mm in columns with kind: 'date', 'time' or 'datetime' also become date and time cells, so Excel can sort and filter them as dates (in 1.1.0 a date string was a text cell). A value that cannot be read (2026-02-30, 25:99, 2026-11-12T09:05:00Z) or text decorated by formatValue goes out as text as it is. Pass dateAsText: true if you want text.
  • A column with formatValue writes the displayed text (₩4,200) as a text cell. If you need to sum it, export numbers with applyFormatValue: false.
  • Strings are never read as formulas, so sanitizeFormulas is 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.
OptionDefaultMeaning
sheetName'Sheet1'Sheet name, up to 31 characters. [ ] : * ? / \ are replaced with _
freezeHeadertrueFreeze the header row. Ignored when header: false
dateAsTextfalseExport 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.

ts
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.

ts
import { downloadXlsx, xlsxSheet } from '@maxgrid/export';

await downloadXlsx('orders.xlsx', ordersApi, {
  sheetName: 'Orders',
  sheets: [xlsxSheet('Branches', branchesApi)],
});
  • The source is an api or { columns, rows }. Each sheet can have its own row type.
  • header, includeHidden, applyGetValue, applyFormatValue, rowScope, hierarchy, errorPolicy, onError, locale and freezeHeader are inherited from the outer options. Change them per sheet in the third argument of xlsxSheet. 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 throws TypeError. [ ] : * ? / \ 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 name History, 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 sheets the file is the same as before. exportXlsxAsync and downloadXlsx take 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.

ts
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 codeLooks like
#,##01,234,567
#,##0.001,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 formatValue and aggregateFormat and 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 text formatValue makes. getValue still applies. Use a percent format on ratio values such as 0.153.
  • The format goes only on finite number cells. Strings, booleans and headers stay as they are, and null, NaN and Infinity become empty cells. A Date gets 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 numberFormats matches no column (a typo), no format is applied and you are told once per export (through onError when 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 (;) throws TypeError, 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.

ts
ex.exportXlsx({ headerGroups: true }); // on-screen header groups as a multi-row header
ex.exportXlsx({ mergedGroups: true }); // grouping.merged group cells as vertical merges
OptionValueBehavior
headerGroupsboolean (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
mergedGroupsboolean (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 headerGroups changes: freezeHeader freezes below the whole header block (3 rows if the block has 3). Row numbers in your data merges stay 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. headerStyle applies to every cell of the block, and rightToLeft and numberFormats keep 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.rows and headerSpan.cols are honored as on screen. Hidden columns follow includeHidden. 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 uses grouping.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, and xlsxSheet can change them per sheet in its third argument. They can also live in exportDefaults.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.

ts
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 }],
});
  • cellStyle receives { kind, column, columnIndex, rowIndex, value, row }. kind is 'header', 'data', 'group' or 'summary', and rowIndex is -1 for the header. value is the exported value, so it is the displayed text when formatValue ran. Read row (the source row of a data line) when you need the original number.
  • Colors accept #RGB or #RRGGBB only. Any other format throws a RangeError (a value returned by your callback follows errorPolicy).
  • headerStyle is laid over the default header (bold, light grey background).
  • In merges, row counts data rows without the header (0-based) and column counts exported columns. A range outside the table or overlapping another throws a RangeError before anything is built. A merged area keeps only the value of its top-left cell.
  • Both xlsx and PDF support rowSpan (vertical) and colSpan (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 and onWarning gets merge-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.

ts
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}` } }
OptionValueBehavior
formulasboolean (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 =
footerFormulasboolean (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, errorPolicy applies 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.

Formulas example

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).

ts
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.

Notes example

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.

ts
ex.exportXlsx({
  protect: { password: 'abc', lockedColumns: ['code', 'name'], allowSort: true },
});
OptionValueBehavior
passwordstring (255 chars or less)The unprotect password. Without it the sheet is protected without a password
lockedColumnsarray of column idsLocks only those columns and unlocks the other body cells. If omitted, every cell is locked. The header is always locked
allowSortboolean (default false)Allows sorting while protected
allowFilterboolean (default false)Allows the auto filter while protected

Protection applies to the first sheet only.

Sheet protection example

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.

ts
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' } },
  ],
});
OptionValueBehavior
startRowinteger 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).

Extra cells example

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).

ts
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 / 3 sits 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 use orientation: 'landscape' or a smaller fontSize.
  • Numbers are right-aligned (an explicit align wins). Dates use the local calendar date, and any column that is not kind: 'date' also shows the time (2025-03-04 09:05).
  • Long text wraps at spaces and between Korean characters (overflow: 'wrap', up to maxCellLines lines, then ...). 'ellipsis' keeps one line. A row is never split across pages.
  • rowScope ('visible', 'all', 'selected') and hierarchy work 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 call api.expandAll() first.
  • formatValue, errorPolicy and onError also work as in CSV and xlsx.
OptionDefaultMeaning
pageSize'A4'Paper: 'A4' or 'Letter'
orientation'portrait''portrait' or 'landscape'
margin36Margin on all four sides, in pt
fontSize9Body font size, in pt
fontauto-detectTTF bytes or koreanFont. false keeps Helvetica only
cellStylenoneCell colors and bold (same as xlsx)
headerStylenoneHeader look
mergesnoneCell merging (horizontal and vertical)
cellImagenoneCell images (PNG, JPEG)
imageHeight48Height of an image cell, in pt
titlenoneTitle drawn above the first page and stored in the document info
authornoneAuthor in the document info
pageNumberstrueDraw page numbers
overflow'wrap'Long text: 'wrap' or 'ellipsis'
maxCellLines6Most lines in one cell
compresstrueCompress streams. Falls back to uncompressed where it is not supported
maxRows100000Row limit. More rows throw a RangeError. The hard ceiling is 1,000,000
onWarningnoneWarning callback. Without it, the first warning goes to console.warn
chunkSize2000Rows built per chunk
signalnoneCancel 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.

bash
pnpm add @maxgrid/export-font-ko
ts
import { koreanFont } from '@maxgrid/export-font-ko';

await downloadPdf('employees.pdf', api, { font: koreanFont, title: 'Employees' });
  • koreanFont reads 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.mjs builds 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's fonts/ folder, unrenamed and unprocessed.
  • With a script tag, load maxgrid.export-font-ko.min.js (it creates the global MaxGridExportFontKo). 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.

  1. 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.
  2. 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 globals MaxGridExportFontKo and MaxGridExportFontSc from script tags first, then the package names. getValue, formatValue and cellStyle run once more in that case. Bundlers (Vite, webpack) do not follow this name, so in a bundled app pass font: koreanFont yourself.
  3. If it finds none, the characters become ? and onWarning gets { code: 'missing-glyph', characters, suggest: '@maxgrid/export-font-ko' } once (console.warn when there is no onWarning). The message says how to install it.
  4. 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.

ts
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 (wght axis) 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 .ttf with TrueType outlines (glyf). OpenType CFF (.otf), .ttc collections and .woff are rejected with a RangeError.
  • A character that the font does not have becomes ? and is reported through onWarning.
  • The font file is treated as untrusted input and every length and position is range-checked. A broken file ends in a RangeError before 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-ko is 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.

bash
pnpm add @maxgrid/export-font-sc
ts
import { 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),
});
  • simplifiedChineseFont reads 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: simplifiedChineseFont alone. 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, load maxgrid.export-font-sc.min.js from jsDelivr or unpkg (it creates the global MaxGridExportFontSc), 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 the fonts/ folder of the same jsDelivr package. The loader checks the font's size and SHA-256; where SHA-256 is unavailable (for example an http: page) it checks the size only, and MaxGridExportFontSc.verified reports 'size'.
  • Characters that neither font has (Arabic, Hebrew, Thai, emoji and so on) still become ?.
  • To use your own font, pass its .ttf bytes: it can sit in the chain too, as in font: [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.

ts
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.

ts
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 a TypeError. 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: maxImageBytes per image (5 MB by default), 20,000 px per side, 16 million pixels in total, and maxImages different 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 default onError, 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.

ts
const blob = await ex.exportPng({ scope: 'all', scale: 2, background: '#ffffff' }); // Blob
await ex.downloadPng('sales.png', { scale: 3 });
OptionValueBehavior
scope'view' | 'all' (default 'view')'view' is the current screen, 'all' is every row after sorting and filtering (up to 5000 rows)
scale1 | 2 | 3 (default 2)Multiplier of the screen size
backgroundCSS colorColour painted behind and under the grid. Cells, stripes and the header keep their theme colours. Falls back to the grid background, then white
filenamestringDefault file name
onErrorfunctionReceives warnings such as skipped images and truncated rows. Without it, console.warn
  • Background: background only 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, lower scale or use scope: 'view'.

PNG example

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.

ts
await ex.print({
  scope: 'all',
  orientation: 'landscape',
  title: 'Order list',
  header: 'MaxGrid · Orders',
  footer: 'Page {page} of {pages}',
  rowsPerPage: 24,
});
OptionValueBehavior
scope'view' | 'all' (default 'view')The visible rows, or every row after sorting and filtering
orientation'portrait' | 'landscape' (default 'portrait')A4 paper orientation
titlestringTitle at the top of every page
header, footerstringPage header and footer. {page} and {pages} are the page number and the page count
repeatHeaderboolean (default true)Repeats the table header on each page
fitWidthboolean (default true)Fits the table to the paper width
rowsPerPageinteger 1 to 1000 (default 38 portrait, 24 landscape)Rows on one page

Browser settings may block the print dialog.

Print example

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.

SettingEffect
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.numerictrue exports number cells (summary rows too); false turns off the call's numberFormats
export.xlsx.numberFormatExcel 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.texttrue writes numbers as text cells too (leading zeros kept)
ts
{ 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: true and no numberFormat, the code is built from format.number. decimals decides the digits; without it the code is General. A prefix or suffix becomes quoted text, and negative: 'parens' makes positive;(positive). When there is nothing to build, number cells are written without a format.
  • Column settings win over the call's numberFormats and dateAsText. A bad format code throws a TypeError that names the column id.
  • numeric and text cannot both be true (invalid-option).
  • export.value may return only a string, a finite number or null. Any other value is handled like a throw: the cell is left empty and onError is told.
  • If export.value throws, that cell is empty and onError is told.

Set export defaults once ​

Write default options per format in exportDefaults, and api.exportCsv(), exportXlsx(), exportPdf() and the download* methods start from them.

ts
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. aggregateFormat is 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 소계, (비어 있음)). Pass texts to change them. {label} is the group name.
ts
exportCsv(api, {
  hierarchy: true,
  texts: { summaryTotal: 'All', summarySubtotal: '{label} sum', summaryEmpty: 'Unsorted' },
});
ts
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.

ts
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.

ts
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 through await.
  • exportCsvChunks(api, options) yields pieces for for 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.