Skip to content

Import and load from a URL ​

The import methods added by withExport(api) read CSV, XML or JSON text into rows and return them (1.4.0). Putting them into the grid is up to the app with setRows or addRows. loadUrl fetches from an address and puts the rows in for you.

ts
const ex = withExport(api);
const { rows, skipped, errors } = ex.importCsv(text);
api.setRows(rows);

await ex.loadUrl('/api/people.json');

Import methods ​

MethodReads
importCsv(text, options?)CSV text; the first line holds the names
importXml(text, options?)XML text; element form and attribute form
importJson(text, options?)JSON text; an array of objects

The result is { rows, skipped, errors }. skipped counts blank lines and non-object items, and errors is a list of { line, message }.

OptionValueDefaultEffect
typedbooleantrueConverts text to values that fit the column kind
delimiterone character','CSV delimiter (not a quote or a line break)
headerbooleantrueThe first CSV line holds the names; false uses columns or the grid order
columnsarray of column idscolumn orderNames of the columns when header: false
pathdotted pathnoneWhere the row list is in JSON or XML ('data.items')
rowTagelement nameall under rootElement name to read as a row in XML
maxBytespositive integer50000000Upper limit of input characters

Names are matched to columns by id, then title, then key. A name that matches nothing becomes a plain property of the row.

Value conversion (typed) ​

Column kindConverted value
numberNumber with commas removed; an empty cell is null
booleantrue/yes/1 and similar give true, false/no/0 and similar give false
date, timeYYYY-MM-DD, YYYY.MM.DD, YYYY/MM/DD, YYYYMMDD, HH:mm(:ss); empty is null
select, comboboxThe value matched by label or value in the fixed editorOptions
multiselectAn array of values matched after splitting by the separator (a joined string with valueAs: 'string')
textAs it is

A cell that cannot be converted becomes null and errors gets its line (item number for JSON and XML) and the reason. JSON keeps numbers, booleans and arrays and only converts text values.

Errors and limits ​

SituationError
Unclosed quote, input, row or cell limitparse-failed
XML syntax errorparse-failed (with the line number)
XML DOCTYPE or custom entityparse-failed: external-entity style attacks are not accepted
XML nested deeper than 64parse-failed
JSON syntax error, not an array, no pathparse-failed
Wrong optioninvalid-option

Load from a URL (loadUrl) ​

ts
await ex.loadUrl('/api/people', { format: 'json', path: 'data.items', mode: 'replace' });

The import options apply, plus these.

OptionValueDefaultEffect
format'json' · 'csv' · 'xml'by the responseWithout it, Content-Type decides, then the URL extension
csv{ delimiter?, header? }noneDelimiter and first-line rule for CSV
method'GET' · 'POST''GET'Request method
headers, bodyobject, stringnoneRequest headers and body (the body is sent only with POST)
credentials'omit' · 'same-origin' · 'include''same-origin'Whether cookies and auth are sent
mode'replace' · 'append''replace'Replace all rows / add after them
timeoutMsinteger 1000-30000030000Time limit
maxBytespositive integer50000000Size limit; counted while streaming and cut off at once
allowCrossOriginbooleanfalseAllows another origin (the server must also allow CORS)
signalAbortSignalnoneCancels the load
fetchtypeof fetchglobal fetchFor tests, workers and demos: used instead of the global fetch. URL, size and timeout rules still apply and relative URLs are still refused

URL rules ​

RuleContent
Schemehttp and https only; file:, javascript:, data: and others give load-failed
Credentialshttps://user:pw@host/… gives load-failed
Cross-originload-failed without allowCrossOrigin: true; the same origin works, relative URLs too
RedirectsFollowed, and the final URL must satisfy the same rules
HTML responseA Content-Type of HTML gives load-failed (a login page is not read as data)
Unknown formatNo format, no Content-Type and no extension gives load-failed

This is the only place where the grid uses fetch. Authentication is up to the app through headers or cookies (credentials).

Flow and events ​

StepBehavior
StartloadStarted { url }; the loading overlay shows unless the app uses the loading option
SuccessRows replaced or appended, loadFinished { url, count }, overlay hidden
FailureloadFailed { url, message } and an error event (load-failed or parse-failed), overlay hidden, the Promise rejects
New loadUrlCancels the earlier load; a cancel emits only loadFailed, not error
destroy()Cancels a running load and emits nothing

