# CSV Column Mapper

> Match the columns of a CSV file to your fields, with detected value types, sample values, and warnings before anything is imported.

Source: https://www.honestui.com/docs/product/csv-column-mapper

```tsx
"use client"

import * as React from "react"

import {
  CsvColumnMapper,
  type CsvMapperField,
  type CsvMappingResult,
} from "@/registry/default/product/csv-column-mapper/csv-column-mapper"

const fields: CsvMapperField[] = [
  { key: "name", label: "Name", aliases: ["Full name"], required: true },
  { key: "email", label: "Email", type: "email", required: true },
  { key: "company", label: "Company", aliases: ["Organization", "Account"] },
  { key: "dealValue", label: "Deal value", type: "currency" },
  { key: "seats", label: "Seats", type: "integer" },
  { key: "renewsOn", label: "Renewal date", type: "date", aliases: ["Renews on"] },
  { key: "newsletter", label: "Newsletter", type: "boolean", aliases: ["Opted in"] },
]

// A CRM export with its own column names. "Deal size" matches nothing on its own,
// and two Seats cells are words, so that column reads as text.
const headers = ["Full Name", "E-mail address", "Organisation", "Deal size", "Seats", "Renews on", "Opted in", "Internal notes"]
const rows = [
  ["Ana Ruiz", "ana@northwind.example", "Northwind", "$12,400", "12", "03/04/2026", "yes", "Met at the summit"],
  ["Li Wei", "li.wei@contoso.example", "Contoso", "$3,250", "5", "04/18/2026", "no", ""],
  ["Sam Cole", "sam@fabrikam.example", "Fabrikam", "$48,000", "ten", "05/01/2026", "yes", "Needs SSO"],
  ["Dee Park", "dee@tailspin.example", "Tailspin Toys", "$900", "2", "06/30/2026", "no", ""],
  ["Omar Haddad", "omar@adatum.example", "Adatum", "$7,800", "8", "07/12/2026", "yes", "Renewal risk"],
  ["Mia Chen", "mia@litware.example", "Litware", "$15,100", "a dozen", "08/01/2026", "", ""],
]

/** Nothing leaves the page: the readout shows the first row `onConfirm` received. */
export function CsvColumnMapperDemo() {
  const [result, setResult] = React.useState<CsvMappingResult | null>(null)
  const first = result?.rows[0]

  return (
    <div className="flex w-full min-w-0 flex-col gap-[var(--hui-space-4)]">
      <CsvColumnMapper
        aria-label="Map columns from customers.csv"
        headers={headers}
        rows={rows}
        fields={fields}
        onConfirm={setResult}
      />
      <p
        role="status"
        className="m-0 px-[var(--hui-space-1)] text-[var(--hui-color-foreground-base-secondary)] empty:hidden [font-size:var(--hui-font-size-small)] [line-height:var(--hui-line-height-small)]"
      >
        {first &&
          `Mapped ${result.rows.length} rows. First row: ${Object.entries(first)
            .map(([key, value]) => `${key} “${value}”`)
            .join(", ")}.`}
      </p>
    </div>
  )
}

```

## Overview [#overview]

CsvColumnMapper is the step between reading a file and importing it. A CSV from another system rarely uses your field names, so each source column is listed with the type its values look like and a few sample values, next to a select for the field it imports as. Columns whose names match a field are mapped when the mapper opens, and people correct the rest.

The mapper only decides where each column goes. It does not read files, parse values, or save rows. Read the file yourself, pass its header row and data rows, and handle the result in `onConfirm`, which receives the mapping, one object per row keyed by field, and a table ready for [Paste Table](/docs/product/paste-table).

Use it on its own when the rows go straight to a server that validates them. Pair it with Paste Table when people should see and fix invalid cells before they import: the mapper settles the columns, then Paste Table checks every cell. The second example on this page wires the two together.

## Anatomy [#anatomy]

