Ir al contenido

CsvImport

Traer una hoja de cálculo a una tabla: suelta el archivo, di qué columna del archivo va a dónde (emparejadas primero por nombre), mira las primeras filas tal como se guardarán, e importa. Las filas que no se pueden guardar se cuentan antes y se pueden descargar después.

import { Wizard, FileDrop, Select } from '@sypnia/ui/react'

En esta página
  1. En un computador
  2. En un celular
  3. Cuando el archivo no se puede leer
  4. Skeleton
  5. Cuándo usarlo
  6. Para todos
  7. Props

En un computador

Pulsa «Usar un archivo de ejemplo» (o suelta un CSV), revisa el emparejamiento, mira la vista previa e importa. Dos filas tienen un correo malo: se omiten y se ofrecen de vuelta.

Importar a customers

Las filas de un archivo CSV se agregan a la tabla customers. Nada cambia hasta el último paso.

  1. Elige el archivo
  2. Empareja las columnas
  3. Revisa las primeras filas

Elige el archivo

Suelta un archivo aquí o elige uno

Hasta 50 MB. La primera línea debe tener los nombres de las columnas.

Código
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>
  );
}

En un celular

En un celular el emparejamiento queda en una tarjeta por cada columna del archivo.

Cuando el archivo no se puede leer

Elige cualquier archivo aquí: el mensaje dice por qué no se puede leer y cómo guardarlo para que sí.

Importar a customers

Las filas de un archivo CSV se agregan a la tabla customers. Nada cambia hasta el último paso.

  1. Elige el archivo
  2. Empareja las columnas
  3. Revisa las primeras filas

Elige el archivo

Suelta un archivo aquí o elige uno

Hasta 50 MB. La primera línea debe tener los nombres de las columnas.

Skeleton

El asistente real en su primer paso mientras cargan las columnas de la tabla; la zona para soltar y el archivo de ejemplo esperan en sus propias cajas.

Importar a customers

Las filas de un archivo CSV se agregan a la tabla customers. Nada cambia hasta el último paso.

  1. Elige el archivo
  2. Empareja las columnas
  3. Revisa las primeras filas

Elige el archivo

Hasta 50 MB. La primera línea debe tener los nombres de las columnas.

Cuándo usarlo

Úsalo cuando

  • Llenar una tabla desde una hoja de cálculo u otro sistema.
  • Decir antes de importar cuántas filas se omitirán y por qué.

No lo uses cuando

  • Importar apenas se sube el archivo: la gente necesita ver el emparejamiento y las primeras filas primero.
  • Hacer fallar toda la importación por unas pocas filas malas: omítelas, cuéntalas, ofrécelas de vuelta.

Para todos

  • El título de cada paso toma el foco; el indicador dice qué paso de cuántos.
  • La elección de cada columna es una lista nombrada con la columna del archivo.
  • El avance de la importación dice cuántas filas de cuántas, en palabras.

Props

WizardTipoPor defecto
finishLabelobligatorio

What the last button does: «Connect the database».

string
labelobligatorio string
onFinishobligatorio () => void | Promise<void>
stepsobligatorio WizardStep[]
busy boolean
onCancel (() => void)
FileDropTipoPor defecto
accept

What it takes: extensions (`.csv`) or types (`text/csv`, `image/*`). Anything else is refused with a message.

string[]
aria-describedby string
aria-label

The name for screen readers when there is no Field around it.

string
aria-labelledby string
children

The sentence inside the zone. By default «Drop a file here or choose one».

ReactNode
className string
disabled boolean
files

The chosen files. Leave it out to let the component keep them.

File[]
id

Inside a Field it comes from the Field.

string
invalid

Marks the value as wrong. Inside a `<Field error>` it is set for you.

boolean
maxSize

The largest file it takes, in bytes.

number
multiple

Takes several files. With one, a new file replaces the old one.

boolean
onChange ((files: File[]) => void)
SelectTipoPor defecto
optionsobligatorio Option[]
aria-describedby string
aria-label

The name for screen readers when there is no Field around it.

string
aria-labelledby string
className string
defaultValue string
disabled boolean
id

Inside a Field it comes from the Field.

string
invalid

Marks the value as wrong. Inside a `<Field error>` it is set for you.

boolean
name

The name of the value when it travels in a form.

string
onChange ((value: string) => void)
placeholder

Shown while nothing is chosen.

string
size "sm" | "md" | "lg"
value

The chosen value. Leave it out (and use `defaultValue`) to let the component keep it.

string | null
  1. En un computador
  2. En un celular
  3. Cuando el archivo no se puede leer
  4. Skeleton
  5. Cuándo usarlo
  6. Para todos
  7. Props

    Busca páginas, secciones y términos