# Spreadsheet import — drop a CSV, map its columns, one record per row

> Bring a CSV or TSV file (exported from Excel, Numbers or Google Sheets) into the app as one record per row: the person picks the file, a mapping step shows the first five rows with a guessed field per column they can change and the key column that matches rows, rows are written in batches with a progress count, importing the same file again updates rows and adds none twice, the result says how many were added, updated and skipped and why, and each imported row belongs to its importer or to the person a chosen column names. Use for importing an existing list of clients, contacts, jobs, stock or members from a spreadsheet; a short list typed or pasted into a form does not need it

Source: https://good.vibes.diy/docs/reference/spreadsheet-import

**The moment this is for: someone's clients, jobs or stock already live in a spreadsheet, and the app becomes theirs the minute that sheet is in it.** A dog groomer with 400 clients, an office manager with the supplier list, a coach with last season's roster: they pick the file, check that the app read the columns the way they meant, and watch the rows arrive. Pasting a short list into a form stays the quick way for a dozen rows; this is the way for hundreds.

Signal words: import, upload my spreadsheet, my clients are in a sheet, CSV, TSV, Excel, Google Sheets, export from, bring in my list, migrate from another app.

## The four steps

An import is four screens in one card, in this order: **pick → match columns → write → result**. Each step replaces the one before it, and the result step offers another import.

**1. Pick.** `<input type="file" accept=".csv,.tsv,text/csv,text/tab-separated-values">`, hidden, opened from a `Button` in the app's words ("Import clients from a spreadsheet"). One line under the button says what to bring: "A CSV or TSV file. From Excel, Numbers or Google Sheets, use File › Download (or Save as) › CSV." Read the picked file with `await file.text()`.

**The file is parsed in the page, in plain code; no model reads it.** Parsing a thousand rows is a loop, and a loop is exact, instant and free: `callAI` never sees the file, its rows or its cells. The parser reads the quoting rules every spreadsheet writes:

- a leading byte-order mark (`\uFEFF`) is dropped, and `\r\n`, `\n` and `\r` all end a row;
- the delimiter is a tab for a `.tsv` file, and otherwise whichever of tab, `;` and `,` splits the header line into the most cells (a sheet saved in many European locales uses `;`);
- a cell that starts with `"` runs to its closing quote, keeping delimiters and line breaks inside it, and `""` inside it is one `"`;
- the first row is the header; a blank header becomes "Column 3"; rows with every cell empty are dropped; a short row reads its missing cells as empty.

**2. Match columns.** **The mapping step shows the first five rows and a guess for every column.** A `Table` of the first five rows under the file's own headers, so the person sees their data, then one `Select` per column: the app's fields plus "Leave out", preset to a guess from the header (`Email`, `E-mail` and `email address` all guess Email; an exact header match wins over a partial one, and each field is guessed for one column at most). The person changes any guess before anything is written. Two more choices sit beside them:

- **Match rows by** — the key column, guessed as the email column, then the name column. Its value makes the record's id, so the same row imported twice is one record.
- **Whose rows** (only when the app's records belong to people) — "Mine" or a column of handles, guessed from a header like `Assigned to`, `Owner` or `Handle`.

The step's lead button names the count: "Import 1,000 rows".

**3. Write.** **Each row's `_id` comes from the key column, so importing the same file again adds nothing twice.** The id is the record type, the row's owner and the key cell, trimmed and lowercased: `"client:" + ownerHandle + ":" + key`. Two people who each import their own sheet with the same email get two records, each theirs, and a second import of the same file finds every id already there. A row whose fields all match the stored record is left alone (no write at all), and a changed row is merged over the stored one, so fields the app added since (a stage, notes) stay. Read the stored records once, from the live query the app already has, into a `Map` by `_id`, rather than one `database.get` per row.

**Rows are written in batches of 50, and the count moves after each batch.** Slice the records 50 at a time, `await Promise.all(batch.map((doc) => database.put(doc)))`, then set the written count, so a `Progress` bar and "Writing 350 of 1,000" move while the rows land. Never one `put` per render or a thousand `put`s at once.

**4. Result.** One line: "412 added, 3 updated, 585 already up to date, 2 skipped", then the skipped rows, each with its line number in the file and the reason in the person's words: "Line 14: no email", "Line 230: same email as line 12", "Line 311: Balance "n/a" is not a number". A skipped row never stops the import. Number fields strip currency signs, spaces and thousands commas before `Number(...)`; a cell that still is not a number skips its row.

## Who sees the imported rows

**Imported rows belong to the person the owner column names, or to the importer.** Each record carries `ownerHandle` (whose row it is) and `authorHandle` (who wrote it). `access.js` routes it to `clients:<ownerHandle>`, granted to that person and the writer, so a member sees the rows filed under their own handle and nobody else's. Filing a row under someone else's handle is the app owner's (`ctx.requireRole("owner")`); anyone signed in imports rows of their own. Gate the import button on `can.create` of a representative row, as every write surface is.

## Worked example — a client tracker with an import

### `App.jsx`
```jsx
import React, { useMemo, useRef, useState } from "react";
import { useFireproof } from "use-fireproof";
import { useViewer, useVibe } from "use-vibes";
import { Badge, Button, Card, Empty, Field, Heading, Row, RowCard, Skeleton, Stack, Table, Text } from "@vibes.diy/ui";
import { Progress, Select } from "@vibes.diy/ui/interactive";

const FIELDS = [
  { key: "name", label: "Name", guess: ["name", "full name", "client", "customer", "contact"] },
  { key: "email", label: "Email", guess: ["email", "e mail", "email address", "mail"] },
  { key: "phone", label: "Phone", guess: ["phone", "mobile", "cell", "tel"] },
  { key: "company", label: "Company", guess: ["company", "business", "organization"] },
  { key: "balance", label: "Balance", number: true, guess: ["balance", "owed", "amount", "due"] },
  { key: "notes", label: "Notes", guess: ["notes", "note", "comments"] },
];
const FIELD_OPTIONS = [{ value: "", label: "Leave out" }, ...FIELDS.map((f) => ({ value: f.key, label: f.label }))];
const BATCH = 50;
const count = (n) => n.toLocaleString();
const words = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();

function pickDelimiter(fileName, text) {
  if (/\.tsv$/i.test(fileName)) return "\t";
  const header = text.split(/\r\n|\n|\r/, 1)[0] ?? "";
  const cells = (d) => header.split(d).length;
  return ["\t", ";", ","].reduce((best, d) => (cells(d) > cells(best) ? d : best), ",");
}

/** Spreadsheet rows: quoted cells keep delimiters and line breaks, and "" inside quotes is one quote. */
function parseSheet(text, delim) {
  const src = text.replace(/^\uFEFF/, "");
  const rows = [];
  let row = [];
  let cell = "";
  let quoted = false;
  for (let i = 0; i < src.length; i++) {
    const ch = src[i];
    if (quoted) {
      if (ch === '"' && src[i + 1] === '"') {
        cell += '"';
        i++;
      } else if (ch === '"') quoted = false;
      else cell += ch;
    } else if (ch === '"' && cell === "") quoted = true;
    else if (ch === delim) {
      row.push(cell);
      cell = "";
    } else if (ch === "\n" || ch === "\r") {
      if (ch === "\r" && src[i + 1] === "\n") i++;
      row.push(cell);
      rows.push(row);
      row = [];
      cell = "";
    } else cell += ch;
  }
  if (cell !== "" || row.length > 0) rows.push([...row, cell]);
  return rows.filter((r) => r.some((c) => c.trim() !== ""));
}

/** One guess per column: exact header matches first, then partial ones, each field used once. */
function guessMapping(headers) {
  const map = headers.map(() => "");
  for (const exact of [true, false]) {
    headers.forEach((h, i) => {
      if (map[i] !== "") return;
      const w = words(h);
      const hit = FIELDS.find((f) => !map.includes(f.key) && f.guess.some((g) => (exact ? w === g : w.includes(g))));
      if (hit) map[i] = hit.key;
    });
  }
  return map;
}

function readSheet(fileName, text) {
  const [head = [], ...rows] = parseSheet(text, pickDelimiter(fileName, text));
  const headers = head.map((h, i) => h.trim() || `Column ${i + 1}`);
  const mapping = guessMapping(headers);
  const keyGuess = [mapping.indexOf("email"), mapping.indexOf("name"), 0].find((i) => i >= 0);
  const ownerGuess = headers.findIndex((h) => /assigned|owner|handle/.test(words(h)));
  return { fileName, headers, rows, mapping, key: String(keyGuess), owner: ownerGuess >= 0 ? String(ownerGuess) : "" };
}

/** The records to write and the rows left out, with the file's own line numbers (the header is line 1). */
function buildRecords(sheet, me) {
  const keyLabel = sheet.headers[Number(sheet.key)].toLowerCase();
  const firstLine = new Map();
  const records = [];
  const skipped = [];
  sheet.rows.forEach((cells, n) => {
    const line = n + 2;
    const key = (cells[Number(sheet.key)] ?? "").trim().toLowerCase();
    if (key === "") return skipped.push({ line, why: `no ${keyLabel}` });
    if (firstLine.has(key)) return skipped.push({ line, why: `same ${keyLabel} as line ${firstLine.get(key)}` });
    firstLine.set(key, line);
    const owner = sheet.owner === "" ? "" : (cells[Number(sheet.owner)] ?? "").trim().replace(/^@/, "");
    const ownerHandle = owner || me;
    const doc = { _id: "client:" + ownerHandle + ":" + key, type: "client", ownerHandle, authorHandle: me };
    for (const [i, field] of sheet.mapping.entries()) {
      if (field === "") continue;
      const raw = (cells[i] ?? "").trim();
      if (FIELDS.find((f) => f.key === field)?.number && raw !== "") {
        const value = Number(raw.replace(/[$€£,\s]/g, ""));
        if (!Number.isFinite(value)) return skipped.push({ line, why: `${sheet.headers[i]} "${raw}" is not a number` });
        doc[field] = value;
      } else doc[field] = raw;
    }
    records.push(doc);
  });
  return { records, skipped };
}

const unchanged = (stored, doc) => Object.keys(doc).every((k) => stored[k] === doc[k]);

function SheetImport({ database, stored, me, onDone }) {
  const fileRef = useRef(null);
  const [sheet, setSheet] = useState(undefined);
  const [written, setWritten] = useState(undefined);
  const plan = useMemo(() => (sheet ? buildRecords(sheet, me) : undefined), [sheet, me]);

  async function onPick(e) {
    const file = e.target.files?.[0];
    e.target.value = "";
    if (file) setSheet(readSheet(file.name, await file.text()));
  }

  async function runImport() {
    const byId = new Map(stored.map((d) => [d._id, d]));
    const tally = { added: 0, updated: 0, same: 0 };
    setWritten(0);
    for (let i = 0; i < plan.records.length; i += BATCH) {
      const batch = plan.records.slice(i, i + BATCH);
      await Promise.all(
        batch.map((doc) => {
          const old = byId.get(doc._id);
          if (old && unchanged(old, doc)) {
            tally.same += 1;
            return undefined;
          }
          tally[old ? "updated" : "added"] += 1;
          return database.put(old ? { ...old, ...doc } : doc);
        })
      );
      setWritten(i + batch.length);
    }
    setSheet(undefined);
    setWritten(undefined);
    onDone({ ...tally, skipped: plan.skipped });
  }

  if (written !== undefined)
    return (
      <Stack gap={2}>
        <Progress value={written} max={plan.records.length} label="Import progress" />
        <Text muted>
          Writing {count(written)} of {count(plan.records.length)}
        </Text>
      </Stack>
    );

  if (sheet === undefined)
    return (
      <Stack gap={2}>
        <input ref={fileRef} type="file" accept=".csv,.tsv,text/csv,text/tab-separated-values" hidden onChange={onPick} />
        <Button onClick={() => fileRef.current?.click()}>Import clients from a spreadsheet</Button>
        <Text size="sm" muted>
          A CSV or TSV file. From Excel, Numbers or Google Sheets, use File › Download (or Save as) › CSV.
        </Text>
      </Stack>
    );

  const columns = sheet.headers.map((h, i) => ({ key: String(i), header: h, render: (r) => <Text truncate>{r.cells[i] ?? ""}</Text> }));
  const headerOptions = sheet.headers.map((h, i) => ({ value: String(i), label: h }));
  const setMapping = (i, value) => setSheet({ ...sheet, mapping: sheet.mapping.map((m, j) => (j === i ? value : m)) });
  return (
    <Stack gap={4}>
      <Text>
        {sheet.fileName}: {count(sheet.rows.length)} rows. Here are the first five, and how each column comes in.
      </Text>
      <Table rows={sheet.rows.slice(0, 5).map((cells, n) => ({ n, cells }))} getKey={(r) => r.n} columns={columns} />
      <Stack gap={2}>
        {sheet.headers.map((h, i) => (
          <Row key={i} gap={2} wrap={false}>
            <Text truncate>{h}</Text>
            <Select label={`${h} becomes`} value={sheet.mapping[i]} onChange={(v) => setMapping(i, v)} options={FIELD_OPTIONS} />
          </Row>
        ))}
        <Field label="Match rows by" hint="The same value in a later import updates that client instead of adding one.">
          {(id, describedBy) => (
            <Select id={id} describedBy={describedBy} value={sheet.key} onChange={(v) => setSheet({ ...sheet, key: v })} options={headerOptions} />
          )}
        </Field>
        <Field label="Whose rows" hint="A column of handles files each row under that person.">
          {(id, describedBy) => (
            <Select
              id={id}
              describedBy={describedBy}
              value={sheet.owner}
              onChange={(v) => setSheet({ ...sheet, owner: v })}
              options={[{ value: "", label: "Mine" }, ...headerOptions]}
            />
          )}
        </Field>
      </Stack>
      <Row gap={2}>
        <Button onClick={runImport} disabled={plan.records.length === 0}>
          Import {count(plan.records.length)} rows
        </Button>
        <Button variant="quiet" onClick={() => setSheet(undefined)}>
          Pick another file
        </Button>
      </Row>
    </Stack>
  );
}

export default function App() {
  const { database, useLiveQuery } = useFireproof("clients");
  const { me, can, ready } = useVibe("clients");
  const { viewer, isViewerPending, requestLogin } = useViewer();
  const { docs: clients } = useLiveQuery("type", { key: "client" });
  const [result, setResult] = useState(undefined);
  const canImport = can.create({ type: "client", _id: `client:${me?.userHandle}:sample`, ownerHandle: me?.userHandle, authorHandle: me?.userHandle });

  return (
    <Stack gap={5}>
      <Heading level={1}>Clients</Heading>
      <Card>
        {!ready || isViewerPending || canImport.pending ? (
          <div aria-busy="true">
            <Skeleton variant="card" />
          </div>
        ) : !viewer ? (
          <Button onClick={requestLogin}>Sign in to bring in your client list</Button>
        ) : canImport.ok ? (
          <SheetImport database={database} stored={clients} me={me?.userHandle} onDone={setResult} />
        ) : (
          <Text muted>Importing is open to this app's team.</Text>
        )}
        {result && (
          <Stack gap={1}>
            <Text>
              {count(result.added)} added, {count(result.updated)} updated, {count(result.same)} already up to date,{" "}
              {count(result.skipped.length)} skipped
            </Text>
            {result.skipped.map((s) => (
              <Text key={s.line} size="sm" muted>
                Line {s.line}: {s.why}
              </Text>
            ))}
          </Stack>
        )}
      </Card>
      {clients.length === 0 ? (
        <Empty icon="user" title="Your clients land here">
          Bring in a spreadsheet and every row becomes a client.
        </Empty>
      ) : (
        <Stack gap={2}>
          {clients.map((c) => (
            <RowCard key={c._id}>
              <Row gap={2}>
                <Text>{c.name || c.email}</Text>
                {c.company && <Badge tone="info">{c.company}</Badge>}
              </Row>
            </RowCard>
          ))}
        </Stack>
      )}
    </Stack>
  );
}
```

### `access.js`
```js
export function clients(doc, oldDoc, user, ctx) {
  if (oldDoc && oldDoc.type !== doc.type) throw { forbidden: "a record keeps its type" };

  if (doc.type === "client") {
    if (!user || doc.authorHandle !== user.userHandle) throw { forbidden: "rows carry their signed-in writer" };
    if (!String(doc._id).startsWith("client:" + doc.ownerHandle + ":")) throw { forbidden: "a row's id starts with its owner" };
    // Anyone signed in imports rows of their own; filing a row under another handle is the owner's.
    if (doc.ownerHandle !== user.userHandle) ctx.requireRole("owner");
    // A stored row changes for the person it belongs to, the person who wrote it, or the owner.
    if (oldDoc && oldDoc.ownerHandle !== user.userHandle && oldDoc.authorHandle !== user.userHandle) ctx.requireRole("owner");
    const ch = "clients:" + doc.ownerHandle;
    return { channels: [ch], grant: { users: { [doc.ownerHandle]: [ch], [user.userHandle]: [ch] } } };
  }

  throw { forbidden: "unknown document type" };
}

// Summary: each client row belongs to the person its ownerHandle names and is read by that person and whoever wrote it; anyone signed in imports rows of their own, and only the app's owner files rows under someone else. Rows carry their writer in authorHandle.
```

The list reads every row the person can see, so a member who signs in finds the clients filed under their handle and none of anyone else's, and the owner who imported them sees all of them.
