Loading...
Please waitLoading...
Please waitpnpm dlx uselab@latest add use-table-export-csv
import { useTableExportCSV } from "@/hooks/use-table-export-csv"
interface Product {
id: number
name: string
price: number
category: string
}
export function Component() {
const { exportCSV } = useTableExportCSV<Product>()
const products: Product[] = [
{ id: 1, name: "Laptop", price: 999.99, category: "Electronics" },
{ id: 2, name: "Mouse", price: 29.99, category: "Accessories" },
]
const columns = [
{ key: "id" as const, header: "ID" },
{ key: "name" as const, header: "Product Name" },
{
key: "price" as const,
header: "Price",
accessor: (row: Product) => `$${row.price.toFixed(2)}`,
},
{ key: "category" as const, header: "Category" },
]
const handleExport = () => {
exportCSV(products, columns, "products-export")
}
return <button onClick={handleExport}>Export to CSV</button>
}exportCSV(rows, columns, filename?):
rows: Array of data objects to export.columns: Array of column definitions with key, header, and optional accessor.filename: Optional filename (defaults to "export.csv").Column Definition:
key: Property name from the row object or a string identifier.header: Display name for the CSV header.accessor: Optional function to transform the value before export.Automatic Formatting:
| Name | Type | Description |
|---|---|---|
exportCSV | (rows: T[], columns: Column<T>[], filename?: string) => void | Exports the table data to a CSV file. |
| Name | Type | Description |
|---|---|---|
key | keyof T | The property key from the row object. |
header | string | The display name for the CSV header column. |
accessor | (row: T) => string | number (optional) | Optional function to transform or format the value before export. |
| ID | Product Name | Price | Category |
|---|---|---|---|
| 1 | Laptop | $999.99 | Electronics |
| 2 | Mouse | $29.99 | Accessories |
| 3 | Keyboard | $79.99 | Accessories |
| 4 | Monitor | $299.99 | Electronics |
Click "Export to CSV" to download the table data as a CSV file.