ProGridSign in

Features

Export

Download the grid as CSV, an Excel workbook or an OpenDocument spreadsheet — every row the filters kept, or just the selection — from the toolbar, the context menu, or the handle. Choose which formats your readers are offered, and add destinations of your own.

What is written

An export takes the visible leaf columns in their current order and every row the filters kept, sorted as the grid shows them. While rows are grouped, each group's summary line comes first and its rows follow beneath it, the way Copy with group headers lays them out. Under pivot mode the pivot is exported as arranged, collapsed groups included.

<ProGrid
  columns={columns}
  data={orders}
  // Defaults to "menu" (inside the gear); true gives it a button, false removes it.
  toolbar={{ export: true }}
/>

The formats

FormatWhat it carriesOpened by
"csv" · "tsv"The text on screen — a formatted currency stays formatted — with a UTF-8 byte-order mark so accents survive. raw: true writes the numbers underneath instead.Everything, including Google Sheets and Numbers.
"xlsx"Office Open XML. Numbers as numbers, booleans as booleans, a bold frozen header row, and column widths taken from the grid.Excel, LibreOffice, OpenOffice, Google Sheets, Numbers.
"ods"OpenDocument — the ISO-standard spreadsheet. The same typed values and widths, with the header marked as the table's heading so it repeats when printed.LibreOffice, OpenOffice, EuroOffice and the suites built on them; also Excel, Google Sheets and Numbers.

Both workbook writers are the grid's own — no spreadsheet library is added to your bundle, and neither format needs a server.

Live demo

Toolbar and context-menu export

Export from the toolbar for the whole view, or right-click a cell range and export just those cells.

import { useRef, useState } from "react"
import { ProGrid, type CustomExportFormat, type ProColumnDef, type ProGridHandle } from "@/components/pro-grid"
import { formatCurrency, operationOrders, type OperationOrder } from "@/lib/operations-data"

function StatusCell({ value }: { value: unknown }) {
  const status = String(value)
  return <span className={`order-status order-status--${status.toLowerCase().replaceAll(" ", "-")}`}>{status}</span>
}

const baseColumns: ProColumnDef<OperationOrder>[] = [
  { accessorKey: "id", header: "Order", size: 118, meta: { label: "Order", type: "string" } },
  { accessorKey: "customer", header: "Customer", size: 190, meta: { label: "Customer", type: "string" } },
  {
    accessorKey: "region",
    header: "Region",
    size: 145,
    meta: {
      label: "Region",
      type: "string", filterVariant: "set",
      filterOptions: ["North America", "Europe", "Asia Pacific", "Latin America"],
      groupable: true,
      pivotable: true,
    },
  },
  {
    accessorKey: "status",
    header: "Status",
    size: 120,
    cell: ({ getValue }) => <StatusCell value={getValue()} />,
    meta: {
      label: "Status",
      type: "string", filterVariant: "set",
      filterOptions: ["On track", "At risk", "Delayed", "Complete"],
      groupable: true,
      pivotable: true,
    },
  },
  {
    accessorKey: "units",
    header: "Units",
    size: 88,
    meta: { label: "Units", type: "number", align: "right", aggregable: true, defaultAgg: "sum" },
  },
  {
    accessorKey: "revenue",
    header: "Revenue",
    size: 128,
    meta: {
      label: "Revenue",
      type: "number",
      align: "right",
      aggregable: true,
      defaultAgg: "sum",
      formatValue: (value) => formatCurrency(Number(value)),
    },
  },
]

const groupingDemoRows = operationOrders.slice(0, 60)

/**
 * The Export control as a toolbar button: three file formats plus a
 * destination of the host's own, which receives the same rows a file would
 * have carried instead of downloading anything. The Preview button reads the
 * CSV back through the handle, as a host would before sending it somewhere.
 */
export function ExportDocsDemo() {
  const gridRef = useRef<ProGridHandle<OperationOrder>>(null)
  const [preview, setPreview] = useState<string | null>(null)
  const [sent, setSent] = useState<string | null>(null)

  // Stands in for a Google Sheets upload: a real one POSTs the matrix to your
  // own endpoint, which holds the OAuth credentials.
  const workspace: CustomExportFormat = {
    id: "workspace",
    label: "Send to workspace",
    icon: "sheet",
    export: (matrix, { filename }) => {
      setPreview(null)
      setSent(`Would upload "${filename}" — ${matrix.rows.length} rows × ${matrix.header.at(-1)?.length ?? 0} columns.`)
    },
  }

  return (
    <>
      <div className="docs-demo__status" aria-live="polite">
        <span>{sent ?? "Export from the toolbar, or right-click a range for just those cells."}</span>
        <button
          type="button"
          className="underline"
          onClick={() => {
            setSent(null)
            setPreview(gridRef.current?.getExportText({ format: "csv" }) ?? "")
          }}
        >
          Preview CSV
        </button>
      </div>
      <ProGrid<OperationOrder>
        ref={gridRef}
        columns={baseColumns}
        data={groupingDemoRows}
        getRowId={(row) => row.id}
        height={360}
        initialGrouping={["region"]}
        exportFormats={["csv", "xlsx", "ods", workspace]}
        toolbar={{ export: true, pivot: false, chart: false }}
        title="Orders queue"
      />
      {preview !== null && (
        <pre className="docs-demo__output" aria-label="CSV preview">
          {preview.split("\n").slice(0, 8).join("\n")}
          {preview.split("\n").length > 8 ? "\n…" : ""}
        </pre>
      )}
    </>
  )
}
Export from the toolbar, or right-click a range for just those cells.