With only the core (no overlay) nothing is shown and the rest is the same.

Read an xlsx file (importXlsx) ​

Since 1.6.0

importXlsx and api.importXlsx live in @maxgrid/export. They read the file with their own code, with no extra library.

Read an Excel file (File, Blob, ArrayBuffer or Uint8Array) into rows. To put it straight into the grid use api.importXlsx, added by withExport(api); to only read it use the standalone importXlsx.

ts
import { importXlsx, withExport } from '@maxgrid/export';

// Read only: { columns, rows, sheetNames, warnings }
const read = await importXlsx(file, { sheet: 'Orders', range: 'A1:F500' });

// Put into the grid: { count, columns, sheetNames, warnings }
const ex = withExport(api);
await ex.importXlsx(file, { mode: 'append', columns: { 'Order No': 'order' } });
OptionMeaningDefault
sheetSheet name or a number counted from 1first sheet
headerRowHeader line (counted from the top of the range if there is one). 0 means no header and the keys are c1…cN1
columnsHeader text → column idnone
rangeCells to read ('A1:F500')all
maxRowsRow limit. More throws limit-exceeded100000
datesDate cells: 'date' (Date), 'iso' (YYYY-MM-DD text), 'serial' (Excel serial number)'date' when reading, 'iso' for api.importXlsx
trimTrim spaces around textfalse
mode(api.importXlsx only) 'replace' swaps all rows, 'append' adds after them'replace'
typed(api.importXlsx only) Convert values to the column kindstrue
  • Dates and percentages are recognized from the cell number format. A percent cell arrives as the stored value, such as 0.035.
  • A merged range has its value only in the top-left cell; the others are empty. A formula gives its stored result.
  • Error values such as #N/A are read as null and listed in warnings.
  • Repeated headers become name_2, and an empty header is named by its column number, such as c3.
  • Columns and values are matched with the same rules as CSV import. A cell that cannot be converted is null, with its line and reason in warnings.

Errors and limits ​

A file that cannot be read throws XlsxImportError; use code to tell why. api.importXlsx throws before changing the grid and also emits an error event (parse-failed or invalid-option).

codeCause
corruptNot an xlsx (ZIP) file, or damaged
encryptedThe file is password-protected
unsupportedA format that is not accepted: old .xls, .xlsb, ZIP64
limit-exceededOver 200 MB unpacked, 200 entries, a compression ratio of 100, or maxRows
sheet-not-foundThe chosen sheet does not exist
invalid-optionAn option name or value is invalid

XML with a DOCTYPE or custom entities is refused as corrupt. Data is unpacked with the browser's DecompressionStream, or with plain JS code in the package where it is missing.

Import by dropping a file (fileDrop) ​

Since 1.6.0

The fileDrop option, the fileImported event, the beforeFileImport hook and the openFileDialog() method were added. The import code comes from withExport(api), so call it.

ts
const api = createGrid(el, { columns, rows, rowKey: 'id', fileDrop: true });
withExport(api);

api.on('fileImported', ({ name, type, rowCount, warnings }) => {});

fileDrop is false (default), true, or an object.

KeyMeaningDefault
acceptArray of formats 'csv' | 'xlsx' | 'json' | 'xml'all four
mode'replace' swaps the rows, 'append' adds after them'replace'
maxSizeFile size limit in bytes. A larger file is not imported and the user is told50 MB
columnsHeader text → column idnone
overlayTextText shown while dragging: a string or { ko, en }the default for the grid language

The flow:

  1. While a file is dragged over the grid, an overlay ("Drop a file to import") appears. Drags that are not files (text, links) are ignored.
  2. On drop, the format comes from the extension (or the MIME type). With several files only the first acceptable one is imported and the others are listed in warnings.
  3. If the beforeFileImport({ file }) hook returns false the file is not imported. A throwing hook emits an error event and the import goes on.
  4. The size and format are checked, the file is read, and setRows or addRows runs. On success fileImported { name, type, rowCount, warnings } fires and a line above the grid shows the result.
  5. On failure an error event (load-failed, parse-failed) and a visible line (role="alert") appear and the rows stay as they were. A drop while an import runs only shows a notice and is ignored.

For keyboard users, api.openFileDialog() opens the file chooser (connect it to a button). It throws invalid-option when fileDrop is off. The messages exist in ko and en and in the Japanese and Chinese packs. After destroy() no listener, hidden input or message line is left.

See also ​