Import options
Look up importDefaults, importLimits, the props of the import button and dialog, and the functions and hook for a custom import UI.
The data-grid-io add-on reads a CSV, TSV, XLSX, or XLS file into rows. DataGridImportButton and DataGridImportDialog take two optional objects: importDefaults sets where the dialog starts, and importLimits bounds the file. Import explains the dialog.
| Symbol | Purpose | Guide |
|---|---|---|
importDefaults | Sets where the dialog starts | Import |
importLimits | Bounds the file | Import |
DataGridImportButton | Opens the dialog from a button | Import |
DataGridImportDialog | Takes the open state from you | Import |
| Functions | Parse a file, match columns, build rows | Control import |
useDataGridImportPreview | Runs the dialog steps for your own UI | Control import |
Dropzone | The drop surface of the dialog | Import |
This sample reads CSV files with semicolons, skips the internal_id column, and rejects a file over 5 MiB or over 10,000 rows, header row included:
import { DataGridImportButton } from "@/components/data-grid-io/data-grid-io";
type Row = { id: string; name: string };
export function ImportRows({ onRows }: { onRows: (rows: Row[]) => void }) {
return (
<DataGridImportButton<Row>
createRow={() => ({ id: crypto.randomUUID(), name: "" })}
onImport={onRows}
importDefaults={{
defaultDelimiter: ";",
defaultSkipColumns: ["internal_id"],
}}
importLimits={{ maxFileBytes: 5 * 1024 * 1024, maxRows: 10_000 }}
/>
);
}Render it inside DataGridProvider.
ImportDefaults
Prop
Type
defaultHeaderRow defaults to true. Without importDefaults, the header row toggle is on, CSV files get a detected delimiter, and each column matches by header text.
The user can change every default in the open dialog.
- With
defaultDelimiterset, the dialog reads CSV files with that delimiter and does not detect one. mapColumnwins overdefaultSkipColumns. If a promise frommapColumnrejects, the dialog drops every answer ofmapColumnand uses the built-in match withdefaultSkipColumns.
ImportLimits
parseImportFile rejects a file over any limit. It never cuts the file. An omitted field takes its value from DEFAULT_IMPORT_LIMITS, which the add-on exports.
Prop
Type
An XLSX part has a cap of maxDecompressedBytes bytes after unpacking. Without maxDecompressedBytes, the cap is maxCells * 10 + 1 MiB.
Excel files
A file with an .xlsx or .xls name goes to the Excel parser. The parser then reads the bytes: a zip file reads as XLSX, and an OLE2 file (the container of Excel 97-2003 files) reads as XLS.
- An XLSX cell comes in as the text that Excel shows, so a date, a currency, or a percentage follows its number format. A number without a format keeps 15 significant digits, so
0.1 + 0.2comes in as0.3. - A boolean comes in as
TRUEorFALSE. An error cell comes in as its code, such as#DIV/0!. - An XLS cell has no number format. A date comes in as an ISO date such as
2024-01-15, and a date with a time comes in as2024-01-15 13:45:00.
valueMode: "raw" in importDefaults (or in the options of parseImportFile) reads the stored value of each cell instead of its formatted text. A number comes in as String(n), a date as ISO 8601 (2024-01-15, or 2024-01-15T13:45:00 with a time), and a boolean as true or false. An XLSX error cell comes in empty. A string stays as it is. CSV files ignore valueMode. The default is "formatted".
The dialog rejects an HTML table, Excel 2003 XML, or an Excel 5.0 file with an .xls name. The message asks for an .xlsx file.
If its number format meets one of these rules, an XLSX cell comes in as its plain value (Excel's General format), not as formatted text:
- over 255 characters
- a fraction with four or more denominator placeholders, such as
# ?/???? - a format that fails on use
A damaged file, or a workbook that the size check cannot follow, gets a read-error message. A file or a sheet without rows gets a "no rows" message.
DataGridImportButtonProps
DataGridImportDialogProps
If you control the open state yourself, use the dialog.
Prop
Type
Functions
| Function | Returns | What it does |
|---|---|---|
parseImportFile(file, options?) | Promise<ParsedImportFile> | Reads a file into a grid of strings. The header row stays in rows[0]. |
matchImportColumns(headers, columns) | (string | null)[] | Matches each header to a grid column id by header text, then by column id. When two headers match one column, the first header keeps it and the later header gives null. |
applyImportOptions(headers, columns, options?) | (string | null)[] | Matches, then applies defaultSkipColumns and a synchronous mapColumn. |
buildImportedRows(options) | a promise of BuildImportedRowsResult | Builds one row per data row and checks every cell. |
parseImportFile
Prop
Type
The function rejects with an Error that carries one of these messages. Another parser error keeps the message of the parser:
| Message | Cause |
|---|---|
file-too-large | The file is over maxFileBytes. |
import-too-many-cells | The rows, columns, or cells are over a cap. |
part-too-large | A part of an XLSX file unpacks over the part cap. |
unsupported-excel-format | The file has an Excel name but is neither XLSX nor BIFF8 XLS. |
unsupported-file-type | The name is not .csv, .tsv, .xlsx, or .xls, and the MIME type is not text/csv or text/tab-separated-values. |
unknown sheet "<name>" | The workbook has no sheet named sheetName. |
unreadable-zip, unreadable-xls | The file has damage. |
[data-grid-io] unsupported csvEncoding: <label> | csvEncoding names a label that is not in IMPORT_CSV_ENCODINGS. The error is a RangeError. |
The signal option aborts the read. If it aborts before the file read ends, the parse rejects with a DOMException named AbortError. A later abort does not stop the parse.
The function resolves to a ParsedImportFile:
Prop
Type
buildImportedRows
Prop
Type
The result lists each cleared cell:
Prop
Type
The function always returns a promise. An abort of signal rejects it with "import-cancelled", which the add-on exports as IMPORT_CANCELLED_MESSAGE. When the abort lands depends on the build:
- A build over 5,000 data rows, or one with
processCellFromText, checkssignalbetween chunks. - A smaller build checks
signalonce, after an asynccreateRowsettles. - A small build with synchronous hooks ignores
signal.
If two entries of mapping name one grid column, the first entry wins, and development mode warns once for that column.
mapping is a list of ImportColumnMapping entries: { importColumnIndex, gridColumnId }, with null as gridColumnId for a skipped column. rejected lists ImportRejectedCell entries for cleared cells. flagged lists the cells of validationMode: "warn" columns that keep their value.
With validateRow, the function runs once per built row, in chunks, and gets the row id from getRowId (default: the row index as text). A verdict entry for a mapped column clears that cell and adds it to rejected. An entry for a column outside the mapping adds a flagged cell with importColumnIndex -1. A throw or a rejection gives that row no verdict. The import dialog passes the grid's validateRow when onImport is set. The default append runs it when the rows commit.
useDataGridImportPreview
The hook runs the file, header, and mapping steps of the dialog and leaves the UI to you.
Prop
Type
Prop
Type
preview is an ImportFileState. loadFile(file, gridColumns) takes the grid columns as ImportTargetColumn entries: { id, header, headerText? }. error is an ImportErrorKey, a key into labels.io. isParsing is true while a file loads.
To build the rows, call build(options) from the hook. To build them yourself, call buildImportedRows with these values:
dataRows:importRows.mapping:preview.mapping.columnsandcellTypes: the values from the read state.createRow: your own function.
setMapping(importColumnIndex, gridColumnId) sets one menu, and null skips the column. It does not check for a grid column that another source column already holds. setHasHeaderRow, setDelimiter, and setSheetName are the calls for the header toggle, the delimiter menu, and the sheet picker of your UI. previewRows holds at most 10 rows.
checkImport
checkImport runs after the build and before onImport. The dialog writes nothing while it runs. An answer without rejected entries goes on to onImport. An answer with entries opens a check step. The step shows the summary and the first 100 entries as row, column, and message. Its buttons are "Import anyway", which calls onImport, and "Back".
A throw, a rejection, or an answer in another shape shows labels.io.checkFailed. The import can be retried. The dialog keeps 1,000 entries and counts the rest as "and more". A rowIndex is an integer inside the built rows. A columnId that is not a grid column shows the entry without a column. A message is cut at 200 characters. signal aborts when the user cancels, closes the dialog, or loads a new file.
On the server, parseImportRows gives the rejected list. See Query layer reference.
Dropzone
data-grid-io installs the dropzone item. Import Dropzone, DropzoneEmptyState, and DropzoneContent from @/components/dropzone/dropzone.
| Prop | Type | Default | What it does |
|---|---|---|---|
accept | DropzoneAccept | every file | Maps MIME types to extensions, such as { "text/csv": [".csv"] }. |
maxFiles | number | unlimited | Sets the most files per drop or pick. 1 turns off multiple files. |
maxSize | number | none | Sets the largest file, in bytes. |
minSize | number | none | Sets the smallest file, in bytes. |
disabled | boolean | false | Ignores drops, clicks, and keys. |
compact | boolean | false | Shows the zone as one row. |
onDrop | (accepted: File[], rejections: DropzoneRejection[]) => void | none | Receives the accepted files and the rejections after a drop or a pick. |
files | File[] | none | Holds the files to show. DropzoneEmptyState hides while it holds a file, and DropzoneContent lists them. |
children | ReactNode | DropzoneEmptyState and DropzoneContent | Replaces the default content. |
className | string | none | Merges after the built-in classes. |
aria-label | string | none | Names the drop surface. |
accessibleDescription | string | The accepted types and the size limit, in English | Replaces the screen reader description of the accepted files. DataGridImportDialog sets it from labels.io.dropzoneDescription. |
aria-labelledby | string | none | Names the drop surface by the element with this id. It wins over aria-label. |
A DropzoneRejection is { file, reasons }. Each reason is accept, maxSize, minSize, or maxFiles. filterFiles(files, options) applies the same rules and returns a FilterFilesResult: accepted holds the accepted files, and rejections holds the rejections. matchesAccept(file, accept) tests one file. DropzoneEmptyState takes a title and a description. DropzoneContent shows its children in place of the file list.
The root carries data-drag-active during a drag and data-disabled while disabled is true.
Types
ProcessCellFromTextconverts the text of one imported cell. It receives the text and{ row, column, source, signal, fromText }.fromTextis the own parser of the column, for the cells you do not change. The columnvalidatestill checks the value that the hook returns. The hook can throw or reject, andfromTextcan throw on text it cannot read. In both cases the grid rejects that one cell and reports it like unreadable text. The rest of the import goes on.ProcessImportRowsrewrites or drops the data rows before the grid maps them. It receives{ rows, headers, mapping, signal }and returns the rows, orfalseto cancel.BuildImportOptionsare the options ofbuild()inuseDataGridImportPreview. They addprocessImportRowsandcheckImport. WithcheckImport, the result carriescheck.CheckImportis the type ofcheckImport. It receives the built rows and{ signal, mapping, fileName, sheetName, rejected }. It returns anImportCheckAnswer:{ rejected?, summary? }.ParseFileparses aFileinto rows. It receives the file and{ signal, limits, sheetName, csvDelimiter, valueMode }.ImportContextis the second argument ofonImport. It holdssignal,rejected,flagged,fileName,sheetName, andmapping(a list ofImportColumnMappingentries).
Related
- Import: the dialog, the Excel rules, and the limits in use.
- Export options: the options of the matching export.
- Validation: the
validatecheck that clears a cell on import.
Export options
Look up the options of exportGrid and printGrid, the props of the export and print buttons, and the helper functions of data-grid-io.
Client pagination options
Look up the options and result of useDataGridPagination, the props of DataGridPaginationBar, and the parts you compose into a custom footer.