Skip to content
WingoUI
ComponentsTemplatesDocsPricingAI agentsBlogChangelogContact
Components
Buttons & Actions
ButtonButton GroupCopy ButtonDelete ButtonTheme ToggleToggleToggle Group
Inputs
Avatar UploadCalendarCheckboxColor PickerComboboxCountry SelectCron PickerCurrency InputDate PickerDate Range PickerDate Time PickerDuration PickerEmail InputEmoji PickerFile UploadFilter BuilderInputInput GroupListboxMasked InputMention InputMonth PickerMulti SelectNumber InputOTP InputPassword InputPhone InputRadio GroupRatingSearch InputSegmented ControlSelectSignature PadSliderSwitchTag InputTextareaTime PickerTimezone SelectTree Select
Forms
Address InputBooking WidgetCSV ImportFieldForm WizardInline EditInvoice line itemsRich Text EditorSchema Builder
Navigation
Back To TopBounce SidebarBreadcrumbCommand MenuGlobal SearchGooey NavHook SidebarNav MenuNav TabsPaginationProximity SidebarScroll ProgressSidebarStepsTable Of ContentsTabsTopbarUser MenuWorkspace Switcher
Overlays
Alert DialogContext MenuDialogDrawerDropdown MenuFamily DrawerHover CardPopoverShare DialogSheetShortcuts DialogTooltipTour
Feedback
AlertBannerCookie ConsentEmoji ReactionEmpty StateNotification BellNotification CenterProgressRoute ProgressSetup ChecklistSkeletonSpinnerToast
Data Display
Approval FlowAvatarBadgeCalendar ViewCode BlockComment ThreadContact cardCountdownDescription ListDiff ViewerFile ListFile managerFolderGanttJSON ViewerKbdLog ViewerMarkdownPresenceSchedulerTagTimelineTree View
Tables & Lists
Audit LogData TableDeal PipelineEditable GridKanbanListMembers tablePermissions MatrixTableTask ListVirtual List
Charts & Stats
Animated CounterArea chartBar chartDonut chartFunnel chartGaugeGitHub ActivityHeatmap calendarLeaderboardLine chartRadar chartRadial barSparklineStat CardTrackerTrend badge
Layout
AccordionApp ShellCardCollapsibleDetail LayoutEntity HeaderPage HeaderScroll AreaSeparatorSettings LayoutSplit ViewToolbar
Media
Audio PlayerCarouselCSV ViewerDOCX EditorDOCX ViewerExcel ViewerFile SystemImage compareImage CropperImage GalleryImage LightboxLocation MapPDF ViewerPowerPoint ViewerQR CodeStep PlayerVideo Player
AI Kit
Agent Status CardChat MessageChat ThreadChat WidgetConversation ListFluid OrbGrid RevealMatrix OrbModel PickerPrompt InputReasoning IndicatorRule BuilderSuggestion ChipsTool Call TimelineUsage MeterVoice InputWorkflow Canvas
Text & Effects
Background PatternGravity LettersMarqueeTerminalText AnimateText Rotate
Mobile
Action SheetBottom Tab BarFABHaptic ButtonHero HeaderInstall PromptLarge Title HeaderNotification BannerOnboarding CarouselPicker WheelPull To RefreshSlide To ConfirmSticky CTA BarSwipe DeckSwipeable Tabs
Commerce
Cart drawerCategory pickerCheckout stepsCoupon inputFavorite buttonFilter panelListing cardListing gridOrder trackerPricePrice rangePricing tableProduct galleryQuantity stepperReviewsSeller card
Marketing Sections
App Download SectionBlog Cards SectionCTA SectionFAQ SectionFeature GridFeature ShowcaseHero SectionIntegrations SectionLogo CloudMarketing FooterMarketing HeaderMarketing SectionNewsletter SectionPricing SectionStats SectionSteps SectionTeam SectionTestimonials SectionTimeline SectionVideo Section
Blocks
Admin Dashboard PageAdmin ShellAI Chat PageAPI Keys PageAutomation Builder PageCheckout PageCRM Contact PageCRM Pipeline PageError PagesInbox PageInvoice PageKPI DashboardListing Detail PageLogin PageMarketplace Home PageMarketplace Search PageMarketplace ShellMobile App HomeOnboarding FlowOrder History PagePost Listing WizardPricing PageProfile PageRegister PageSettings PageUsers Admin Page
Templates
About PageAcademy PageAccessibility PageAffiliate PageAgency PageAI Product PageAppointment Booking PageBlog PageBlog Post PageBug Bounty PageCareers PageChangelog PageCommunity PageCompare PageContact PageCustomer Story PageCustomers PageDemo Booking PageDevelopers PageDocs Home PageDownload PageEnterprise PageEvents PageExperts PageFAQ PageFeature PageGlossary PageHelp Article PageHelp Center PageHome Services PageImpact PageIntegration Detail PageIntegrations PageJob Detail PageLanding PageLaunch PageLegal PageManifesto PagePortfolio PagePress PageProduct Tour PagePromo PageReal Estate PageReferral PageResearch Report PageRestaurant PageRoadmap PageROI Calculator PageSecurity PageSolutions PageStartups PageStatus PageStorefront PageSwitch PageTemplate Gallery PageTravel PageWaitlist PageYear in Review Page
Hooks & Utilities
AI ChatChart kitCommerceDate utilsFile exportFile typesFiltersForm validationHapticsInvoicingMotion presetsNavigationNumber formatRelative timeRomanian locationsSpreadsheetText matchTonesUIProvideruseClipboarduseConsentuseControllableStateuseCooldownuseDebounceuseKeyboardInsetuseLocaleuseLongPressuseMediaControlsuseMediaQueryuseOverflowItemsusePersistedStateuseScrollEdgesuseScrollStateuseSelectionuseShortcutuseStickToBottom
GalleryTheme

