gridcn2.0.0
Import and export

Control the import

Replace the file parser, set the accepted file types and encoding, rewrite rows and cells, and handle a failed onImport.

These props shape the import. Pass them to DataGridImportButton or DataGridImportDialog. Every prop is optional. The import runs in this order:

  1. parseFile reads the file.
  2. defaultHeaderRow drops the rows above the header.
  3. processImportRows rewrites the rows.
  4. The dialog applies the column mapping.
  5. processCellFromText parses each cell.
  6. validate checks each value.
  7. onImport receives the rows.
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 Import. parseFile and processImportRows cannot raise a bound: their results pass the same bounds as a built-in result. Raise a bound with importLimits. The dialog rejects a file over maxFileBytes before parseFile runs.

Import props

PropRunsWhat it does
parseFilefor every parse: file load, delimiter, sheetReads the file instead of the built-in parser. Return { rows }: arrays of strings that fit importLimits. It can also return delimiter, sheetNames, and sheetName, which the dialog shows.
acceptwhen the drop zone opensSets the file types the drop zone takes. Default: csv, tsv, xls, xlsx.
csvEncodingwhen a CSV file is readDecodes the CSV with this label instead of UTF-8. parseFile replaces it.
importDefaults.defaultHeaderRowafter the parseA number is the 0-based index of the header row. The dialog drops the rows above it.
importDefaults.mapColumnfor each file headerReceives (header, index, { signal }). The signal aborts when a newer parse replaces the run or the dialog unmounts. The dialog ignores an aborted result. Inside a grid, gateTimeoutMs.mapColumn also aborts it, and the built-in match applies.
processImportRowson confirm, before the dialog applies the mappingReturns the rows to import, or false to cancel. It gets rows (header excluded), headers, mapping, and signal.
processCellFromTextfor each mapped cellReturns the cell value instead of the column's fromText. The context holds fromText, the column's own parser.
onImportafter the buildGets rows and { signal, rejected, flagged, fileName, sheetName, mapping }.
onImportErrorwhen onImport rejectsGets the rejection. The dialog stays open.

The createRow prop receives (index, { signal }) with the same signal.

Steps

Pick the props from the table. Pass them as props. In this sample, processCellFromText parses total as a number and maps an empty cell to null. Every other cell goes through the column's fromText after a trim:

import { DataGridImportButton } from "@/components/data-grid-io/data-grid-io";
import { api, type Order } from "./api";

export function ImportOrders({ refresh }: { refresh: () => void }) {
  return (
    <DataGridImportButton<Order>
      createRow={() => ({ id: crypto.randomUUID(), customer: "", total: 0 })}
      importDefaults={{ defaultHeaderRow: 3 }}
      csvEncoding="windows-1252"
      processImportRows={({ rows }) => rows.filter((row) => row[0] !== "TOTAL")}
      processCellFromText={(text, { column, fromText }) =>
        column.id === "total"
          ? text.trim() === ""
            ? null
            : Number.parseFloat(text)
          : fromText(text.trim())
      }
      onImport={async (rows, { signal, rejected, fileName }) => {
        await api.import(rows, { signal, fileName, skipped: rejected.length });
        refresh();
      }}
      onImportError={(error) => console.error(error)}
    />
  );
}

Result

The dialog builds the rows and clears each cell that fails validation. onImport receives the rows. It also receives the cleared cells in rejected and the cells of a validationMode: "warn" column in flagged.

Prop rules

csvEncoding takes one of these labels: utf-8, utf-16le, utf-16be, iso-8859-1, iso-8859-2, iso-8859-15, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1257, shift_jis, euc-jp, euc-kr, gb18030, and big5. The list is IMPORT_CSV_ENCODINGS. With any other label, parseImportFile throws a RangeError, and the import dialog shows labels.io.errorParseFailed.

processImportRows and parseFile must return arrays of strings. A result that has another shape, or more rows, columns, or cells than importLimits allows, stops the import and the dialog shows an error.

processCellFromText defaults to the grid's processCellFromClipboard, then to the column's fromText. A grid that sets processCellFromClipboard therefore uses it for imports too. A promise result makes the build asynchronous. The prop runs for every cell of 2,000 rows at a time, so limit the concurrency inside it. Its value still goes through the column's validate. The dialog clears a cell that fails. rejected lists it with the validator's message, cut at 200 characters.

When onImport rejects, the dialog shows The import failed: <message> if the error has a message. Without one, it shows the generic line. Both texts come from labels.io.

Load a file from code

Pass file to DataGridImportDialog to load a file you already hold, such as one you fetched or one the user dropped on the page. The dialog loads it when it opens. For a custom dialog under the provider, useDataGridImportPreview() returns build(), which runs processImportRows and the row build for the current preview. It reads columns and cellTypes from the grid. Pass columns or cellTypes to build for other ones:

import { useDataGridImportPreview } from "@/components/data-grid-io/data-grid-io";
import { api } from "./api";

export function useSaveImport() {
  const preview = useDataGridImportPreview();
  return async (signal: AbortSignal) => {
    const built = await preview.build({
      createRow: () => ({ id: crypto.randomUUID(), customer: "", total: 0 }),
      signal,
    });
    if (built) await api.import(built.rows, { signal });
  };
}

Server mode

These props work the same in every data mode. A server grid sends the rows to its server in onImport and calls server.refresh(). See Import into a server grid.

On this page