gridcn2.0.0
Import and export

Shape the export file

Pick the columns, format each cell, and send the finished file to your server instead of a browser download.

Two options shape the file, and one option decides where it goes. They apply to a loaded export and to an export with a source.

Id
Name
Price
Qty
A-1
Desk lamp
12.5
4
A-2
Notebook
3.2
10
A-3
Pen set
8
6
A-4
Stapler
6.75
2
output receives the finished file. Nothing is downloaded.
formatCell returns numbers, so xlsx cells are numeric.
columns: the ids to write, in this order (Note is hidden in the grid)

Cell types in the first row: id=textname=textprice=textqty=text

Before you start

Install data-grid-io. See Export.

Options

Set only the options you need:

  • Set columns to the column ids to write, in order. A hidden column is allowed. An unknown id throws a RangeError before anything is fetched. A source gets the same list as ctx.columnIds, so your server can select only those columns.
  • Set formatCell to return the value of one cell.
  • Set output to receive the finished file.

This example sends the file to your server and downloads nothing:

import { DataGridExportButton } from "@/components/data-grid-io/data-grid-io";

export function UploadReport() {
  return (
    <DataGridExportButton
      options={{
        columns: ["name", "price", "createdAt"],
        formatCell: ({ column, value, text }) =>
          column.id === "price" ? Number(value) : text,
        output: async (file, { fileName, signal }) => {
          await fetch(`/api/reports/${fileName}`, {
            method: "PUT",
            body: file,
            signal,
          });
        },
      }}
    />
  );
}

Result

output gets a finished Blob. The grid never builds a URL from it. If output rejects, the export rejects. The signal aborts when the export is cancelled, and output does not run for an aborted export. A loaded export with output shows the button as busy while it runs.

Cell values

formatCell returns a string, a number, a boolean, a Date, or null for an empty cell. It runs once for every cell, after the cell type made its text. text is that default. ctx.signal aborts on a cancel or a failure. Load data for many cells in the source. For data that one cell needs, return a promise. The export awaits the promises of each slice of rows together, in groups of at most 10,000 cells.

ValueCSVXLSX
stringwritten as text, cut at 32,767 charactersa text cell, cut at 32,767 characters
finite numberthe number as texta number cell, so Excel can sum it
booleantrue or falsea boolean cell
valid DateISO 8601 texta date cell
NaN, Infinity, invalid Date, null, undefinedemptyempty

A string is never a formula. A CSV cell that starts with =, +, -, @, TAB, or CR still gets the quote prefix. A plain number such as -5 or -1e-7 is the exception. An XLSX string is always a text cell. The limits maxRows and maxBytes count the formatted output.

Build the file without a download

For the CSV text of the loaded rows without a Blob, call rowsToCsv(buildExportRows(state, scope)). The text has no header row. exportRows(state, options, onBatch) is the engine behind a source export. It reads the batches, applies columns and formatCell, enforces the limits and the abort, and hands each batch of text rows to onBatch. Pass api.store.getState() from the grid ref as state. This sample writes one JSON object per row:

import {
  exportRows,
  type ExportSource,
} from "@/components/data-grid-io/data-grid-io";
import type { DataGridReadState } from "@/components/data-grid/data-grid-sdk";

export async function toJsonLines(
  state: DataGridReadState,
  source: ExportSource,
  columnIds: string[],
) {
  const lines: string[] = [];
  const options = {
    source,
    columns: columnIds,
    maxRows: 50_000,
    maxBytes: 20_000_000,
  };
  await exportRows(state, options, (rows) => {
    const batch = rows.map((row) => {
      const entries = columnIds.map((id, index) => [id, row[index]]);
      return JSON.stringify(Object.fromEntries(entries));
    });
    lines.push(...batch);
    return batch.reduce((size, line) => size + line.length, 0);
  });
  return lines;
}

onBatch returns the size of the batch it kept, in characters or bytes, so maxBytes can stop the export.

maxRows and maxBytes are optional. They default to 1,000,000 rows and 256 MiB. A negative value counts as 0, and NaN reads as the default.

On this page