Hooks & Utilities

Spreadsheet

Hooks & Utilities

Spreadsheet TypeScript helper for React

Romanian locationsText match
Live props
Options
delimiter
escapeFormulas
threshold0.5
  1. Home
  2. Components
  3. Hooks & Utilities
  4. Spreadsheet
Pro

Spreadsheet TypeScript helper for React

v1.0.0·Added in 1.0.0

Read CSV and Excel files in the browser, match their columns to your fields, and write CSV that Excel opens with diacritics intact.

Choose a CSV or an .xlsx file (or keep the sample, a ';' export from a European Excel): the demo shows the detected delimiter and encoding, the header row, how each column matched a Northwind CRM field (Company name → Company, VAT ID → Tax ID) with its score, and the first rows. Download CSV writes the parsed rows back with the delimiter from the playground, a byte order mark and formula cells neutralised.

Spreadsheet is a Pro React helper in the React hooks and utilities category, written in TypeScript for React 19. It installs as source with npx wingo-ui@latest add spreadsheet, together with Text match and the npm package read-excel-file.

Add to a project

Requirements: React 19, in Next.js (App Router or Pages), Vite or React Router. Installation guide · Next.js setup · Vite setup

npx wingo-ui@latest add spreadsheet

Spreadsheet is part of Pro, with 298 more Pro items: $8 a month or $150 once. 14-day refund before you download any Pro item. See plans

Usage

Import readSpreadsheet from @/lib/spreadsheet.

import { matchColumns, readSpreadsheet, SpreadsheetError, toCsv } from "@/lib/spreadsheet"

async function onFile(file: File) {
  try {
    const { sheets } = await readSpreadsheet(file)
    const [sheet] = sheets
    const mapping = matchColumns(sheet.headers, [
      { id: "name", label: "Company", aliases: ["Company name", "Customer"] },
      { id: "taxId", label: "Tax ID", aliases: ["VAT ID", "VAT number"] },
    ])
    return { sheet, mapping }
  } catch (error) {
    if (error instanceof SpreadsheetError && error.code === "unsupported") return null
    throw error
  }
}

toCsv([["Customer", "Balance"], ["Northwind Tech LLC", 12480]], { delimiter: ";" })

API

  • delimiterdefault ","
    string

    toCsv options.delimiter for the download: "," or ";" (what a Romanian Excel expects, because "," is its decimal mark).

  • escapeFormulasdefault true
    boolean

    toCsv options.escapeFormulas: cells starting with = + - @ get a leading ' so a spreadsheet never runs them (CSV injection).

  • thresholddefault 0.5
    number

    matchColumns options.threshold: the lowest score that still maps a column to a field.

  • readSpreadsheet
    (file: Blob & { name?: string }, options?: { maxRows?; maxBytes?; header?: "auto" | number | false; delimiter?; columnLabel? }) => Promise<SpreadsheetWorkbook>

    A picked file as { kind: "csv" | "xlsx", sheets: { name, headers, rows, truncated }[], delimiter?, encoding? }. CSV / TSV / TXT are decoded as UTF-8, else Windows-1250 (a Romanian Excel), with the delimiter detected; .xlsx loads read-excel-file on demand. Blank and duplicate headers get names, short rows are padded, empty rows dropped. Throws SpreadsheetError with code "unsupported" (.xls, .numbers), "too-large" (default 20 MB), "empty" or "parse".

