Core CSV & JSON export
0.2.0: Types and helpers on this page use the React-state contract from the root
comins-tableentry. Neutral/corehas a separate type contract. See the migration guide for imports and cell policies.
Converts supplied rows and export column definitions into text. It does not automatically query selected rows, pages or server data, or trigger a download.
Live example
Section titled “Live example”import { useMemo, useState } from 'react';import { CominsTable, createCominsTableState, exportCominsRowsToCsv, exportCominsRowsToJson, getCominsPageRows, selectRows, setCominsSortModel, updateCominsRows, addCominsRows, type CominsTableColumn, type CominsExportRowsOptions } from 'comins-table';import 'comins-table/styles.css';
type Row = { id: string; name: string; amount: number };const rows: Row[] = [{ id: 'a', name: 'Alpha', amount: 30 }, { id: 'b', name: 'Beta, quoted', amount: 10 }, { id: 'c', name: 'Gamma', amount: 20 }];
export default function TableCoreDemo({ lang = 'ko' }: { lang?: string }) { const ko = lang === 'ko'; const columns = useMemo<CominsTableColumn<Row>[]>(() => [ { field: 'id', label: 'ID', width: 100 }, { field: 'name', label: ko ? '이름' : 'Name', width: 240 }, { field: 'amount', label: ko ? '수량' : 'Amount', width: 130, sort: true }, ], [ko]); const makeState = () => createCominsTableState({ rows, columns, getRowId: (row: Row) => row.id, pagination: { pageSize: 20 } }); const [state, setState] = useState(makeState); const [format, setFormat] = useState<'csv' | 'json'>('csv'); const [formatted, setFormatted] = useState(false); // Core derives row order. The React Table renders that result through its own props. const displayColumns = useMemo(() => columns.map(column => ({ ...column, sort: false })), [columns]); const displayedRows = getCominsPageRows(state); const options: CominsExportRowsOptions<Row> = { rows: displayedRows, columns: [ { id: 'id', label: 'ID', value: row => row.id }, { id: 'name', label: ko ? '이름' : 'Name', value: row => row.name }, { id: 'amount', label: ko ? '수량' : 'Amount', value: row => row.amount, format: row => `${row.amount} ${ko ? '개' : 'units'}` }, ], valueSource: formatted ? 'formatted' : 'raw', }; const output = format === 'csv' ? exportCominsRowsToCsv(options) : exportCominsRowsToJson(options); return <div className="demo" data-demo="table-core"> <div className="demo-toolbar"> <button onClick={() => setState(value => setCominsSortModel(value, [{ columnId: 'amount', direction: 'asc' }]))}>{ko ? '수량 오름차순' : 'Sort amount ascending'}</button> <button onClick={() => setState(value => selectRows(value, ['a']))}>{ko ? 'ID a 선택' : 'Select ID a'}</button> <button onClick={() => setState(value => updateCominsRows(value, [{ id: 'a', patch: row => ({ ...row, amount: row.amount + 1 }) }]))}>{ko ? 'a 수량 +1' : 'a amount +1'}</button> <button disabled={state.rows.length > 3} onClick={() => setState(value => addCominsRows(value, [{ id: 'd', name: 'Delta', amount: 15 }]))}>{ko ? '행 추가' : 'Add row'}</button> <button onClick={() => { setState(makeState()); setFormat('csv'); setFormatted(false); }}>{ko ? '초기화' : 'Reset'}</button> </div> <div className="table-viewport"> <CominsTable data={displayedRows} columns={displayColumns} getRowId={row => row.id} rowSelectionOnClick={false} rowProps={{ draggable: false }} /> </div> <p className="demo-status" data-core-state>{ko ? '기준 순서' : 'Source order'}: {state.rowIds.join(', ')} · {ko ? '표시 순서' : 'Display order'}: {displayedRows.map(row => row.id).join(', ')} · {ko ? 'Core 선택' : 'Core selection'}: {state.selection.rowIds.join(', ') || '—'}</p> <div className="demo-toolbar" data-export-format style={{ marginTop: 16 }}> <button aria-pressed={format === 'csv'} onClick={() => setFormat('csv')}>CSV</button> <button aria-pressed={format === 'json'} onClick={() => setFormat('json')}>JSON</button> <button aria-pressed={formatted} onClick={() => setFormatted(value => !value)}>{ko ? '표시값 사용' : 'Use formatted values'}: {formatted ? 'ON' : 'OFF'}</button> </div> <pre data-core-export aria-label={ko ? '내보내기 결과' : 'Export result'}>{output}</pre> </div>;}exportCominsRowsToCsv
Section titled “exportCominsRowsToCsv”export declare function exportCominsRowsToCsv<TData>({ columnOrder, columns, headerOverrides, rows, metadata, valueSource, }: CominsExportRowsOptions<TData>): string;Joins one header row and data rows with newlines. Values containing commas, quotes or CR/LF use CSV quoting. null/undefined becomes empty; objects use JSON text. Header precedence is headerOverrides[id] → label → id → empty string.
exportCominsRowsToJson
Section titled “exportCominsRowsToJson”export declare function exportCominsRowsToJson<TData>({ columnOrder, columns, headerOverrides, rows, metadata, valueSource, }: CominsExportRowsOptions<TData>): string;Uses the same resolved headers as object keys and returns a JSON array with two-space indentation. Later columns overwrite repeated keys, so use unique headers. Values follow JSON.stringify rules; cyclic references and bigint can throw.
CominsExportFormat
Section titled “CominsExportFormat”export type CominsExportFormat = "csv" | "json";csv/json format tokens for selecting the corresponding export function.
CominsExportValueSource
Section titled “CominsExportValueSource”export type CominsExportValueSource = "formatted" | "raw";raw is the default and uses value. formatted uses format when available, falling back to value.
CominsExportColumn
Section titled “CominsExportColumn”export type CominsExportColumn<TData> = { format?: (row: TData, rowIndex: number) => unknown; id?: string; label?: string; value: (row: TData, rowIndex: number) => unknown;};| Property | Behavior / default |
|---|---|
format |
Optional conversion for formatted mode. |
id |
Optional ID referenced by columnOrder/headerOverrides. |
label |
Optional header text. |
value |
Required raw-value resolver using the row and its index in the supplied array. |
CominsExportRowsOptions
Section titled “CominsExportRowsOptions”export type CominsExportRowsOptions<TData> = { columnOrder?: string[]; columns: Array<CominsExportColumn<TData>>; headerOverrides?: Record<string, string>; rows: readonly TData[]; metadata?: CominsExportMetadata<TData>; valueSource?: CominsExportValueSource;};| Property | Behavior / default |
|---|---|
columnOrder |
A nonempty list exports only those IDs, in that order. Omitted/empty uses all columns in their original order. |
columns |
Required export column definitions, separate from React display columns. |
headerOverrides |
Header overrides by column ID; also used as JSON keys. |
rows |
Required rows to export; the caller chooses the scope. |
metadata |
Optional management-column getters; see below. |
valueSource |
raw (default) or formatted. |
Related documentation
Section titled “Related documentation”CSV import and structure builders share the same contracts through comins-table/core, without React or DOM.
importCominsRowsFromCsv
Section titled “importCominsRowsFromCsv”export declare function importCominsRowsFromCsv<TData>({ text, mapRow, hasHeader, maxCharacters, maxCells, }: CominsCsvImportOptions<TData>): TData[];Validates all CSV syntax and field counts before mapping application rows. Syntax errors throw SyntaxError; invalid or exceeded limits throw RangeError. Mapper errors propagate without returning partial rows. Side effects cannot be rolled back. Does not read files, generate IDs, update tables or restore Tree/Group structures.
CominsCsvImportRow
Section titled “CominsCsvImportRow”export type CominsCsvImportRow = { cells: readonly string[]; headers: readonly string[] | null; rowIndex: number;};Read-only mapper input. Headers do not create properties or field paths automatically; duplicate headers are preserved.
| Property | Behavior/default |
|---|---|
cells |
Read-only raw cells of the current record. |
headers |
First record by default; null when hasHeader=false. |
rowIndex |
Zero-based data-row index excluding the header. |
CominsCsvImportOptions
Section titled “CominsCsvImportOptions”export type CominsCsvImportOptions<TData> = { text: string; mapRow: (row: CominsCsvImportRow) => TData; hasHeader?: boolean; maxCharacters?: number; maxCells?: number;};Supports CRLF/LF/CR records and doubled quotes. Preserves quoted newlines, spaces, leading zeroes and formula text. Ignores an initial BOM and trailing separator. Empty/header-only input returns an empty array. Actual empty records remain and must match field counts. Processing is synchronous in memory; values are not sanitized for formulas or HTML.
| Property | Behavior/default |
|---|---|
text |
Required CSV text. The caller decodes file bytes. |
mapRow |
Required pure row mapper. Validate headers, values and business rules here. |
hasHeader |
Defaults to true; false treats the first record as data. |
maxCharacters |
Defaults to 1,000,000 UTF-16 code units including BOM. Requires a positive safe integer. |
maxCells |
Defaults to 100,000 cells including headers. Requires a positive safe integer. |
CominsExportMetadata
Section titled “CominsExportMetadata”export type CominsExportMetadata<TData> = { __rowId?: (row: TData, rowIndex: number) => CominsRowId; __parentId?: (row: TData, rowIndex: number) => CominsRowId | null; __depth?: (row: TData, rowIndex: number) => number; __groupId?: (row: TData, rowIndex: number) => CominsRowId | null;};Appends enabled management columns after business columns in __rowId, __parentId, __depth, __groupId order without mutating rows. Conflicting business headers throw. Business-column ordering, labels and formatting do not modify management columns. JSON preserves null and numeric/string IDs; CSV renders null as an empty cell.
| Property | Behavior/default |
|---|---|
__rowId |
Row ID getter. |
__parentId |
Parent ID getter; null for roots. |
__depth |
Depth getter; zero for roots. |
__groupId |
Group ID getter. |
CominsExportTreeOptions
Section titled “CominsExportTreeOptions”export type CominsExportTreeOptions<TData> = Omit<CominsExportRowsOptions<TData>, "rows" | "metadata"> & { nodes: readonly import("./tree").CominsTreeNode<TData>[]; getRowId: (row: TData, sourceIndex: number) => CominsRowId;};Options for exporting the full input tree. Inherits business-column options without inspecting UI collapse, filtering or selection.
| Property | Behavior/default |
|---|---|
nodes |
Required original Tree nodes. |
getRowId |
Required row ID getter. Tree uses preorder indices; Group uses original indices. |
CominsExportGroupedOptions
Section titled “CominsExportGroupedOptions”export type CominsExportGroupedOptions<TData, TGroup> = Omit<CominsExportRowsOptions<TData>, "metadata"> & { groups: readonly TGroup[]; getGroupId: (group: TGroup) => CominsRowId; getRowGroupId: (row: TData, sourceIndex: number) => CominsRowId; getRowId: (row: TData, sourceIndex: number) => CominsRowId;};Options for exporting membership in single-level groups. The caller supplies rows and groups.
| Property | Behavior/default |
|---|---|
groups |
Required groups determining export order. |
getGroupId |
Required group ID getter. |
getRowGroupId |
Required row group ID getter. |
getRowId |
Required row ID getter. Tree uses preorder indices; Group uses original indices. |
createCominsTreeExportOptions
Section titled “createCominsTreeExportOptions”export declare function createCominsTreeExportOptions<TData>({ nodes, getRowId, ...options }: CominsExportTreeOptions<TData>): CominsExportRowsOptions<TData>;Visits every input node in preorder, including collapsed children. Attaches __rowId, __parentId and __depth; roots have null parent and zero depth. getRowId receives preorder indices. Rejects duplicate IDs and cycles. Returns CSV/JSON options preserving original row references. Do not separately reorder or replace returned rows; regenerate options after data or structure changes.
createCominsGroupedExportOptions
Section titled “createCominsGroupedExportOptions”export declare function createCominsGroupedExportOptions<TData, TGroup>({ rows, groups, getGroupId, getRowGroupId, getRowId, ...options }: CominsExportGroupedOptions<TData, TGroup>): CominsExportRowsOptions<TData>;Orders groups as supplied and preserves original input order within groups. Attaches __rowId and __groupId. ID getters use original indices; column value/format use final export indices. Rejects duplicate group/row IDs and unknown groups. Does not add synthetic rows, headings or summaries for empty groups. Use returned rows and options together and regenerate after changes.