# CSV Import

> Bring rows in from a spreadsheet: match its columns to fields, preview, and see which rows are skipped and why.

Page: https://uicontext.com/docs/components/csv-import

Group: Forms.

## When to use

Bring rows in from a spreadsheet: match its columns to fields, preview, and see which rows are skipped and why. Use [Dropzone](https://uicontext.com/docs/components/dropzone.md) instead when the file is kept as it is, not read into records.

## Usage

```ts
import { CsvImport } from "./ui/uicontext/components/CsvImport.ts"

export const ImportProducts = <M>(h: Html.H<M>, onImport: (rows: ReadonlyArray<Record<string, string>>) => M) =>
	CsvImport(h, {
		props: {
			noun: "product",
			fields: [
				{ key: "sku", label: "SKU", required: true },
				{ key: "name", label: "Name", required: true },
				{ key: "price", label: "Price", kind: "number" },
			],
		},
		onEmit: { RequestedImport: ({ rows }) => onImport(rows) },
	})
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### Importing contacts

Try the sample file: its columns are matched by name, and the rows with no email or a bad one are skipped.

```ts title="src/demo.ts" source="www/src/examples/csv-import/demo.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { CsvImport, type ImportField } from "./ui/uicontext/components/CsvImport.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, font, space } from "./ui/uicontext/components/tokens.stylex.ts"

const styles = stylex.create({
	wrap: { display: "grid", gap: space.md, inlineSize: "min(100%, 44rem)" },
	note: { margin: 0, fontSize: font.sm, color: color.muted },
})

const fields: ReadonlyArray<ImportField> = [
	{ key: "email", label: "Email", kind: "email", required: true, aliases: ["E-mail address", "Mail"] },
	{ key: "name", label: "Name", aliases: ["Full name"] },
	{ key: "company", label: "Company", aliases: ["Organization", "Account"] },
	{ key: "phone", label: "Phone", aliases: ["Mobile", "Tel"] },
]

// an export from another tool: its own column names, quoted commas, one row with no email and one that's mistyped
const sample = {
	name: "contacts-export.csv",
	text: [
		"Full name,E-mail address,Organization,Mobile,Owner",
		"Ada Okafor,ada@harborview.example,Harborview Supply,+1 415 555 0142,Wei",
		"Tomás García,tomas@northwind-labs.example,\"Northwind Labs, Inc.\",+34 612 555 019,Priya",
		"Priya Raman,priya.raman@example.org,Lumen Health,,Wei",
		"Wei Chen,,Fieldstone Dental,+1 206 555 0199,Ada",
		"Jonas Berg,jonas@@kestrel.example,Kestrel Air,+46 70 555 0123,Ada",
		"Mariam Haddad,mariam@cedarline.example,Cedarline Foods,+961 3 555 012,Priya",
	].join("\n"),
}

const Message = UiSchema.TaggedEnum({ Imported: { count: Schema.Number } })