<Anatomy title="CsvColumnMapper">
  <AnatomyItem name="Header" description="Title, and a status line with mapped columns and row count" />

  <AnatomyItem name="Problems" description="Required fields that no column is mapped to" />

  <AnatomyItem name="Column table" description="One row per source column">
    <AnatomyItem name="Column" description="Source name, detected type, and blank cells" />

    <AnatomyItem name="Samples" description="The first non-empty values from the column" />

    <AnatomyItem name="Field select" description="Chooses the field the column imports as, or Don't import" />

    <AnatomyItem name="Hint" description="How the column was matched, that it is skipped, or a type warning" />
  </AnatomyItem>

  <AnatomyItem name="Actions" description="Cancel and Continue, shown when their callbacks are passed" />
</Anatomy>

Installing `csv-column-mapper` brings `Button`, `Select`, and `Table` along as registry dependencies.

## Behavior [#behavior]

### Matching on open [#matching-on-open]

Each header is compared with every field's `label`, `key`, and `aliases`, ignoring case, spaces, and punctuation. An exact match or a listed alias always maps. Otherwise the closest names map when their similarity reaches `matchThreshold`, which defaults to 0.72: "E-mail address" finds Email, and "Organisation" finds a field with the alias "Organization". A similar name is passed over when the column's values plainly disagree with the field's type, so a text column called "Start" does not land in a date field.

Each field takes one column. The hint under a mapped field says how it was matched, so people know which choices the mapper made for them.

### Detected types [#detected-types]

Up to 500 rows are scanned per column. Each non-empty cell is read as a whole number, number, currency, percent, date, yes/no, email, link, or text. The column takes the type at least 80% of its cells share, and a column whose cells disagree is text. Numbers widen sensibly: whole numbers and decimals together are a number, and amounts with a currency sign absorb plain numbers.

When a field declares a `type` and the column does not fit it, the hint warns with both types, such as "Values look like text; Seats expects whole number." The warning does not block anything. Text fields, and fields without a type, accept every column.

### Changing the mapping [#changing-the-mapping]

Choosing a field that another column already uses moves it, and the select lists which column holds each field and which fields are required. "Don't import" skips a column; skipped columns stay listed in a muted color.

### Confirming [#confirming]

Continue names the number of rows it will pass on. While a required field has no column, pressing it sends nothing, lists the missing fields, and moves focus to that list. When `onConfirm` returns a promise, the controls are disabled until it settles.

## Accessibility [#accessibility]

The columns are a native table with column headings. Each field select is named for its source column, such as "Field for E-mail address", and its hint is the select's description, so type warnings and match reasons are announced with it.

The summary is a polite status region and is announced as columns are mapped. The missing-fields list is an alert, and it receives focus when Continue is pressed too early. Warnings use an icon and words, not color alone.

Give the root an `aria-label` that names the file, or keep the visible title, which labels it by default.

| Key                                                 | Action                                      |
| --------------------------------------------------- | ------------------------------------------- |
| <kbd>Tab</kbd>                                      | Move between field selects and actions      |
| <kbd>Enter</kbd>, <kbd>Space</kbd>, or <kbd>↓</kbd> | Open the focused field select               |
| <kbd>↑</kbd> <kbd>↓</kbd>                           | Move between fields in an open select       |
| <kbd>Escape</kbd>                                   | Close the select without changing the field |

## Installation [#installation]


  

  
    <CliBlock commands="[&#x22;csv-column-mapper&#x22;]" />
  

  
    
      
        No extra packages are needed beyond the base setup.
      

      
        Copy and paste these files into your project.
      

      <ComponentSource name="csv-column-mapper" title="components/ui/csv-column-mapper/csv-column-mapper-types.ts" file="csv-column-mapper-types.ts" />

      <ComponentSource name="csv-column-mapper" title="components/ui/csv-column-mapper/csv-column-mapper-utils.ts" file="csv-column-mapper-utils.ts" />

      <ComponentSource name="csv-column-mapper" title="components/ui/csv-column-mapper/csv-column-mapper.tsx" file="csv-column-mapper.tsx" />

      
        Update the import paths to match your project setup.
      
    
  


## Usage [#usage]

Describe the fields once, split the file into a header row and data rows, then handle the result:

