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.
const ex = withExport(api);
const { rows, skipped, errors } = ex.importCsv(text);
api.setRows(rows);
await ex.loadUrl('/api/people.json');Import methods
| Method | Reads |
|---|---|
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 }.
| Option | Value | Default | Effect |
|---|---|---|---|
typed | boolean | true | Converts text to values that fit the column kind |
delimiter | one character | ',' | CSV delimiter (not a quote or a line break) |
header | boolean | true | The first CSV line holds the names; false uses columns or the grid order |
columns | array of column ids | column order | Names of the columns when header: false |
path | dotted path | none | Where the row list is in JSON or XML ('data.items') |
rowTag | element name | all under root | Element name to read as a row in XML |
maxBytes | positive integer | 50000000 | Upper 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 kind | Converted value |
|---|---|
| number | Number with commas removed; an empty cell is null |
| boolean | true/yes/1 and similar give true, false/no/0 and similar give false |
| date, time | YYYY-MM-DD, YYYY.MM.DD, YYYY/MM/DD, YYYYMMDD, HH:mm(:ss); empty is null |
| select, combobox | The value matched by label or value in the fixed editorOptions |
| multiselect | An array of values matched after splitting by the separator (a joined string with valueAs: 'string') |
| text | As 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
| Situation | Error |
|---|---|
| Unclosed quote, input, row or cell limit | parse-failed |
| XML syntax error | parse-failed (with the line number) |
| XML DOCTYPE or custom entity | parse-failed: external-entity style attacks are not accepted |
| XML nested deeper than 64 | parse-failed |
JSON syntax error, not an array, no path | parse-failed |
| Wrong option | invalid-option |
Load from a URL (loadUrl)
await ex.loadUrl('/api/people', { format: 'json', path: 'data.items', mode: 'replace' });The import options apply, plus these.
| Option | Value | Default | Effect |
|---|---|---|---|
format | 'json' · 'csv' · 'xml' | by the response | Without it, Content-Type decides, then the URL extension |
csv | { delimiter?, header? } | none | Delimiter and first-line rule for CSV |
method | 'GET' · 'POST' | 'GET' | Request method |
headers, body | object, string | none | Request 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 |
timeoutMs | integer 1000-300000 | 30000 | Time limit |
maxBytes | positive integer | 50000000 | Size limit; counted while streaming and cut off at once |
allowCrossOrigin | boolean | false | Allows another origin (the server must also allow CORS) |
signal | AbortSignal | none | Cancels the load |
fetch | typeof fetch | global fetch | For 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
| Rule | Content |
|---|---|
| Scheme | http and https only; file:, javascript:, data: and others give load-failed |
| Credentials | https://user:pw@host/… gives load-failed |
| Cross-origin | load-failed without allowCrossOrigin: true; the same origin works, relative URLs too |
| Redirects | Followed, and the final URL must satisfy the same rules |
| HTML response | A Content-Type of HTML gives load-failed (a login page is not read as data) |
| Unknown format | No 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
| Step | Behavior |
|---|---|
| Start | loadStarted { url }; the loading overlay shows unless the app uses the loading option |
| Success | Rows replaced or appended, loadFinished { url, count }, overlay hidden |
| Failure | loadFailed { url, message } and an error event (load-failed or parse-failed), overlay hidden, the Promise rejects |
New loadUrl | Cancels 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.
Gallery example: import-csv
Gallery example: import-xml
Gallery example: load-url
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.
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' } });| Option | Meaning | Default |
|---|---|---|
sheet | Sheet name or a number counted from 1 | first sheet |
headerRow | Header line (counted from the top of the range if there is one). 0 means no header and the keys are c1…cN | 1 |
columns | Header text → column id | none |
range | Cells to read ('A1:F500') | all |
maxRows | Row limit. More throws limit-exceeded | 100000 |
dates | Date cells: 'date' (Date), 'iso' (YYYY-MM-DD text), 'serial' (Excel serial number) | 'date' when reading, 'iso' for api.importXlsx |
trim | Trim spaces around text | false |
mode | (api.importXlsx only) 'replace' swaps all rows, 'append' adds after them | 'replace' |
typed | (api.importXlsx only) Convert values to the column kinds | true |
- 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/Aare read asnulland listed inwarnings. - Repeated headers become
name_2, and an empty header is named by its column number, such asc3. - 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 inwarnings.
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).
code | Cause |
|---|---|
corrupt | Not an xlsx (ZIP) file, or damaged |
encrypted | The file is password-protected |
unsupported | A format that is not accepted: old .xls, .xlsb, ZIP64 |
limit-exceeded | Over 200 MB unpacked, 200 entries, a compression ratio of 100, or maxRows |
sheet-not-found | The chosen sheet does not exist |
invalid-option | An 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.
Gallery example: xlsx-import-basic
Gallery example: xlsx-import-mapping
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.
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.
| Key | Meaning | Default |
|---|---|---|
accept | Array of formats 'csv' | 'xlsx' | 'json' | 'xml' | all four |
mode | 'replace' swaps the rows, 'append' adds after them | 'replace' |
maxSize | File size limit in bytes. A larger file is not imported and the user is told | 50 MB |
columns | Header text → column id | none |
overlayText | Text shown while dragging: a string or { ko, en } | the default for the grid language |
The flow:
- 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.
- 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. - If the
beforeFileImport({ file })hook returnsfalsethe file is not imported. A throwing hook emits anerrorevent and the import goes on. - The size and format are checked, the file is read, and
setRowsoraddRowsruns. On successfileImported { name, type, rowCount, warnings }fires and a line above the grid shows the result. - On failure an
errorevent (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.
Gallery example: file-drop-basic
Gallery example: file-drop-append