Export
Download the rows of the grid as a CSV or XLSX file, or print them as a paged table, from a toolbar button or from code.
Export writes the rows of the grid to a CSV or XLSX file. DataGridExportButton adds a toolbar button for it, and exportGrid does the same from code. In the demo, the toolbar button downloads the rows as XLSX or CSV:
Export downloads the current view as a csv or xlsx file. Import accepts a csv or xlsx file (a sheet picker appears for multi-sheet workbooks), lets you map its columns, and appends the rows to the grid.
pnpm dlx shadcn@latest add @gridcn/data-grid-io
The add-on depends on hucre (pinned to 1.1.0) for XLSX and on papaparse for CSV import. papaparse loads with the add-on. The grid loads hucre on the first XLSX or XLS read or write.
Download a file
Place DataGridExportButton inside the provider, usually in the toolbar. The sample imports DataGridToolbar, so install data-grid-toolbar as well:
import {
DataGridBody,
DataGridHeader,
DataGridProvider,
DataGridRoot,
} from "@/components/data-grid/data-grid";
import {
DataGridToolbar,
} from "@/components/data-grid-toolbar/data-grid-toolbar";
import { DataGridExportButton } from "@/components/data-grid-io/data-grid-io";
// your order rows and their defineColumns array
import { columns, orders } from "./orders";
export function OrdersGrid() {
return (
<DataGridProvider defaultData={orders} columns={columns}>
<DataGridToolbar>
<DataGridExportButton options={{ fileName: "orders" }} />
</DataGridToolbar>
<DataGridRoot className="h-80">
<DataGridHeader />
<DataGridBody />
</DataGridRoot>
</DataGridProvider>
);
}The button opens a menu with XLSX and CSV. With one format and no source, such as formats={["csv"]}, a click exports at once. The options prop passes every exportGrid option except format. onError(error, format) receives the error and the format of a failed export. Without it, a failure logs a warning in development only.
To start an export from your own control, call exportGrid from useDataGridExport():
"use client";
import { useDataGridExport } from "@/components/data-grid-io/data-grid-io";
export function ExportAllButton() {
const { exportGrid } = useDataGridExport();
return (
<button onClick={() => exportGrid({ format: "csv", scope: "all" })}>
Export all rows
</button>
);
}Choose the rows
scope picks the rows:
view(default) writes the rows of the current view, in sort order and after the filters. A grid that pages its view writes every page. Quick search does not narrow the view, so it does not narrow the export.pagewrites the rows of the shown page. A grid without paging treats it asview.allwrites every row ofdatain data order, whatever the sort and the filters.selectionwrites the rows that a cell range or a checked row marker covers, in view order. With'until-cleared'or'across-filters', one checked row limits the export to the checked rows. Run bulk actions exports the checked rows from a button.
Without columns, every scope writes the visible columns in view order. Shape the export file picks other columns, hidden ones included. A cell range that covers part of a row still writes the whole row. includeHeaders: false drops the header row. maxRows keeps the first rows only and does not count the header row. When it cuts rows, the console warns in development.
Write a CSV file
Export writes each cell as the text that its cell type's toText gives. If processCellForClipboard is unset, copy gives the same text.
A CSV file holds UTF-8 text with a byte order mark. Excel reads UTF-8 from a file that starts with that mark. Set csvBom: false for a reader that fails on the mark. csvDelimiter sets the separator (comma by default). The writer quotes a field that holds the delimiter, a quote, or a line break. Lines end with CRLF.
A cell that starts with =, +, -, @, a tab, or a carriage return gets a leading single quote. Plain numbers stay as they are, also in exponent form such as -1e-7. Spreadsheets read the quote as a text marker, so a cell such as =HYPERLINK("http://x") opens as text and does not run.
sanitizeFormulas: false writes the raw text. A spreadsheet runs a cell that starts with = as a formula. Set it only for a program that expects the exact text.
rowsToCsv(rows, options) sanitizes the same way. Pass { sanitizeFormulas: false } for raw fields. sanitizeFormulaCell(value) from data-grid does the same for your own writers. Copy and cut prefix such cells too. The grid prop sanitizeClipboardFormulas turns that off (see Clipboard).
Write an XLSX file
An XLSX file holds one compressed sheet. A number column writes number cells. A date column writes date cells, and a checkbox column writes boolean cells. Excel can sum and sort them. Every other cell is a text cell with its toText string. A string never runs as a formula there. To write other typed cells, or to write a built-in column as text, return the value from formatCell.
sheetName names the sheet (Sheet1 by default). An export rejects a name that Excel does not allow:
- an empty name or a name over 31 characters
- a name with
[,],:,*,?,/, or\ - a name that starts or ends with an apostrophe
History, in any case
The writer cuts a cell text over 32,767 characters.
The output option receives the workbook as a Blob and starts no download. Use it to upload the file:
import { useDataGridExport } from "@/components/data-grid-io/data-grid-io";
export function useUploadWorkbook() {
const { exportGrid } = useDataGridExport();
return () =>
exportGrid({
format: "xlsx",
scope: "all",
output: async (file) => {
await fetch("/api/reports", { method: "POST", body: file });
},
});
}printGrid(state, options) fills a hidden frame with a plain table of the rows and opens the browser print dialog. It returns a promise of { rowCount, truncated }. The dialog's "Save as PDF" creates a PDF. Call useDataGridPrint() inside the provider, or place DataGridPrintButton in the toolbar. The Print example shows the button with a page size picker. Print takes the same scope as export. It prints visible columns in view order.
- Each cell shows the display text of its cell type (
toDisplayText, elsetoText), so a formatted value prints as it reads on screen. - A cell aligns with the
alignof its cell type, in reading direction, so an end-aligned number stays at the end in a right-to-left page. - A
cellClassNamedoes not reach the printed table. - A call while a print frame is open replaces that frame and aborts a
sourcethat is still loading. - Print does nothing during server rendering.
titleprints as a heading and sets the document title.orientationdefaults tolandscapeabove 6 visible columns, elseportrait.paperSizeis"A4"(default),"A3","Letter", or"Legal".maxRowsdefaults to 10,000. A 500,000-cell ceiling cuts it further.NaNreads as the default, and a negative value counts as 0. A cut table ends with a note such as "Printed 10000 of 25000 rows".directionis"ltr"or"rtl". It defaults to the reading direction of the page that prints.- A cell text over 32,767 characters is cut, as in XLSX.
headersmaps a column id to its header text.cssadds rules after the built-in ones, in a second<style>node. It is text only and at most 65,536 characters. Build it from constants: a cell value incsscan load a remote URL.signalcancels the print. The promise rejects with the reason and no dialog opens.sourceprints the whole server result, as in Export the whole result. It takes the export bounds: 1,000-row slices,maxRows, and the 500,000-cell ceiling. A cut table ends with a note such as "Printed the first 10000 rows".DataGridPrintButtonpasses itsoptionsprop toprintGrid. It setsaria-busywhile asourceloads, aborts the load on unmount, and a second click replaces the run.
Server mode
Without a source, export covers the rows the grid holds. It never asks the server for more.
- A client grid that pages its view (
pageSize) holds every row. Theviewandallscopes write all pages. Usescope: "page"for the shown page only. - Server pages write the current page. The
allscope writes that page only. - Scroll mode writes the loaded rows. Every scope skips unloaded rows.
- With your own API (
onDataChangewrite-through), export writes the rows thatdataholds. - With
sortMode="server", theviewscope keeps the order ofdata. WithfilterMode="server", it applies no filter. - With controlled
sortStateandfilterState, export follows the view like a local grid.
A source writes the whole server result. See Export the whole result.
Print covers the rows the grid holds, in the same way. A grid fed by useDataGridServerRows prints its current page, or the loaded blocks in scroll mode. Pass source to print the whole server result. The source receives the grid's spec and the printed columnIds.
Related
- Export options: every
exportGridandprintGridoption. - Export the whole result: the
sourceoption for server pages and scroll mode. - Shape the export file:
columns,formatCell, andoutput. - Import: the dialog that reads CSV and Excel files into rows.
- Clipboard: the copy text that export reuses.