```tsx
import {
  CsvColumnMapper,
  type CsvMapperField,
} from "@/components/ui/csv-column-mapper/csv-column-mapper"
import { parseClipboardTable } from "@/components/ui/paste-table/paste-table"

const fields: CsvMapperField[] = [
  { key: "name", label: "Name", aliases: ["Full name"], required: true },
  { key: "email", label: "Email", type: "email", required: true },
  { key: "seats", label: "Seats", type: "integer" },
]

const [headers, ...rows] = parseClipboardTable(await file.text(), ",")

<CsvColumnMapper
  headers={headers}
  rows={rows}
  fields={fields}
  onCancel={closeImport}
  onConfirm={({ rows }) => api.importContacts(rows)}
/>
```

Rows in the result hold the source text, trimmed but not parsed. Parse and validate them on the server, or hand `result.table` to Paste Table to do it in the browser first.

### Followed by Paste Table [#followed-by-paste-table]

The mapper's fields are a subset of Paste Table's columns, so one array describes both steps. `result.table` puts each field's label in the first row, and Paste Table's `defaultRows` opens its review step with it, mapping every column without guessing:

```tsx
<PasteTable columns={columns} defaultRows={result.table} onImport={save} />
```

### Controlled mapping [#controlled-mapping]

Pass `mapping` and `onMappingChange` to store choices, for example to remember a mapping per source system. `suggestMapping(headers, fields)` returns what the mapper would choose on its own.

## Examples [#examples]

### A complete import [#a-complete-import]

Choose a CSV file or use the sample, map its columns, then review cells in Paste Table and import. "Contact" matches no field, so Name has to be chosen by hand.

