gridcn2.0.0
Import and export

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.

Name
Email
Role
Score
Silent Tiger
user0@example.com
Viewer
4
Quick Lion
user1@example.com
Viewer
89
Swift Wolf
user2@example.com
Manager
80
Eager Lion
user3@example.com
User
51
Eager Tiger
user4@example.com
Viewer
83
Silent Wolf
user5@example.com
User
15
Swift Lion
user6@example.com
Viewer
62
Eager Lion
user7@example.com
Manager
42
Eager Eagle
user8@example.com
Editor
35
Bold Tiger
user9@example.com
Editor
52
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.
  • page writes the rows of the shown page. A grid without paging treats it as view.
  • all writes every row of data in data order, whatever the sort and the filters.
  • selection writes 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 });
      },
    });
}

Print

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, else toText), so a formatted value prints as it reads on screen.
  • A cell aligns with the align of its cell type, in reading direction, so an end-aligned number stays at the end in a right-to-left page.
  • A cellClassName does not reach the printed table.
  • A call while a print frame is open replaces that frame and aborts a source that is still loading.
  • Print does nothing during server rendering.
  • title prints as a heading and sets the document title.
  • orientation defaults to landscape above 6 visible columns, else portrait.
  • paperSize is "A4" (default), "A3", "Letter", or "Legal".
  • maxRows defaults to 10,000. A 500,000-cell ceiling cuts it further. NaN reads as the default, and a negative value counts as 0. A cut table ends with a note such as "Printed 10000 of 25000 rows".
  • direction is "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.
  • headers maps a column id to its header text.
  • css adds 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 in css can load a remote URL.
  • signal cancels the print. The promise rejects with the reason and no dialog opens.
  • source prints 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".
  • DataGridPrintButton passes its options prop to printGrid. It sets aria-busy while a source loads, 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. The view and all scopes write all pages. Use scope: "page" for the shown page only.
  • Server pages write the current page. The all scope writes that page only.
  • Scroll mode writes the loaded rows. Every scope skips unloaded rows.
  • With your own API (onDataChange write-through), export writes the rows that data holds.
  • With sortMode="server", the view scope keeps the order of data. With filterMode="server", it applies no filter.
  • With controlled sortState and filterState, 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.

On this page