gridcn2.0.0
Add-on optionsImport and export

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.

SymbolPurposeGuide
importDefaultsSets where the dialog startsImport
importLimitsBounds the fileImport
DataGridImportButtonOpens the dialog from a buttonImport
DataGridImportDialogTakes the open state from youImport
FunctionsParse a file, match columns, build rowsControl import
useDataGridImportPreviewRuns the dialog steps for your own UIControl import
DropzoneThe drop surface of the dialogImport

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 defaultDelimiter set, the dialog reads CSV files with that delimiter and does not detect one.
  • mapColumn wins over defaultSkipColumns. If a promise from mapColumn rejects, the dialog drops every answer of mapColumn and uses the built-in match with defaultSkipColumns.

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.2 comes in as 0.3.
  • A boolean comes in as TRUE or FALSE. 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 as 2024-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

Prop

Type

DataGridImportDialogProps

If you control the open state yourself, use the dialog.

Prop

Type

Functions

FunctionReturnsWhat 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 BuildImportedRowsResultBuilds 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:

MessageCause
file-too-largeThe file is over maxFileBytes.
import-too-many-cellsThe rows, columns, or cells are over a cap.
part-too-largeA part of an XLSX file unpacks over the part cap.
unsupported-excel-formatThe file has an Excel name but is neither XLSX nor BIFF8 XLS.
unsupported-file-typeThe 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-xlsThe 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, checks signal between chunks.
  • A smaller build checks signal once, after an async createRow settles.
  • 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.
  • columns and cellTypes: 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.

PropTypeDefaultWhat it does
acceptDropzoneAcceptevery fileMaps MIME types to extensions, such as { "text/csv": [".csv"] }.
maxFilesnumberunlimitedSets the most files per drop or pick. 1 turns off multiple files.
maxSizenumbernoneSets the largest file, in bytes.
minSizenumbernoneSets the smallest file, in bytes.
disabledbooleanfalseIgnores drops, clicks, and keys.
compactbooleanfalseShows the zone as one row.
onDrop(accepted: File[], rejections: DropzoneRejection[]) => voidnoneReceives the accepted files and the rejections after a drop or a pick.
filesFile[]noneHolds the files to show. DropzoneEmptyState hides while it holds a file, and DropzoneContent lists them.
childrenReactNodeDropzoneEmptyState and DropzoneContentReplaces the default content.
classNamestringnoneMerges after the built-in classes.
aria-labelstringnoneNames the drop surface.
accessibleDescriptionstringThe accepted types and the size limit, in EnglishReplaces the screen reader description of the accepted files. DataGridImportDialog sets it from labels.io.dropzoneDescription.
aria-labelledbystringnoneNames 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

  • ProcessCellFromText converts the text of one imported cell. It receives the text and { row, column, source, signal, fromText }. fromText is the own parser of the column, for the cells you do not change. The column validate still checks the value that the hook returns. The hook can throw or reject, and fromText can 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.
  • ProcessImportRows rewrites or drops the data rows before the grid maps them. It receives { rows, headers, mapping, signal } and returns the rows, or false to cancel.
  • BuildImportOptions are the options of build() in useDataGridImportPreview. They add processImportRows and checkImport. With checkImport, the result carries check.
  • CheckImport is the type of checkImport. It receives the built rows and { signal, mapping, fileName, sheetName, rejected }. It returns an ImportCheckAnswer: { rejected?, summary? }.
  • ParseFile parses a File into rows. It receives the file and { signal, limits, sheetName, csvDelimiter, valueMode }.
  • ImportContext is the second argument of onImport. It holds signal, rejected, flagged, fileName, sheetName, and mapping (a list of ImportColumnMapping entries).
  • Import: the dialog, the Excel rules, and the limits in use.
  • Export options: the options of the matching export.
  • Validation: the validate check that clears a cell on import.

On this page