# Configuring Data Import

Canonical page: https://www.adaptabletools.com/docs/handbook-importing-configuring

- AdapTable provides built-in handling for CSV and JSON files, and a default path for pasted text
- Developers can replace or extend those with `fileHandlers`, customise paste parsing with `textHandler`, or take full control of applying imported rows with `handleImportedData`

[`DataImportOptions`](https://www.adaptabletools.com/docs/reference/dataimportoptions.md) defines these **stable** properties for Data Import:

| Property                              | Purpose                                                                                                                                                      |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `fileHandlers`                        | Custom or replacement parsers for uploaded files (see below)                                                                                                 |
| `textHandler`                         | Parse pasted text into row objects (see [Text Import](https://www.adaptabletools.com/docs/handbook-importing-configuring/index.md#text-import))                                |
| `validate`                            | Per-row validation before apply — see [Validating Import Data](https://www.adaptabletools.com/docs/handbook-importing/index.md#validating-import-data)                         |
| `handleImportedData` | Apply imported data yourself instead of default grid update (see [Custom Apply](https://www.adaptabletools.com/docs/handbook-importing-configuring/index.md#custom-apply)) |

Other fields on [`DataImportOptions`](https://www.adaptabletools.com/docs/reference/dataimportoptions.md) are documented in the reference only.

## Custom File Handlers

AdapTable ships with 2 File Handlers for Data Import: CSV and JSON.

However developers can provide custom file handlers where required.

These can either override an AdapTable-shipped file handler, or handle a different file type

This is done via the `fileHandlers` property in [Data Import Options](https://www.adaptabletools.com/docs/technical-reference-importing/index.md).

### `fileHandlers`

Custom File Handlers to use for Data Import

  [`DataImportFileHandler`](https://www.adaptabletools.com/docs/reference/dataimportfilehandler.md)

Allows developers to provide custom File Handlers for Data Import where the shipped File Handlers are insufficient.

The custom File Handler can either:

- replace one of the File Handlers provided by AdapTable (CSV or JSON)
- handle a different type of File

The [`DataImportFileHandler`](https://www.adaptabletools.com/docs/reference/dataimportfilehandler.md) is defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [fileExtension](https://www.adaptabletools.com/docs/reference/dataimportfilehandler.md#fileextension) | `string` | Name of File Extension |
| [handleFile](https://www.adaptabletools.com/docs/reference/dataimportfilehandler.md#handlefile) | `(file: File) => Promise<T[]>` | Async function which handles the import returning a Data Record |

The `handleFile` property returns the data in the form of `Record<string, any>[]` (one object per imported row).

The File Handlers are typically just referenced in Data Import Options:

```ts {2}
dataImportOptions: {
  fileHandlers: [csvFileHandler],
},
```

and defined elsewhere:

```ts {1}
const csvFileHandler: DataImportFileHandler<Record<string, any>> = {
  fileExtension: '.csv',
  handleFile: (file: File) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = event => {
        const content = event.target?.result as string;
        resolve(parseCSV(content));
      };
      reader.readAsText(file);
    });
  },
};

export const parseCSV = (content: string): Record<string, unknown>[] => {
  const SEPARATOR = '|';
  const lines = content.split('\n');
  const headers = lines[0].split(SEPARATOR);
  const data = [];

  if (lines.length <= 1) {
    return [];
  }

  for (let i = 1; i < lines.length; i++) {
    const values = lines[i].split(SEPARATOR);
    if (values.length === headers.length) {
      const item: Record<string, unknown> = {};
      for (let j = 0; j < headers.length; j++) {
        const value = values[j];

        // Any string that looks like a number it is converted to number
        item[headers[j]] =
          value === '' || isNaN(Number(value)) ? value : Number(value);
      }
      data.push(item);
    }
  }
  return data;
};
```

**Example: Data Import - Custom CSV File Handler**

Custom file handlers.

- This example overrides the CSV file handler provided by AdapTable with a custom file handler, that parses CSV using a different (|) delimiter
- Click to download <DownloadFile href="/data/updateframeworks-pipe.csv">updateframeworks-pipe.csv</DownloadFile>, then upload it in the Data Import wizard — it will be parsed by the custom file handler
- We have added [Flashing Cells](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md) to the grid (and increased duration to 3 seconds) so you can see the changes to the first 2 rows

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableOptions,
  DataImportFileHandler,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

/**
 * Custom parser that uses | for separator
 */
export const parseCSV = (content: string): Record<string, unknown>[] => {
  const SEPARATOR = '|';
  const lines = content.split('\n');
  const headers = lines[0].split(SEPARATOR);
  const data = [];

  if (lines.length <= 1) {
    return [];
  }

  for (let i = 1; i < lines.length; i++) {
    const values = lines[i].split(SEPARATOR);
    if (values.length === headers.length) {
      const item: Record<string, unknown> = {};
      for (let j = 0; j < headers.length; j++) {
        const value = values[j];

        // Any string that looks like a number is converted to number
        // Note: this converts 00012345 to 12345 or a value with potential scientific notation to a number
        item[headers[j]] =
          value === '' || isNaN(Number(value)) ? value : Number(value);
      }
      data.push(item);
    }
  }
  return data;
};

// Custom CSV File Handler
const csvFileHandler: DataImportFileHandler<Record<string, any>> = {
  fileExtension: '.csv',
  handleFile: (file: File) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = event => {
        const content = event.target?.result as string;
        resolve(parseCSV(content));
      };
      reader.readAsText(file);
    });
  },
};

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom CSV File Handler',
  dataImportOptions: {
    fileHandlers: [csvFileHandler],
  },
  initialState: {
    Dashboard: {
      ModuleButtons: ['DataImport'],
    },
    FlashingCell: {
      FlashingCellDefinitions: [
        {
          Name: 'Flashing_Cell_Any_Change',
          Scope: {
            All: true,
          },
          Rule: 'ANY_CHANGE()',
          FlashDuration: 3000,
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'github_stars',
            'language',
            'license',
            'github_watchers',
            'has_projects',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

## Text Import

When the user imports via **Text** in the wizard, AdapTable passes the pasted string to `textHandler` (if provided). 

The function should return an array of row objects (or a Promise of that array), using the same shapes as file-based import.

If you omit `textHandler`, AdapTable uses its built-in parsing for pasted content

### `textHandler`

Parse pasted text into rows for Data Import

```ts
textHandler?: (text: string) => T[] | Promise<T[]>;
```

Use this when your users paste tab-separated values, fixed-width extracts, or other formats that differ from the default.

## Custom Apply

By default, after the wizard finishes, AdapTable applies imported rows to the grid (updates and adds) using the primary key. 

- If you provide `handleImportedData`, AdapTable **does not** run that default apply
- You are responsible for updating the grid (for example via `context.adaptableApi.gridApi`)

When your handler finishes, you can return a [`HandleImportedDataResolution`](https://www.adaptabletools.com/docs/reference/handleimporteddataresolution.md) with `addedRows`, `updatedRows`, and `emitDataImportedEvent: true` if you want the `DataImported` event to fire. 

If you return nothing (`void`), no automatic grid update and no event occurs.

See [Data Imported event](https://www.adaptabletools.com/docs/technical-reference-importing/index.md#data-imported-event) and [`DataImportApi`](https://www.adaptabletools.com/docs/reference/dataimportapi.md) for related run-time APIs.

### `handleImportedData`

Handle imported data and apply it to the grid, or replace default application

```ts
handleImportedData?: (
  context: HandleImportedDataContext<T>
) => Promise<void | HandleImportedDataResolution>;
```