export const ImportContacts = Html.component({
	name: "ImportContacts",
	model: Schema.Struct({ imported: Schema.NullOr(Schema.Number) }),
	message: Message,
}).make({
	init: () => ({ imported: null }),
	update: { Imported: ($, { count }) => $.evolve({ imported: count }) },
	view: (h, model) =>
		h.div.attrs(sx(styles.wrap)).children(
			CsvImport(h, {
				key: "contacts",
				props: { noun: "contact", fields, sample },
				onEmit: { RequestedImport: ({ rows }) => Message.Imported({ count: rows.length }) },
			}),
			model.imported === null ? null : h.p.attrs(sx(styles.note)).children("The app saves the rows now; this demo keeps nothing."),
		),
})
```

### A required column to pick by hand

Import waits until every required field has a column. Values that don't fit their field are marked in the preview.

```ts title="src/transactions.ts" source="www/src/examples/csv-import/transactions.ts"
import type { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { CsvImport, type ImportField } from "./ui/uicontext/components/CsvImport.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"

const styles = stylex.create({ wrap: { inlineSize: "min(100%, 44rem)" } })

const fields: ReadonlyArray<ImportField> = [
	{ key: "date", label: "Date", kind: "date", required: true, aliases: ["Booking date", "Posted"] },
	{ key: "amount", label: "Amount", kind: "number", required: true },
	{ key: "payee", label: "Payee", aliases: ["Counterparty", "Description"] },
	{ key: "category", label: "Category" },
]

// a bank's export: semicolons, and a column ("Betrag") no name matches, so Amount waits for a pick
const sample = {
	name: "statement-2026-11.csv",
	text: [
		"Booking date;Counterparty;Betrag;Reference",
		"2026-11-02;Cedarline Foods;-84.20;Card 4242",
		"2026-11-03;Payroll;4200.00;Nov salary",
		"2026-11-05;Fieldstone Dental;-120.00;Invoice 2291",
		"2026-11-09;Kestrel Air;-412.65;Flight OSL",
		"2026-11-12;Refund: Lumen Health;35.00;",
		"pending;Harborview Supply;-19.99;Card 4242",
	].join("\n"),
}

export const ImportTransactions = <M>(h: Html.H<M>) =>
	h.div.attrs(sx(styles.wrap)).children(
		CsvImport(h, { key: "statement", props: { id: "statement", noun: "transaction", fields, sample, preview: 4 } }),
	)
```

## API reference

**Props**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `noun` (required) | `string` | — | What a row becomes, singular: "contact". The plural adds an s; give `nouns` otherwise. |
| `nouns` | `string` | — | — |
| `fields` (required) | `ImportField[]` | — | The app's fields, in the order they're matched and shown. |
| `preview` | `number` | `5` | How many rows the preview shows; 5 by default. |
| `maxSize` | `number` | — | The largest file taken, in bytes; 20 MB by default. |
| `sample` | `{ name, text }` | — | A file to try it with, offered under the drop zone: a template with the app's columns. |
| `id` | `string` | `"csv"` | Starts the ids inside it, unique on the page; "csv" by default. |
| `locale` | `string` | — | For the counts; the browser's by default. |

**Events**

| Event | Payload | Description |
| --- | --- | --- |
| `RequestedImport` | `{ rows: (Record<string, string>)[]; skipped: number }` | Import was pressed: the rows that passed, keyed by field, and how many were skipped. |

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/csv-import
```

With npm: `npx shadcn@latest add checkfu/uicontext/csv-import`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/csv-import`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/csv-import`.

It writes these files:

- `src/ui/uicontext/components/CsvImport.ts`
- `src/ui/uicontext/components/FileList.ts`
- `src/ui/uicontext/components/FormControls.ts`
- `src/ui/uicontext/components/IconStroke.ts`
- `src/ui/uicontext/components/ShowText.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/domain/Format.ts`
- `src/ui/uicontext/components/domain/Outcome.ts`
- `src/ui/uicontext/components/domain/Upload.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`
- `src/ui/uicontext/components/upload/Dropzone.ts`
- `src/ui/uicontext/components/upload/Receive.ts`
- `src/ui/uicontext/components/upload/parts.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/CsvImport.ts](https://github.com/checkfu/uicontext/blob/main/src/CsvImport.ts)

## Related

- [Form](https://uicontext.com/docs/components/form.md) (`form`): A form built from one Effect Schema. Errors read in plain words, and focus goes to the first field to fix.
- [Form Layout](https://uicontext.com/docs/components/form-layout.md) (`form-layout`): Labels, hints and sections for a form, with a save bar that guards unsaved changes.
- [Repeating Fields](https://uicontext.com/docs/components/repeating-fields.md) (`repeating-fields`): Rows of fields to add, remove and reorder, such as invites or line items.
- [Form Wizard](https://uicontext.com/docs/components/form-wizard.md) (`form-wizard`): A long form in steps. Each step checks its own fields, and progress survives a reload.
- [Date Field](https://uicontext.com/docs/components/date-field.md) (`date-field`): A date typed part by part in the reader's order, with an error that says what's wrong.
- [Date Picker](https://uicontext.com/docs/components/date-picker.md) (`date-picker`): A date field with a calendar. Type words like “next fri”, or pick from the keyboard.
