CsvImport
Bringing a spreadsheet into a table: drop the file, say which column of the file goes where (matched by name first), look at the first rows as they will be saved, then import. Rows that cannot be saved are counted before and can be downloaded after.
import { Wizard, FileDrop, Select } from '@sypnia/ui/react'
On a desktop
Press «Use a sample file» (or drop a CSV), check the matching, look at the preview and import. Two rows have a bad email: they are skipped and offered back.
Import into customers
Rows from a CSV file are added to the table customers. Nothing changes until the last step.
- Choose the file
- Match the columns
- Check the first rows
Choose the file
Up to 50 MB. The first line must hold the names of the columns.
Code
import { useEffect, useState, type ReactNode } from 'react';
import {
Alert, Button, Callout, DownloadButton, EmptyState, Field, FileDrop, Page, PageHeader, Panel, Progress,
Select, SkeletonOf, Stack, Table, Wizard, useSypnia, type Column,
} from '@sypnia/ui/react';
// Bringing a spreadsheet into a table: drop the file, say which column of the file goes to which column of the table
// (matched by name first), look at the first rows as they will be saved, then import. Rows that cannot be saved are
// counted before importing and can be downloaded afterwards, with the reason on each.
const en = {
title: 'Import into customers', lead: 'Rows from a CSV file are added to the table customers. Nothing changes until the last step.', label: 'Import a CSV',
s1: 'Choose the file', drop: 'The CSV file', dropHint: 'Up to 50 MB. The first line must hold the names of the columns.', sample: 'Use a sample file', noFile: 'Choose a CSV file first.',
read: (n: number, f: string) => `${f}: ${n} rows and the names of its columns.`,
s2: 'Match the columns', s2Lead: 'Each column of the file goes to a column of customers, or is skipped. Columns with the same name are matched already.',
fileCol: 'Column in the file', tableCol: 'Column in customers', skip: 'Skip this column', needEmail: 'Match a column of the file to email: every customer needs one.',
s3: 'Check the first rows', s3Lead: 'This is how the first rows will be saved.', bad: (n: number) => `${n} rows have an email that is not valid. They will be skipped; you can download them after.`,
finish: (n: number) => `Import ${n} rows`, importing: 'Importing', importingOf: (a: number, b: number) => `${a} of ${b} rows`,
done: (n: number) => `${n} rows were added to customers`, skipped: (n: number) => `${n} rows were skipped because their email is not valid. Download them, fix them and import them again.`,
downloadSkipped: 'Download skipped rows', open: 'Open customers', again: 'Import another file',
failed: 'This file cannot be read', failedBody: 'It does not look like a CSV: the first line has no column names. Save it from your spreadsheet as «CSV UTF-8» and try again.',
cols: { email: 'email', name: 'name', company: 'company', country: 'country', created_at: 'created_at' },
};
const es: typeof en = {
title: 'Importar a customers', lead: 'Las filas de un archivo CSV se agregan a la tabla customers. Nada cambia hasta el último paso.', label: 'Importar un CSV',
s1: 'Elige el archivo', drop: 'El archivo CSV', dropHint: 'Hasta 50 MB. La primera línea debe tener los nombres de las columnas.', sample: 'Usar un archivo de ejemplo', noFile: 'Primero elige un archivo CSV.',
read: (n: number, f: string) => `${f}: ${n} filas y los nombres de sus columnas.`,
s2: 'Empareja las columnas', s2Lead: 'Cada columna del archivo va a una columna de customers, o se omite. Las columnas con el mismo nombre ya están emparejadas.',
fileCol: 'Columna del archivo', tableCol: 'Columna en customers', skip: 'Omitir esta columna', needEmail: 'Empareja una columna del archivo con email: cada cliente necesita uno.',
s3: 'Revisa las primeras filas', s3Lead: 'Así se guardarán las primeras filas.', bad: (n: number) => `${n} filas tienen un correo que no es válido. Se omitirán; puedes descargarlas después.`,
finish: (n: number) => `Importar ${n} filas`, importing: 'Importando', importingOf: (a: number, b: number) => `${a} de ${b} filas`,
done: (n: number) => `Se agregaron ${n} filas a customers`, skipped: (n: number) => `Se omitieron ${n} filas porque su correo no es válido. Descárgalas, corrígelas e impórtalas de nuevo.`,
downloadSkipped: 'Descargar filas omitidas', open: 'Abrir customers', again: 'Importar otro archivo',
failed: 'Este archivo no se puede leer', failedBody: 'No parece un CSV: la primera línea no tiene nombres de columnas. Guárdalo desde tu hoja de cálculo como «CSV UTF-8» e intenta de nuevo.',
cols: { email: 'email', name: 'name', company: 'company', country: 'country', created_at: 'created_at' },
};
const tableCols = ['email', 'name', 'company', 'country', 'created_at'];
const firstNames = ['Ana', 'Luis', 'Marta', 'Kenji', 'Sofía', 'Omar', 'Lena', 'Tomás', 'Aiko', 'Pablo'];
const sampleCsv = ['Email,Full name,Company,Country,Signed up', ...Array.from({ length: 248 }, (_, i) => {
const n = firstNames[i % 10];
const email = i % 97 === 13 ? `${n.toLowerCase()}.at.example` : `${n.toLowerCase()}${i}@example.com`;
return `${email},${n} ${String.fromCharCode(65 + (i % 26))}.,${['Acme', 'Lumen', 'Northwind', 'Globex'][i % 4]},${['CO', 'ES', 'MX', 'US'][i % 4]},2026-${String((i % 11) + 1).padStart(2, '0')}-0${(i % 9) + 1}`;
})].join('\n');
// A small CSV reader: commas, quotes and doubled quotes.
const parse = (text: string) => text.trim().split(/\r?\n/).map((line) => {
const out: string[] = []; let cur = '', q = false;
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if (q) { if (ch === '"' && line[i + 1] === '"') { cur += '"'; i++; } else if (ch === '"') q = false; else cur += ch; }
else if (ch === '"') q = true; else if (ch === ',') { out.push(cur); cur = ''; } else cur += ch;
}
out.push(cur); return out;
});
const guess = (h: string) => { const k = h.toLowerCase().replace(/[^a-z]/g, ''); return k.includes('mail') ? 'email' : k.includes('name') ? 'name' : k.includes('company') ? 'company' : k.includes('country') ? 'country' : k.includes('sign') || k.includes('created') ? 'created_at' : ''; };
const isEmail = (e: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);
export default function CsvImport({ state = 'ready' }: { state?: 'ready' | 'loading' | 'error' }) {
const { locale } = useSypnia();
const c = locale.startsWith('es') ? es : en;
const [files, setFiles] = useState<File[]>([]);
const [fileName, setFileName] = useState('');
const [data, setData] = useState<string[][] | null>(null);
const [map, setMap] = useState<string[]>([]);
const [unreadable, setUnreadable] = useState(false);
const [phase, setPhase] = useState<'wizard' | 'importing' | 'done'>('wizard');
const [progress, setProgress] = useState(0);
const load = (text: string, name: string) => {
const rows = parse(text);
if (state === 'error' || rows.length < 2 || rows[0].every((h) => !h.trim())) { setUnreadable(true); setData(null); return; }
setUnreadable(false); setFileName(name); setData(rows); setMap(rows[0].map(guess));
};
useEffect(() => { if (files[0]) void files[0].text().then((t) => load(t, files[0].name)); }, [files]); // eslint-disable-line react-hooks/exhaustive-deps
const body = data ? data.slice(1) : [];
const emailAt = map.indexOf('email');
const good = body.filter((r) => emailAt >= 0 && isEmail(r[emailAt] ?? ''));
const badCount = body.length - good.length;
useEffect(() => {
if (phase !== 'importing') return;
if (progress >= good.length) { setPhase('done'); return; }
const t = setTimeout(() => setProgress((p) => Math.min(good.length, p + 40)), 120);
return () => clearTimeout(t);
}, [phase, progress, good.length]);
const header = <PageHeader title={c.title} lead={c.lead} />;
// Loading: the real wizard on its first step; the drop zone and the sample wait in their own boxes until the
// table's columns (which the next step maps to) have come.
const loading = state === 'loading';
const wait = (n: ReactNode) => (loading ? <SkeletonOf>{n}</SkeletonOf> : n);
if (phase === 'importing') {
return <Page>{header}<Panel title={c.importing}><Progress label={c.importing} value={progress} max={good.length} detail={c.importingOf(progress, good.length)} /></Panel></Page>;
}
if (phase === 'done') {
return (
<Page>{header}
<Panel>
<EmptyState icon="success" title={c.done(good.length)}
actions={<><Button variant="primary" href="#customers">{c.open}</Button>{badCount > 0 && <DownloadButton href="#skipped.csv" filename="skipped-rows.csv">{c.downloadSkipped}</DownloadButton>}<Button variant="quiet" onClick={() => { setPhase('wizard'); setData(null); setFiles([]); setProgress(0); }}>{c.again}</Button></>}>
{badCount > 0 ? c.skipped(badCount) : null}
</EmptyState>
</Panel>
</Page>
);
}
type Pair = { i: number; head: string };
const pairs: Pair[] = (data?.[0] ?? []).map((head, i) => ({ i, head }));
const mapped = map.map((m, i) => ({ m, i })).filter((x) => x.m);
const previewCols: Column<string[]>[] = mapped.map(({ m, i }) => ({ id: m, header: m, cell: (r) => r[i] }));
return (
<Page>
{header}
<Panel>
<Wizard label={c.label} finishLabel={c.finish(good.length)} onFinish={() => { setProgress(0); setPhase('importing'); }} steps={[
{ id: 'file', title: c.s1, validate: () => (data ? undefined : c.noFile), content: (
<Stack gap={4}>
<Field label={c.drop} hint={c.dropHint}>{wait(<FileDrop accept={['.csv', 'text/csv']} maxSize={50 * 1024 * 1024} files={files} onChange={setFiles} />)}</Field>
<div>{wait(<Button icon="csv" onClick={() => load(sampleCsv, 'customers-2026.csv')}>{c.sample}</Button>)}</div>
{unreadable && <Alert tone="fail" title={c.failed}>{c.failedBody}</Alert>}
{data && <Callout kind="ok">{c.read(body.length, fileName)}</Callout>}
</Stack>
) },
{ id: 'map', title: c.s2, validate: () => (emailAt >= 0 ? undefined : c.needEmail), content: (
<Stack gap={4}>
<p>{c.s2Lead}</p>
<Table label={c.s2} rows={pairs} rowKey={(p) => p.i} columns={[
{ id: 'file', header: c.fileCol, cell: (p) => <b>{p.head}</b> },
{ id: 'table', header: c.tableCol, cell: (p) => (
<Select aria-label={`${c.tableCol}: ${p.head}`} size="sm" value={map[p.i] || 'skip'}
options={[...tableCols.map((t) => ({ value: t, label: t, disabled: map.includes(t) && map[p.i] !== t })), { value: 'skip', label: c.skip }]}
onChange={(v) => setMap((m) => m.map((x, j) => (j === p.i ? (v === 'skip' ? '' : v) : x)))} />
) },
]} />
</Stack>
) },
{ id: 'preview', title: c.s3, content: (
<Stack gap={4}>
<p>{c.s3Lead}</p>
{badCount > 0 && <Alert tone="warn" title={c.bad(badCount)} />}
<Table label={c.s3} rows={body.slice(0, 5)} rowKey={(r) => r.join('|')} columns={previewCols} />
</Stack>
) },
]} />
</Panel>
</Page>
);
} On a phone
On a phone the matching becomes one card per column of the file.
When the file cannot be read
Choose any file here: the message says why it cannot be read and how to save it so it can.
Import into customers
Rows from a CSV file are added to the table customers. Nothing changes until the last step.
- Choose the file
- Match the columns
- Check the first rows
Choose the file
Up to 50 MB. The first line must hold the names of the columns.
Skeleton
The real wizard on its first step while the table's columns load; the drop zone and the sample file wait in their own boxes.
Import into customers
Rows from a CSV file are added to the table customers. Nothing changes until the last step.
- Choose the file
- Match the columns
- Check the first rows
Choose the file
Up to 50 MB. The first line must hold the names of the columns.
When to use it
Use it when
- Filling a table from a spreadsheet or another system.
- Saying before importing how many rows will be skipped and why.
Do not use it when
- Importing straight after the upload: people need to see the matching and the first rows first.
- Failing the whole import for a few bad rows: skip them, count them, offer them back.
For everyone
- Each step's title takes the focus; the stepper says which step of how many.
- Each column's choice is a select named with the column of the file.
- The progress of the import says how many rows of how many, in words.
Props
| Wizard | Type | Default |
|---|---|---|
finishLabelrequiredWhat the last button does: «Connect the database». | string | |
labelrequired | string | |
onFinishrequired | () => void | Promise<void> | |
stepsrequired | WizardStep[] | |
busy | boolean | |
onCancel | (() => void) |
| FileDrop | Type | Default |
|---|---|---|
acceptWhat it takes: extensions (`.csv`) or types (`text/csv`, `image/*`). Anything else is refused with a message. | string[] | |
aria-describedby | string | |
aria-labelThe name for screen readers when there is no Field around it. | string | |
aria-labelledby | string | |
childrenThe sentence inside the zone. By default «Drop a file here or choose one». | ReactNode | |
className | string | |
disabled | boolean | |
filesThe chosen files. Leave it out to let the component keep them. | File[] | |
idInside a Field it comes from the Field. | string | |
invalidMarks the value as wrong. Inside a `<Field error>` it is set for you. | boolean | |
maxSizeThe largest file it takes, in bytes. | number | |
multipleTakes several files. With one, a new file replaces the old one. | boolean | |
onChange | ((files: File[]) => void) |
| Select | Type | Default |
|---|---|---|
optionsrequired | Option[] | |
aria-describedby | string | |
aria-labelThe name for screen readers when there is no Field around it. | string | |
aria-labelledby | string | |
className | string | |
defaultValue | string | |
disabled | boolean | |
idInside a Field it comes from the Field. | string | |
invalidMarks the value as wrong. Inside a `<Field error>` it is set for you. | boolean | |
nameThe name of the value when it travels in a form. | string | |
onChange | ((value: string) => void) | |
placeholderShown while nothing is chosen. | string | |
size | "sm" | "md" | "lg" | |
valueThe chosen value. Leave it out (and use `defaultValue`) to let the component keep it. | string | null |