diff --git a/.changeset/data-table-export-columns.md b/.changeset/data-table-export-columns.md new file mode 100644 index 00000000..084cf6c1 --- /dev/null +++ b/.changeset/data-table-export-columns.md @@ -0,0 +1,12 @@ +--- +'@wirecore/wirelayer-recipes': minor +'@wirecore/wirelayer-vue': minor +'@wirecore/wirelayer-react': minor +'@wirecore/wirelayer-native': minor +--- + +DataTable: `exportColumns` splits a column into several columns of the CSV and Excel export, at its position – e.g. +"Name" shown as "Doe, Jane" exported as "First name" and "Last name". It takes precedence over `exportHeader` and +`exportValue`; `exportable: false` and a hidden column export nothing. In Excel the aggregate and footer of the column go +to its first part. Printing keeps the shown column. The React Native DataTable exports the same way (`tableCsv`, +`tableXlsxSheet`); new recipe helper `tableExportColumns`. Story _Export columns_. diff --git a/apps/storybook/src/Introduction.mdx b/apps/storybook/src/Introduction.mdx index a49ee5f8..8f792040 100644 --- a/apps/storybook/src/Introduction.mdx +++ b/apps/storybook/src/Introduction.mdx @@ -332,6 +332,33 @@ narrow screens). `minScrollHeight` keeps it from collapsing; below that the page ``` +## DataTable export (CSV, Excel) + +`exportFilename` shows the export button, `exportFormats` picks CSV, Excel (.xlsx) or both; `generateCsv()` and +`generateXlsx()` return the file instead of downloading it. The export has the filtered and sorted rows of all pages (or +the selection) and the visible columns in their current order. Per column: `exportable: false` leaves it out, +`exportHeader` and `exportValue` replace the name and the value, and `exportColumns` splits it into several columns at +its position – the table keeps showing one column, and printing too: + +```ts +const columns: DataTableColumn[] = [ + { + id: 'name', + header: 'Name', + accessor: (row) => `${row.lastName}, ${row.firstName}`, // shown: "Doe, Jane" + exportColumns: [ + { header: 'First name', value: (row) => row.firstName }, + { header: 'Last name', value: (row) => row.lastName }, + ], + }, + { id: 'club', header: 'Club' }, +]; +// CSV: First name;Last name;Club +``` + +`exportColumns` takes precedence over `exportHeader` and `exportValue`. In Excel the aggregate and the footer of a split +column go to its first part. The React Native DataTable exports the same way. + ## AI assistants (MCP, llms.txt) So that Claude, Cursor and others use the components correctly, the API is available as text and as an MCP server: diff --git a/packages/mcp/data/components.json b/packages/mcp/data/components.json index 36281473..5054203f 100644 --- a/packages/mcp/data/components.json +++ b/packages/mcp/data/components.json @@ -38146,6 +38146,11 @@ "title": "DataTable feature modules", "text": "Parts of the DataTable that bring a lot of code along are imported on their own – an app only bundles the ones it passes\nin `features` (fixed for the life of a table). The DatePicker alone is about 40 KB (gzip).\n\n| Feature | Import | Adds | Without it |\n| ---------------- | ---------------------------------------------------------------------- | ---------------------------------------------------- | -------------------------------------------- |\n| `virtualRows` | `@wirecore/wirelayer-react/virtual` (peer dependency TanStack Virtual) | only the visible rows are rendered with `virtual` | all rows are rendered, a hint in development |\n| `dateInput` | `@wirecore/wirelayer-react/data-table` | DatePicker for `date` and `datetime` filters/editors | the browser's date input |\n| `numberInput` | `@wirecore/wirelayer-react/data-table` | NumberInput for `number` filters and editors | the browser's number input |\n| `dateRangeInput` | `@wirecore/wirelayer-react/data-table` | one DateRangePicker for `between` filters of dates | two fields (from, to) |\n\n```tsx\nimport { DataTable, dateInput, numberInput } from '@wirecore/wirelayer-react/data-table';\nimport { virtualRows } from '@wirecore/wirelayer-react/virtual';\n\n// Once for all tables of the app\nconst features = [virtualRows, dateInput, numberInput];\n\n;\n```\n\n```vue\n\n```\n\nVue: the same imports from `@wirecore/wirelayer-vue/data-table` and `@wirecore/wirelayer-vue/virtual`.\n\n`scrollHeight` takes a CSS length – the maximum height, the rows scroll inside – or `fill`: the table takes the rest of a\nflex column and the rows scroll in the room left down to its bottom, whatever is above it (headings, figures that wrap on\nnarrow screens). `minScrollHeight` keeps it from collapsing; below that the page scrolls.\n\n```vue\n
\n \n \n \n
\n```" }, + { + "id": "introduction-datatable-export-csv-excel", + "title": "DataTable export (CSV, Excel)", + "text": "`exportFilename` shows the export button, `exportFormats` picks CSV, Excel (.xlsx) or both; `generateCsv()` and\n`generateXlsx()` return the file instead of downloading it. The export has the filtered and sorted rows of all pages (or\nthe selection) and the visible columns in their current order. Per column: `exportable: false` leaves it out,\n`exportHeader` and `exportValue` replace the name and the value, and `exportColumns` splits it into several columns at\nits position – the table keeps showing one column, and printing too:\n\n```ts\nconst columns: DataTableColumn[] = [\n {\n id: 'name',\n header: 'Name',\n accessor: (row) => `${row.lastName}, ${row.firstName}`, // shown: \"Doe, Jane\"\n exportColumns: [\n { header: 'First name', value: (row) => row.firstName },\n { header: 'Last name', value: (row) => row.lastName },\n ],\n },\n { id: 'club', header: 'Club' },\n];\n// CSV: First name;Last name;Club\n```\n\n`exportColumns` takes precedence over `exportHeader` and `exportValue`. In Excel the aggregate and the footer of a split\ncolumn go to its first part. The React Native DataTable exports the same way." + }, { "id": "introduction-ai-assistants-mcp-llms-txt", "title": "AI assistants (MCP, llms.txt)", diff --git a/packages/native/src/data-table/types.ts b/packages/native/src/data-table/types.ts index 3aa94d5e..d18ab13d 100644 --- a/packages/native/src/data-table/types.ts +++ b/packages/native/src/data-table/types.ts @@ -74,6 +74,12 @@ export interface DataTableColumn { exportHeader?: string; /** Value in the export (default: the shown text) */ exportValue?: (row: TData) => unknown; + /** + * The column is replaced by these columns in the CSV/Excel export (in this order, at its position) – e.g. "Name" + * shown as "Doe, Jane" exported as "First name" and "Last name". Takes precedence over `exportHeader` and + * `exportValue`; with `exportable: false` nothing is exported + */ + exportColumns?: { header: string; value: (row: TData) => unknown }[]; /** Own cell content (default: the formatted value) – screen readers still read "header: text" on iOS/Android */ cell?: (row: TData, value: unknown) => ReactNode; } diff --git a/packages/parity/e2e/visual/__screenshots__/react-data-datatable--export-columns.png b/packages/parity/e2e/visual/__screenshots__/react-data-datatable--export-columns.png new file mode 100644 index 00000000..b26c567e Binary files /dev/null and b/packages/parity/e2e/visual/__screenshots__/react-data-datatable--export-columns.png differ diff --git a/packages/parity/src/data-table.test.ts b/packages/parity/src/data-table.test.ts index 8f1407f1..94720573 100644 --- a/packages/parity/src/data-table.test.ts +++ b/packages/parity/src/data-table.test.ts @@ -1717,6 +1717,70 @@ describe.each(frameworks)('%s DataTable', (framework) => { ); }); + it('exportColumns: a column becomes several export columns at its position; hidden or not exportable: none', async () => { + let handle: { generateCsv: (options?: object) => string } | undefined; + const kind = (row: { name: string }) => row.name.split('-')[0]; + const number = (row: { name: string }) => row.name.split('-').slice(1).join('-'); + const split = (hiddenColumns: string[]) => + table({ + ref: (value: typeof handle | null) => (handle = value ?? handle), + hiddenColumns, + columns: [ + { + id: 'name', + header: 'Name', + // exportColumns takes precedence + exportHeader: 'Hostname', + exportValue: () => 'unused', + exportColumns: [ + { header: 'Kind', value: kind }, + { header: 'Number', value: number }, + ], + }, + { id: 'location', header: 'Location' }, + { + id: 'load', + header: 'Load', + exportable: false, + exportColumns: [{ header: 'Never', value: () => 1 }], + }, + ], + }); + await render(framework, split([])); + expect(handle!.generateCsv({ bom: false }).split('\r\n')).toEqual([ + 'Kind,Number,Location', + 'web,01,Frankfurt', + 'db,primary,Frankfurt', + 'k8s,node-3,Nuremberg', + ]); + // The table still shows the one column + expect(screen.getByRole('columnheader', { name: 'Name' })).toBeInTheDocument(); + expect(screen.queryByRole('columnheader', { name: 'Kind' })).not.toBeInTheDocument(); + }); + + it('exportColumns of a hidden column are left out too', async () => { + let handle: { generateCsv: (options?: object) => string } | undefined; + await render( + framework, + table({ + ref: (value: typeof handle | null) => (handle = value ?? handle), + hiddenColumns: ['name'], + columns: [ + { + id: 'name', + header: 'Name', + exportColumns: [ + { header: 'Kind', value: () => 'k' }, + { header: 'Number', value: () => 'n' }, + ], + }, + { id: 'location', header: 'Location' }, + ], + }) + ); + expect(handle!.generateCsv({ bom: false }).split('\r\n')[0]).toBe('Location'); + }); + it('csvSeparator sets the separator of the export, the option of a single export still wins', async () => { let handle: { generateCsv: (options?: object) => string } | undefined; await render( @@ -2034,6 +2098,40 @@ describe.each(frameworks)('%s DataTable spreadsheet, server and layout', (framew expect(screen.getByRole('menuitem', { name: 'All rows as CSV' })).toBeInTheDocument(); }); + it('Excel export with exportColumns: the parts as columns, aggregates and footer in the first part', async () => { + let handle: Handle | undefined; + await render( + framework, + table({ + ref: (value: Handle | null) => (handle = value ?? handle), + columns: [ + { id: 'name', header: 'Name' }, + { id: 'location', header: 'Location', groupable: true }, + { + id: 'load', + header: 'Load', + aggregate: 'sum', + exportColumns: [ + { header: 'Load %', value: (row: { load: number }) => row.load }, + { header: 'Busy', value: (row: { load: number }) => (row.load > 50 ? 'yes' : 'no') }, + ], + }, + ], + groupBy: 'location', + }) + ); + const sheet = sheetXml(handle!.generateXlsx()); + const cells = (row: number) => [...sheet.querySelectorAll(`row[r="${row}"] c`)].map((cell) => cell.textContent); + expect(cells(1)).toEqual(['Name', 'Location', 'Load %', 'Busy']); + // Group row: the label in the first column, the sum in the first part, the second part empty + expect(cells(2)).toEqual(['Location: Frankfurt (2)', '', '113', '']); + expect(cells(3)).toEqual(['web-01', 'Frankfurt', '42', 'no']); + expect(sheet.querySelector('c[r="C3"]')!.getAttribute('t')).toBeNull(); + expect(cells(4)).toEqual(['db-primary', 'Frankfurt', '71', 'yes']); + // Total row: the sum in the first part + expect(cells(7)).toEqual(['Total', '', '131', '']); + }); + it('cell range: dragging and Shift+arrow keys select cells, Ctrl+C copies them as tab-separated text', async () => { const onRange = vi.fn(); await render(framework, table({ navigation: 'grid', cellSelection: true, onCellSelectionChange: onRange })); diff --git a/packages/parity/src/native-data.test.ts b/packages/parity/src/native-data.test.ts index dfb8290e..bb3316a5 100644 --- a/packages/parity/src/native-data.test.ts +++ b/packages/parity/src/native-data.test.ts @@ -177,6 +177,43 @@ describe('export', () => { ); }); + it('exportColumns: a column becomes several columns at its position, also in the Excel sheet', () => { + const split: TableViewColumn[] = [ + { + id: 'name', + header: 'Name', + exportHeader: 'unused', + exportColumns: [ + { header: 'Prefix', value: (row) => row.name.split('-')[0] }, + { header: 'Number', value: (row) => Number(row.name.split('-')[1]) }, + ], + }, + { id: 'city', header: 'City' }, + { + id: 'load', + header: 'Load', + aggregate: 'sum', + exportColumns: [ + { header: 'Load', value: (row) => row.load }, + { header: 'Note', value: () => '' }, + ], + }, + { id: 'id', header: 'No.', exportable: false, exportColumns: [{ header: 'Never', value: () => 1 }] }, + ]; + expect(tableCsv(rows.slice(0, 1), split, { bom: false })).toBe( + 'Prefix;Number;City;Load;Note\r\nsrv;10;Cologne;40;' + ); + const sheet = tableXlsxSheet(rows.slice(0, 2), split, { groupBy: column('city'), totalLabel: 'Total' }); + expect(sheet.columns.map((part) => part.header)).toEqual(['Prefix', 'Number', 'City', 'Load', 'Note']); + expect(sheet.rows.map((row) => [row.kind ?? 'data', ...row.cells])).toEqual([ + ['group', 'City: Cologne (1)', null, null, 40, null], + ['data', 'srv', 10, 'Cologne', 40, ''], + ['group', 'City: Berlin (1)', null, null, 85, null], + ['data', 'srv', 2, 'Berlin', 85, ''], + ['total', 'Total', null, null, 125, null], + ]); + }); + it('Excel cells: numbers stay numbers, date columns become dates, yes/no stays', () => { expect(xlsxCellValue(columns[2]!, rows[0]!)).toBe(40); expect(xlsxCellValue(columns[3]!, rows[0]!)).toEqual({ date: '2024-03-01' }); diff --git a/packages/react/src/data-table/DataTable.stories.tsx b/packages/react/src/data-table/DataTable.stories.tsx index fa4ce229..c8ba6530 100644 --- a/packages/react/src/data-table/DataTable.stories.tsx +++ b/packages/react/src/data-table/DataTable.stories.tsx @@ -1852,3 +1852,52 @@ export const ColumnSettings: Story = { /> ), }; + +const people = [ + { id: 'p1', firstName: 'Anna', lastName: 'Muster', club: 'TSV Nord', born: 2009 }, + { id: 'p2', firstName: 'Jonas', lastName: 'Becker', club: 'SC Süd', born: 2011 }, + { id: 'p3', firstName: 'Lea', lastName: 'Albrecht', club: 'TSV Nord', born: 2010 }, +]; +type Person = (typeof people)[number]; +const personColumns: DataTableColumn[] = [ + { + id: 'name', + header: 'Name', + accessor: (row) => `${row.lastName}, ${row.firstName}`, + exportColumns: [ + { header: 'First name', value: (row) => row.firstName }, + { header: 'Last name', value: (row) => row.lastName }, + ], + }, + { id: 'club', header: 'Club' }, + { id: 'born', header: 'Born', align: 'end' }, +]; + +function ExportColumnsDemo() { + const [csv, setCsv] = useState(''); + return ( +
+ + ref={(handle: DataTableHandle | null) => { + if (handle && !csv) setCsv(handle.generateCsv({ bom: false, separator: ';' })); + }} + features={features} + data={people} + columns={personColumns} + caption="Participants" + getRowId={(row) => row.id} + exportFilename="participants" + exportFormats={['csv', 'xlsx']} + className={card} + /> +

CSV export

+
{csv}
+
+ ); +} + +/** + * `exportColumns`: the table shows "Last name, first name" in one column, the CSV and Excel export split it into + * "First name" and "Last name" (printing keeps the shown column) + */ +export const ExportColumns: Story = { name: 'Export columns', render: () => }; diff --git a/packages/react/src/data-table/DataTable.tsx b/packages/react/src/data-table/DataTable.tsx index c42cc6fc..4aed32d0 100644 --- a/packages/react/src/data-table/DataTable.tsx +++ b/packages/react/src/data-table/DataTable.tsx @@ -85,6 +85,7 @@ import { saveTableState, syncGrid, treeGridKeyAction, + tableExportColumns, toCsv, toTsv, treeDropMove, @@ -2607,18 +2608,17 @@ export function DataTable({ .getVisibleLeafColumns() .map((column) => columnById.get(column.id)!) .filter((column) => column.exportable !== false); + const parts = tableExportColumns>(visible); const rows = ( options.selectionOnly ? table.getSelectedRowModel().flatRows : table.getSortedRowModel().flatRows ).filter((row) => !row.getIsGrouped()); const records = rows.map((row) => - visible.map((column) => - column.exportValue - ? column.exportValue(row.original) - : display(column, row.getValue(column.id), row.original) + parts.map(({ column, value }) => + value ? value(row.original) : display(column, row.getValue(column.id), row.original) ) ); const separator = options.separator ?? csvSeparatorProp ?? csvSeparator(locale); - const csv = toCsv([visible.map((column) => column.exportHeader ?? column.header), ...records], separator); + const csv = toCsv([parts.map((part) => part.header), ...records], separator); return options.bom === false ? csv.slice(1) : csv; }; const exportCsv = (options: boolean | DataTableCsvOptions = false) => { @@ -2665,6 +2665,7 @@ export function DataTable({ .getVisibleLeafColumns() .map((column) => columnById.get(column.id)!) .filter((column) => column.exportable !== false); + const parts = tableExportColumns>(visible); const rows: XlsxRow[] = exportRows(options.selectionOnly) .filter((entry) => !entry.group || options.groups !== false) .map(({ row, group, depth }) => { @@ -2673,9 +2674,10 @@ export function DataTable({ return { kind: 'group', level: depth, - cells: visible.map((column, index) => { + cells: parts.map(({ column, first }, index) => { if (index === 0) return groupLabel(row); - if (!column.aggregate) return null; + // Aggregates of a split column (exportColumns) in its first part + if (!first || !column.aggregate) return null; const value = aggregateValues( leaves.map((leaf) => rawValue(column, leaf.original)), column.aggregate @@ -2686,9 +2688,9 @@ export function DataTable({ } return { level: options.groups === false ? 0 : depth, - cells: visible.map((column) => { - if (column.exportValue) { - const value = column.exportValue(row.original); + cells: parts.map(({ column, value: exportValue }) => { + if (exportValue) { + const value = exportValue(row.original); return typeof value === 'number' || typeof value === 'boolean' ? value : value instanceof Date @@ -2699,9 +2701,10 @@ export function DataTable({ }), }; }); - if (options.totals !== false && visible.some((column) => column.aggregate || column.footer)) { + if (options.totals !== false && parts.some(({ column }) => column.aggregate || column.footer)) { const leaves = table.getFilteredRowModel().flatRows.filter((row) => !row.getIsGrouped()); - const cells = visible.map((column): XlsxValue => { + const cells = parts.map(({ column, first }): XlsxValue => { + if (!first) return null; if (column.footer !== undefined) return column.footer; if (!column.aggregate) return null; const value = aggregateValues( @@ -2715,7 +2718,7 @@ export function DataTable({ } return createXlsx({ name: options.sheetName ?? caption, - columns: visible.map((column) => ({ header: column.exportHeader ?? column.header })), + columns: parts.map((part) => ({ header: part.header })), rows, }); }; diff --git a/packages/react/src/data-table/types.ts b/packages/react/src/data-table/types.ts index b0f81c0c..91553686 100644 --- a/packages/react/src/data-table/types.ts +++ b/packages/react/src/data-table/types.ts @@ -222,6 +222,12 @@ export interface DataTableColumn { exportHeader?: string; /** Value in the CSV export (default: the shown text) */ exportValue?: (row: TData) => unknown; + /** + * The column is replaced by these columns in the CSV/Excel export (in this order, at its position) – e.g. "Name" + * shown as "Doe, Jane" exported as "First name" and "Last name". Takes precedence over `exportHeader` and + * `exportValue`; with `exportable: false` nothing is exported. Printing keeps the shown column + */ + exportColumns?: { header: string; value: (row: TData) => unknown }[]; /** A copy button next to the value */ copyable?: boolean; /** diff --git a/packages/recipes/src/index.ts b/packages/recipes/src/index.ts index 00990956..2945a065 100644 --- a/packages/recipes/src/index.ts +++ b/packages/recipes/src/index.ts @@ -1142,10 +1142,13 @@ export { sortTableRows, tableAggregateText, tableCsv, + tableExportColumns, tablePageCount, tableXlsxSheet, xlsxCellValue, type TableCsvOptions, + type TableExportColumn, + type TableExportColumnPart, type TableRowGroup, type TableViewColumn, type TableViewFilter, diff --git a/packages/recipes/src/native/index.ts b/packages/recipes/src/native/index.ts index 9b98ae23..a9233671 100644 --- a/packages/recipes/src/native/index.ts +++ b/packages/recipes/src/native/index.ts @@ -386,10 +386,13 @@ export { sortTableRows, tableAggregateText, tableCsv, + tableExportColumns, tablePageCount, tableXlsxSheet, xlsxCellValue, type TableCsvOptions, + type TableExportColumn, + type TableExportColumnPart, type TableRowGroup, type TableViewColumn, type TableViewFilter, diff --git a/packages/recipes/src/table-view.ts b/packages/recipes/src/table-view.ts index a8820b24..e68735df 100644 --- a/packages/recipes/src/table-view.ts +++ b/packages/recipes/src/table-view.ts @@ -40,6 +40,12 @@ export interface TableViewColumn { exportHeader?: string; /** Value in the export (default: the shown text) */ exportValue?: (row: T) => unknown; + /** + * The column is replaced by these columns in the CSV/Excel export (in this order, at its position) – e.g. "Name" + * shown as "Doe, Jane" exported as "First name" and "Last name". Takes precedence over `exportHeader` and + * `exportValue`; with `exportable: false` nothing is exported + */ + exportColumns?: readonly TableExportColumnPart[]; /** Total of the column (footer, group rows of the Excel export) */ aggregate?: DataTableAggregate | ((values: unknown[]) => unknown); /** Footer text of the column (instead of the aggregate) */ @@ -224,6 +230,50 @@ export function tableAggregateText(rows: readonly T[], column: TableViewColum export const exportColumns = (columns: readonly TableViewColumn[]) => columns.filter((column) => column.exportable !== false); +/** One of the export columns a column is split into (`exportColumns`) */ +export interface TableExportColumnPart { + header: string; + value: (row: T) => unknown; +} + +/** One column of a CSV/Excel export: a column of the table, or one of the `exportColumns` it is split into */ +export interface TableExportColumn { + column: C; + header: string; + /** Value of the cell (`exportValue` or the part's); none: the shown text of the column */ + value?: (row: T) => unknown; + /** The first (or only) export column of its column – it gets the column's aggregate and footer */ + first: boolean; +} + +/** + * The columns of an export, in the order of `columns`: `exportable: false` left out, a column with `exportColumns` + * replaced by its parts, the others with `exportHeader` and `exportValue` + */ +export function tableExportColumns< + T, + C extends { + header: string; + exportable?: boolean; + exportHeader?: string; + exportValue?: (row: T) => unknown; + exportColumns?: readonly TableExportColumnPart[]; + }, +>(columns: readonly C[]): TableExportColumn[] { + return columns + .filter((column) => column.exportable !== false) + .flatMap((column): TableExportColumn[] => + column.exportColumns + ? column.exportColumns.map((part, index) => ({ + column, + header: part.header, + value: part.value, + first: index === 0, + })) + : [{ column, header: column.exportHeader ?? column.header, value: column.exportValue, first: true }] + ); +} + /** Options of the CSV of a table */ export interface TableCsvOptions { /** Separator (default ";"; the DataTable passes its `csvSeparator`, by default from the locale) */ @@ -232,19 +282,20 @@ export interface TableCsvOptions { bom?: boolean; } -/** The CSV of rows: a header line (`exportHeader`), the values (`exportValue`, else the shown text) */ +/** + * The CSV of rows: a header line (`exportHeader`), the values (`exportValue`, else the shown text); a column with + * `exportColumns` becomes several columns + */ export function tableCsv( rows: readonly T[], columns: readonly TableViewColumn[], { separator, bom = true }: TableCsvOptions = {} ): string { - const visible = exportColumns(columns); + const parts = tableExportColumns>(columns); const csv = toCsv( [ - visible.map((column) => column.exportHeader ?? column.header), - ...rows.map((row) => - visible.map((column) => (column.exportValue ? column.exportValue(row) : cellText(column, row))) - ), + parts.map((part) => part.header), + ...rows.map((row) => parts.map((part) => (part.value ? part.value(row) : cellText(part.column, row)))), ], separator ); @@ -252,9 +303,13 @@ export function tableCsv( } /** A cell of the Excel export: numbers as numbers, dates (filter type `date`) as dates, else the shown text */ -export function xlsxCellValue(column: TableViewColumn, row: T): XlsxValue { - if (column.exportValue) { - const value = column.exportValue(row); +export function xlsxCellValue( + column: TableViewColumn, + row: T, + exportValue: ((row: T) => unknown) | undefined = column.exportValue +): XlsxValue { + if (exportValue) { + const value = exportValue(row); if (typeof value === 'number') return Number.isFinite(value) ? value : null; if (typeof value === 'boolean') return value; if (value instanceof Date) return { date: value }; @@ -289,10 +344,10 @@ export function tableXlsxSheet( columns: readonly TableViewColumn[], { name, groupBy, groupLabel, totals = true, totalLabel = '' }: TableXlsxOptions = {} ): XlsxSheet { - const visible = exportColumns(columns); + const parts = tableExportColumns>(columns); const dataRow = (row: T, level: number): XlsxRow => ({ level, - cells: visible.map((column) => xlsxCellValue(column, row)), + cells: parts.map((part) => xlsxCellValue(part.column, row, part.value)), }); const aggregateCell = (column: TableViewColumn, list: readonly T[]): XlsxValue => { if (!column.aggregate) return null; @@ -306,25 +361,28 @@ export function tableXlsxSheet( ? groupTableRows(rows, groupBy).flatMap((group) => [ { kind: 'group' as const, - cells: visible.map((column, index) => + // Aggregates of a split column in its first part + cells: parts.map((part, index) => index === 0 ? (groupLabel?.(group) ?? `${groupBy.header}: ${group.text} (${group.rows.length})`) - : aggregateCell(column, group.rows) + : part.first + ? aggregateCell(part.column, group.rows) + : null ), }, ...group.rows.map((row) => dataRow(row, 1)), ]) : rows.map((row) => dataRow(row, 0)); - if (totals && visible.some((column) => column.aggregate || column.footer !== undefined)) { - const cells = visible.map((column) => - column.footer !== undefined ? column.footer : aggregateCell(column, rows) + if (totals && parts.some(({ column }) => column.aggregate || column.footer !== undefined)) { + const cells = parts.map(({ column, first }) => + !first ? null : column.footer !== undefined ? column.footer : aggregateCell(column, rows) ); if (cells[0] === null) cells[0] = totalLabel; sheetRows.push({ kind: 'total', cells }); } return { name, - columns: visible.map((column) => ({ header: column.exportHeader ?? column.header })), + columns: parts.map((part) => ({ header: part.header })), rows: sheetRows, }; } diff --git a/packages/vue/src/data-table/DataTable.stories.ts b/packages/vue/src/data-table/DataTable.stories.ts index 5b8bb950..a129cb03 100644 --- a/packages/vue/src/data-table/DataTable.stories.ts +++ b/packages/vue/src/data-table/DataTable.stories.ts @@ -2198,3 +2198,62 @@ export const ColumnSettings: Story = {
`, }), }; + +const people = [ + { id: 'p1', firstName: 'Anna', lastName: 'Muster', club: 'TSV Nord', born: 2009 }, + { id: 'p2', firstName: 'Jonas', lastName: 'Becker', club: 'SC Süd', born: 2011 }, + { id: 'p3', firstName: 'Lea', lastName: 'Albrecht', club: 'TSV Nord', born: 2010 }, +]; +type Person = (typeof people)[number]; + +/** + * `exportColumns`: the table shows "Last name, first name" in one column, the CSV and Excel export split it into + * "First name" and "Last name" (printing keeps the shown column) + */ +export const ExportColumns: Story = { + name: 'Export columns', + render: () => ({ + components: { DataTable: DataTable as ConcreteComponent }, + setup: () => { + const table = ref<{ generateCsv: (options?: object) => string }>(); + const csv = computed(() => table.value?.generateCsv({ bom: false, separator: ';' }) ?? ''); + return { + features, + rows: people, + card, + table, + csv, + getRowId: (row: Person) => row.id, + columns: [ + { + id: 'name', + header: 'Name', + accessor: (row: Person) => `${row.lastName}, ${row.firstName}`, + exportColumns: [ + { header: 'First name', value: (row: Person) => row.firstName }, + { header: 'Last name', value: (row: Person) => row.lastName }, + ], + }, + { id: 'club', header: 'Club' }, + { id: 'born', header: 'Born', align: 'end' }, + ], + }; + }, + template: ` +
+ +

CSV export

+
{{ csv }}
+
`, + }), +}; diff --git a/packages/vue/src/data-table/DataTable.vue b/packages/vue/src/data-table/DataTable.vue index 3841cae3..5df7065b 100644 --- a/packages/vue/src/data-table/DataTable.vue +++ b/packages/vue/src/data-table/DataTable.vue @@ -121,6 +121,7 @@ import { saveTableState, syncGrid, treeGridKeyAction, + tableExportColumns, toCsv, toTsv, treeDropMove, @@ -2606,18 +2607,17 @@ function generateCsv(options: DataTableCsvOptions = {}) { .getVisibleLeafColumns() .map((column) => columnById.value.get(column.id)!) .filter((column) => column.exportable !== false); + const parts = tableExportColumns>(visible); const rows = ( options.selectionOnly ? table.getSelectedRowModel().flatRows : table.getSortedRowModel().flatRows ).filter((row) => !row.getIsGrouped()); const records = rows.map((row) => - visible.map((column) => - column.exportValue - ? column.exportValue(row.original) - : display(column, row.getValue(column.id), row.original) + parts.map(({ column, value }) => + value ? value(row.original) : display(column, row.getValue(column.id), row.original) ) ); const separator = options.separator ?? props.csvSeparator ?? localeCsvSeparator(localeContext.value.locale); - const csv = toCsv([visible.map((column) => column.exportHeader ?? column.header), ...records], separator); + const csv = toCsv([parts.map((part) => part.header), ...records], separator); return options.bom === false ? csv.slice(1) : csv; } /** Downloads the CSV – `true` (or `{ selectionOnly: true }`) only the selected rows */ @@ -2666,6 +2666,7 @@ function generateXlsx(options: DataTableXlsxOptions = {}) { .getVisibleLeafColumns() .map((column) => columnById.value.get(column.id)!) .filter((column) => column.exportable !== false); + const parts = tableExportColumns>(visible); const rows: XlsxRow[] = exportRows(options.selectionOnly) .filter((entry) => !entry.group || options.groups !== false) .map(({ row, group, depth }): XlsxRow => { @@ -2674,9 +2675,10 @@ function generateXlsx(options: DataTableXlsxOptions = {}) { return { kind: 'group', level: depth, - cells: visible.map((column, index) => { + cells: parts.map(({ column, first }, index) => { if (index === 0) return groupLabel(row); - if (!column.aggregate) return null; + // Aggregates of a split column (exportColumns) in its first part + if (!first || !column.aggregate) return null; const value = aggregateValues( leaves.map((leaf) => rawValue(column, leaf.original)), column.aggregate @@ -2687,9 +2689,9 @@ function generateXlsx(options: DataTableXlsxOptions = {}) { } return { level: options.groups === false ? 0 : depth, - cells: visible.map((column) => { - if (column.exportValue) { - const value = column.exportValue(row.original); + cells: parts.map(({ column, value: exportValue }) => { + if (exportValue) { + const value = exportValue(row.original); return typeof value === 'number' || typeof value === 'boolean' ? value : value instanceof Date @@ -2700,9 +2702,10 @@ function generateXlsx(options: DataTableXlsxOptions = {}) { }), }; }); - if (options.totals !== false && visible.some((column) => column.aggregate || column.footer)) { + if (options.totals !== false && parts.some(({ column }) => column.aggregate || column.footer)) { const leaves = table.getFilteredRowModel().flatRows.filter((row) => !row.getIsGrouped()); - const cells = visible.map((column): XlsxValue => { + const cells = parts.map(({ column, first }): XlsxValue => { + if (!first) return null; if (column.footer !== undefined) return column.footer; if (!column.aggregate) return null; const value = aggregateValues( @@ -2716,7 +2719,7 @@ function generateXlsx(options: DataTableXlsxOptions = {}) { } return createXlsx({ name: options.sheetName ?? props.caption, - columns: visible.map((column) => ({ header: column.exportHeader ?? column.header })), + columns: parts.map((part) => ({ header: part.header })), rows, }); } diff --git a/packages/vue/src/data-table/types.ts b/packages/vue/src/data-table/types.ts index 315c9936..981c5248 100644 --- a/packages/vue/src/data-table/types.ts +++ b/packages/vue/src/data-table/types.ts @@ -222,6 +222,12 @@ export interface DataTableColumn { exportHeader?: string; /** Value in the CSV export (default: the shown text) */ exportValue?: (row: TData) => unknown; + /** + * The column is replaced by these columns in the CSV/Excel export (in this order, at its position) – e.g. "Name" + * shown as "Doe, Jane" exported as "First name" and "Last name". Takes precedence over `exportHeader` and + * `exportValue`; with `exportable: false` nothing is exported. Printing keeps the shown column + */ + exportColumns?: { header: string; value: (row: TData) => unknown }[]; /** A copy button next to the value */ copyable?: boolean; /**