```tsx
"use client"

import * as React from "react"
import { ArrowLeft as ArrowLeftIcon, FileSpreadsheet as FileSpreadsheetIcon } from "honestui/icons"

import { cn } from "@/lib/utils"
import {
  CsvColumnMapper,
  type CsvMappingResult,
} from "@/registry/default/product/csv-column-mapper/csv-column-mapper"
import {
  PasteTable,
  parseClipboardTable,
  type PasteTableColumn,
} from "@/registry/default/product/paste-table/paste-table"
import { Button } from "@/components/honest-ui/ui/button"

// One schema for both steps: CSV Column Mapper reads key, label, type, aliases, and
// required; Paste Table also reads the parsing and validation settings.
const columns: PasteTableColumn[] = [
  { key: "name", label: "Name", required: true },
  {
    key: "email",
    label: "Email",
    required: true,
    validate: (value) =>
      /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value)) ? undefined : "Enter an email address, such as name@example.com",
  },
  { key: "company", label: "Company" },
  { key: "seats", label: "Seats", type: "number", aliases: ["Licenses"] },
  { key: "startDate", label: "Start date", type: "date", dateOrder: "mdy" },
]

const SAMPLE_FILE = `Contact,Work email,Company name,Licenses,Start
Ana Ruiz,ana@northwind.example,"Northwind, Inc.",12,3/4/2026
Li Wei,li.wei@northwind,Contoso,"1,250",03/18/2026
Sam Cole,sam@fabrikam.example,Fabrikam,five,2026-04-01
Dee Park,dee@tailspin.example,Tailspin Toys,3,4/31/2026`

type Step =
  | { name: "choose"; imported?: number }
  | { name: "map"; fileName: string; headers: string[]; rows: string[][] }
  | { name: "review"; fileName: string; headers: string[]; rows: string[][]; result: CsvMappingResult }

const STEPS = ["Choose file", "Map columns", "Review and import"] as const

/**
 * A complete import: read a CSV, map its columns with type hints, then fix
 * cells in Paste Table before importing. Nothing leaves the page.
 */
export function CsvColumnMapperImportFlow() {
  const [step, setStep] = React.useState<Step>({ name: "choose" })
  const [readError, setReadError] = React.useState<string | null>(null)
  const fileInputRef = React.useRef<HTMLInputElement>(null)
  const current = step.name === "choose" ? 0 : step.name === "map" ? 1 : 2

  function open(fileName: string, text: string) {
    const table = parseClipboardTable(text, ",")
    if (table.length < 2) {
      setReadError(`${fileName} has no rows under its header.`)
      return
    }
    setReadError(null)
    setStep({ name: "map", fileName, headers: table[0], rows: table.slice(1) })
  }

  return (
    <div className="flex w-full min-w-0 flex-col gap-[var(--hui-space-5)]">
      <ol className="m-0 flex list-none flex-wrap items-center gap-x-[var(--hui-space-4)] gap-y-[var(--hui-space-1)] p-0 [font-size:var(--hui-font-size-small)] [line-height:var(--hui-line-height-small)]">
        {STEPS.map((label, index) => (
          <li
            key={label}
            aria-current={index === current ? "step" : undefined}
            className={cn(
              "flex items-center gap-[var(--hui-space-2)]",
              index === current
                ? "text-[var(--hui-color-foreground-base-primary)] [font-weight:var(--hui-font-weight-medium)]"
                : "text-[var(--hui-color-foreground-base-secondary)]"
            )}
          >
            <span
              aria-hidden="true"
              className={cn(
                "flex size-5 items-center justify-center rounded-full tabular-nums [font-size:var(--hui-font-size-mini)]",
                index === current
                  ? "bg-[var(--hui-color-background-neutral-emphasis,var(--hui-color-foreground-base-primary))] text-[var(--hui-color-background-base-primary)]"
                  : "border-[0.5px] border-[var(--hui-color-border-base-secondary)]"
              )}
            >
              {index + 1}
            </span>
            {label}
          </li>
        ))}
      </ol>

      {step.name === "choose" && (
        <div className="flex flex-col items-center gap-[var(--hui-space-4)] rounded-[var(--hui-radius-2)] border-[0.5px] border-dashed border-[var(--hui-color-border-base-secondary)] px-[var(--hui-space-6)] py-[var(--hui-space-8)] text-center">
          <FileSpreadsheetIcon aria-hidden="true" className="size-6 text-[var(--hui-color-foreground-base-secondary)]" />
          <div className="flex flex-col gap-[var(--hui-space-1)]">
            <p className="m-0 text-[var(--hui-color-foreground-base-primary)] [font-size:var(--hui-font-size-regular)] [font-weight:var(--hui-font-weight-medium)]">
              Import contacts from a CSV file
            </p>
            <p className="m-0 text-[var(--hui-color-foreground-base-secondary)] [font-size:var(--hui-font-size-small)]">
              Any column names work. You will match them to fields next.
            </p>
          </div>
          <div className="flex flex-wrap justify-center gap-[var(--hui-space-2)]">
            <Button size="sm" variant="outline" onClick={() => fileInputRef.current?.click()}>
              Choose CSV file
            </Button>
            <input
              ref={fileInputRef}
              type="file"
              tabIndex={-1}
              aria-hidden="true"
              accept=".csv,text/csv"
              className="sr-only"
              onChange={async (event) => {
                const file = event.currentTarget.files?.[0]
                event.currentTarget.value = ""
                if (file) open(file.name, await file.text())
              }}
            />
            <Button size="sm" onClick={() => open("contacts.csv", SAMPLE_FILE)}>
              Use sample file
            </Button>
          </div>
          <p role="status" className="m-0 text-[var(--hui-color-foreground-base-primary)] empty:hidden [font-size:var(--hui-font-size-small)]">
            {readError ??
              (step.imported !== undefined && `Imported ${step.imported} ${step.imported === 1 ? "contact" : "contacts"}.`)}
          </p>
        </div>
      )}

      {step.name === "map" && (
        <CsvColumnMapper
          aria-label={`Map columns from ${step.fileName}`}
          labels={{ title: step.fileName }}
          headers={step.headers}
          rows={step.rows}
          fields={columns}
          onCancel={() => setStep({ name: "choose" })}
          onConfirm={(result) => setStep({ ...step, name: "review", result })}
        />
      )}

      {step.name === "review" && (
        <div className="flex min-w-0 flex-col gap-[var(--hui-space-3)]">
          <Button
            variant="ghost"
            size="sm"
            className="-ms-[var(--hui-space-3)] self-start"
            onClick={() => setStep({ name: "map", fileName: step.fileName, headers: step.headers, rows: step.rows })}
          >
            <ArrowLeftIcon aria-hidden="true" className="rtl:rotate-180" />
            Back to mapping
          </Button>
          <PasteTable
            aria-label={`Review contacts from ${step.fileName}`}
            columns={columns}
            defaultRows={step.result.table}
            onImport={(rows) => setStep({ name: "choose", imported: rows.length })}
          />
        </div>
      )}
    </div>
  )
}

```