Orders queue

Row GroupsRegion
Region
Order
Customer
Status
Units
Revenue
Total
Sum13230
Sum$2,811,630
60 rows

Choosing which formats are offered

exportFormats sets what the Export menus list, and in what order — in the toolbar, the gear, and the body context menu alike. An empty list removes the control everywhere.

// The default: CSV, Excel and OpenDocument, in that order.
<ProGrid columns={columns} data={orders} />

// Only open formats — for a team on LibreOffice, OpenOffice or EuroOffice.
<ProGrid columns={columns} data={orders} exportFormats={["csv", "ods"]} />

// One format, no menu to choose from.
<ProGrid columns={columns} data={orders} exportFormats={["xlsx"]} />

// No export at all.
<ProGrid columns={columns} data={orders} exportFormats={[]} />

Google Sheets and other destinations

Google Sheets is not a file format — it imports CSV, XLSX and ODS, so any of the three already opens there once downloaded. Sending rows straight into a spreadsheet instead means an authenticated call to Google's API, which belongs to your application rather than to a grid component: it needs your OAuth client, your consent screen, and a server to hold the credentials.

So the grid stops at the rows. An entry in exportFormats can be a destination of your own, listed beside the built-in formats and handed the same matrix one of them would have written — for Sheets, for a reporting service, for anything a download cannot reach.

<ProGrid
  columns={columns}
  data={orders}
  exportFormats={[
    "csv",
    "ods",
    {
      id: "sheets",
      label: "Google Sheets",
      icon: "sheet",
      // The same rows an .ods would have contained. Where they go is yours.
      export: async (matrix, { filename }) => {
        await fetch("/api/google-sheets", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ title: filename, rows: matrix }),
        })
      },
    },
  ]}
/>

The handle reaches destinations too: grid.current?.exportGrid({ destination: "sheets" }). A rejected promise is caught and warned about in development rather than left unhandled.

From the handle

Both entry points on ProGridHandle take the same options. exportGrid downloads a file (or runs a destination); getExportText returns the delimited text for you to send or store.

const grid = useRef<ProGridHandle<Order>>(null)

// A file, as the toolbar would produce it.
grid.current?.exportGrid({ format: "ods", filename: "orders-q3" })

// Only the cell range or the checked rows — what Copy would take.
grid.current?.exportGrid({ format: "csv", rows: "selected" })

// The same text without a download, to send somewhere yourself.
const csv = grid.current?.getExportText({ format: "csv", raw: true })
type GridExportOptions = {
  format?: "csv" | "tsv" | "xlsx" | "ods"  // default "csv"
  destination?: string              // id of a custom entry in exportFormats
  rows?: "view" | "selected"        // default "view": every row the filters kept
  headers?: boolean                 // default true
  groupHeaders?: boolean            // default: on while grouped
  raw?: boolean                     // delimited only: numbers instead of formatted text
  filename?: string                 // without extension; defaults to the grid title
  sheetName?: string                // .xlsx / .ods only
}

On the server

The writers are pure. matrixToFile, buildXlsx and buildOds are exported from the server entry, so an API route can hand back the same file the toolbar would, over every matching row rather than one page.

import { buildOds, matrixToFile, type ExportMatrix } from "@andreisaac/pro-grid/server"

// Rows you fetched yourself, as the grid would lay them out.
const matrix: ExportMatrix = {
  header: [["Order", "Customer", "Revenue"]],
  rows: orders.map((o) => [
    { text: o.id },
    { text: o.customer },
    { text: formatCurrency(o.revenue), raw: o.revenue, type: "number" },
  ]),
}
const { content, mime, filename } = matrixToFile(matrix, { format: "ods", filename: "orders" })
return new Response(content, { headers: { "Content-Type": mime, "Content-Disposition": `attachment; filename="${filename}"` } })