Parts

  • parseCsv

    function

    RFC 4180 parsing (quotes, doubled quotes, line breaks inside quotes, CRLF, a BOM), the delimiter among , ; tab | that splits the first lines most evenly, and the text of a file's bytes. Signature: (text, { delimiter?, maxRows? }) => { rows: string[][]; delimiter }.

  • detectDelimiter

    function

    RFC 4180 parsing (quotes, doubled quotes, line breaks inside quotes, CRLF, a BOM), the delimiter among , ; tab | that splits the first lines most evenly, and the text of a file's bytes. Signature: (text) => string.

  • decodeText

    function

    RFC 4180 parsing (quotes, doubled quotes, line breaks inside quotes, CRLF, a BOM), the delimiter among , ; tab | that splits the first lines most evenly, and the text of a file's bytes. Signature: (buffer: ArrayBuffer) => { text; encoding }.

  • toSheet

    function

    Raw rows to a sheet with a header row, and a cell as text for previews and validators (dates as "2026-09-24"). Signature: (name, rows, options?) => SpreadsheetSheet.

  • cellToString

    function

    Raw rows to a sheet with a header row, and a cell as text for previews and validators (dates as "2026-09-24"). Signature: (cell: SpreadsheetCell) => string.

  • matchColumns

    function

    Pairs each field with at most one column by name, ignoring case, diacritics and punctuation ("Company name" = "company_name", "Société" = "societe"), aliases included ("VAT ID", "Tax ID"), best scores first, each column used once. The auto-match of an import wizard. Signature: (headers: string[], targets: { id; label; aliases? }[], { threshold? }) => { targetId; column: number | null; score }[].

  • toCsv

    function

    CSV text with quoting where needed, a UTF-8 BOM by default so Excel keeps accented letters (é, ü, ñ), and a browser download (nothing happens on the server). Signature: (rows, { delimiter?, bom?, lineEnding?, escapeFormulas? }) => string.

  • downloadCsv

    function

    CSV text with quoting where needed, a UTF-8 BOM by default so Excel keeps accented letters (é, ü, ñ), and a browser download (nothing happens on the server). Signature: (filename, rowsOrText, options?) => void.

  • SpreadsheetError

    type

    What readSpreadsheet throws, so a UI can print its own message per code. Type: class extends Error { code: "unsupported" | "empty" | "too-large" | "parse" }.

Examples

Export to CSV

Quotes, accented names and a formula-looking note come out safe for Excel; the button saves orders.csv with a UTF-8 BOM.

Dependencies

read-excel-filetext-match

Files

  • lib/spreadsheet.ts

FAQ

Is the Spreadsheet helper free?

The preview, props and docs are free; copying the source needs a Pro plan. See plans.

How do I install Spreadsheet?

Run npx wingo-ui@latest add spreadsheet. It also adds the Wingo UI item it builds on (Text match) and the npm package read-excel-file. With shadcn, add the @wingo-ui registry with your API key, then run npx shadcn@latest add @wingo-ui/spreadsheet.

See also

File UploadText matchlibFile typeslib

Used in

Excel ViewerCSV ImportAudit Log

More React hooks and utilities

ToneslibUIProviderlibuseClipboardhookuseConsenthookuseControllableStatehookuseCooldownhook
All 36 React hooks and utilities

Articles using this component

  • React CSV Importer: Upload, Map Columns, Fix Rows, Import

    Component guides · Oct 16, 2026 · 7 min read

  • React Excel Viewer: Show .xlsx Files With Their Real Styles

    Component guides · Oct 16, 2026 · 10 min read

PreviousRomanian locationsNext Text match
customers-exportCSV · ; · utf-8 (sample) · 5 rows
  • Company nameCompany1.00
  • VAT IDTax ID1.00
  • TownCity1.00
  • Primary contact emailEmail0.65
  • Tel.Phone0.73
  • Current balanceBalance1.00
  • Bank account no. (IBAN)IBAN0.73
Company nameVAT IDTownPrimary contact emailTel.Current balanceBank account no. (IBAN)
Northwind Tech GmbHDE123456789Berlinoffice@northwind.example030 1234 567812.480,00DE89370400440532013000
Summit Logistics SAFR40303265045Lyoncontact@summit.example04 72 41 02 2048.920,50
Greenleaf Pharmacy BVNL001234567B01Utrecht030 412 00007.315,20
Pixel StudioES B12345678Madridhello@pixelstudio.example3.450,00
=HYPERLINK("x")
Company name,VAT ID,Town,Primary contact email,Tel.,Current balance,Bank account no. (IBAN)
Northwind Tech GmbH,DE123456789,Berlin,office@northwind.example,030 1234 5678,"12.480,00",DE89370400440532013000
Summit Logistics SA,FR40303265045,Lyon,contact@summit.example,04 72 41 02 20,"48.920,50",
"'=HYPERLINK(""x"")",,,,,,