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:
parseFilereads the file.defaultHeaderRowdrops the rows above the header.processImportRowsrewrites the rows.- The dialog applies the column mapping.
processCellFromTextparses each cell.validatechecks each value.onImportreceives the rows.
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
| Prop | Runs | What it does |
|---|---|---|
parseFile | for every parse: file load, delimiter, sheet | Reads 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. |
accept | when the drop zone opens | Sets the file types the drop zone takes. Default: csv, tsv, xls, xlsx. |
csvEncoding | when a CSV file is read | Decodes the CSV with this label instead of UTF-8. parseFile replaces it. |
importDefaults.defaultHeaderRow | after the parse | A number is the 0-based index of the header row. The dialog drops the rows above it. |
importDefaults.mapColumn | for each file header | Receives (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. |
processImportRows | on confirm, before the dialog applies the mapping | Returns the rows to import, or false to cancel. It gets rows (header excluded), headers, mapping, and signal. |
processCellFromText | for each mapped cell | Returns the cell value instead of the column's fromText. The context holds fromText, the column's own parser. |
onImport | after the build | Gets rows and { signal, rejected, flagged, fileName, sheetName, mapping }. |
onImportError | when onImport rejects | Gets 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.
Related
- Import: the dialog.
- Import options: every field and limit.
- Labels and i18n: the
labels.iotexts.
Import into a server grid
Send the imported rows to your server from onImport, then refresh the grid, because a grid with a row count cannot append rows.
Write a cell type
Pick the lightest way to change how a column shows and edits values, then write a custom cell type with its own display, editor, and text round trip.