## API reference [#api-reference]

### CsvColumnMapper [#csvcolumnmapper]

Accepts native section props beyond those listed.

| Prop              | Type                                | Default   | Description                                             |
| ----------------- | ----------------------------------- | --------- | ------------------------------------------------------- |
| `headers`         | `string[]`                          | Required  | Column names from the file's first row.                 |
| `rows`            | `string[][]`                        | Required  | Data rows, without the header row.                      |
| `fields`          | `CsvMapperField[]`                  | Required  | The fields a column can map to.                         |
| `mapping`         | `CsvColumnMapping`                  | —         | Controlled mapping, one field key or `null` per column. |
| `defaultMapping`  | `CsvColumnMapping`                  | Suggested | Initial mapping when uncontrolled.                      |
| `onMappingChange` | `(mapping) => void`                 | —         | Called with the whole mapping after each change.        |
| `onConfirm`       | `(result) => void \| Promise<void>` | —         | Shows Continue. Receives the mapping and mapped rows.   |
| `onCancel`        | `() => void`                        | —         | Shows Cancel.                                           |
| `sampleCount`     | number                              | `3`       | Non-empty values shown per column.                      |
| `matchThreshold`  | number                              | `0.72`    | Similarity from 0 to 1 a name needs to map on open.     |
| `disabled`        | boolean                             | `false`   | Keeps every control visible but inactive.               |
| `labels`          | `Partial<CsvColumnMapperLabels>`    | English   | Replacement text, type names, and count wording.        |

### Fields [#fields]

| Property   | Type           | Description                                                                 |
| ---------- | -------------- | --------------------------------------------------------------------------- |
| `key`      | string         | Property name of the field in each mapped row.                              |
| `label`    | string         | Name shown in the select and matched against headers.                       |
| `type`     | `CsvValueType` | The kind of value expected. Defaults to `"text"`, which accepts any column. |
| `aliases`  | `string[]`     | Other header names that map to this field.                                  |
| `required` | boolean        | A column must be mapped before Continue works.                              |

### Functions [#functions]

| Export                     | Signature                                                 | Description                                         |
| -------------------------- | --------------------------------------------------------- | --------------------------------------------------- |
| `profileColumns`           | `(headers, rows, options?) => CsvColumnProfile[]`         | Detected type, blanks, and samples per column.      |
| `detectColumnType`         | `(values, threshold?) => { type; confidence }`            | The type most cells share.                          |
| `detectValueType`          | `(raw) => CsvValueType \| null`                           | The type one cell looks like.                       |
| `suggestMapping`           | `(headers, fields, options?) => { mapping; suggestions }` | The matching the mapper runs on open.               |
| `headerSimilarity`         | `(a, b) => number`                                        | How alike two names are, from 0 to 1.               |
| `isTypeCompatible`         | `(fieldType, detected) => boolean`                        | Whether a field accepts a column without a warning. |
| `getMissingRequiredFields` | `(mapping, fields) => CsvMapperField[]`                   | Required fields with no column.                     |
| `applyMapping`             | `(rows, mapping) => Record<string, string>[]`             | Rows keyed by field.                                |
| `toMappedTable`            | `(rows, mapping, fields) => string[][]`                   | Mapped columns with field labels in the first row.  |

### Types [#types]

| Export                  | Shape                                                                                                   |
| ----------------------- | ------------------------------------------------------------------------------------------------------- |
| `CsvValueType`          | `"text" \| "number" \| "integer" \| "currency" \| "percent" \| "date" \| "boolean" \| "email" \| "url"` |
| `CsvColumnMapping`      | `(string \| null)[]`, one field key per source column                                                   |
| `CsvMappingResult`      | `{ mapping; rows; table }`                                                                              |
| `CsvColumnProfile`      | `{ index; header; type; confidence; samples; emptyCount }`                                              |
| `CsvColumnMapperLabels` | Every string, type name, and count function the component writes                                        |
