# CSV export

> Export the grid's current view as CSV text or a downloadable file, with control over columns, separators, formatting and selection.

`exportCsv()` returns the grid's data as a CSV string. `downloadCsv()` builds the same string and saves it as a file. Both export what the user is looking at: the current filters and sort order apply, columns appear in their current order, and hidden columns are left out. With pagination, every page of the result is exported, not only the current one.

```ts title="export-orders.ts"
import { createGrid } from '@birchui/core';

const grid = createGrid<Order>(document.querySelector('#orders')!, {
  columns,
  rows: orders,
  getRowId: (o) => o.id,
  rowSelection: 'multiple',
  checkboxSelection: true,
});

document.querySelector('#export')!.addEventListener('click', () => {
  grid.downloadCsv({ fileName: `orders-${new Date().toISOString().slice(0, 10)}.csv` });
});
```

## Options

**`CsvExportOptions`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface CsvExportOptions
```

| Property | Type | Description |
| --- | --- | --- |
| `separator?` | `string` |  |
| `includeHeaders?` | `boolean` |  |
| `columns?` | `string[]` |  |
| `onlySelected?` | `boolean` |  |
| `formatted?` | `boolean` |  |
| `fileName?` | `string` |  |

| Option | Default | Meaning |
| --- | --- | --- |
| `separator` | `','` | Field separator. Use `';'` for spreadsheet apps in locales that use a decimal comma, or `'\t'` for TSV. |
| `includeHeaders` | `true` | Write a header row with the column headers. |
| `columns` | All visible columns | Restrict the export to these column IDs. Columns keep the grid's display order, and hidden columns are never exported. |
| `onlySelected` | `false` | Export only selected rows. |
| `formatted` | `false` | Write each column's formatted text (`format` or the type's default formatter) instead of the raw value. |
| `fileName` | `'export.csv'` | File name for `downloadCsv()`. |

### Raw or formatted values

Raw values are best when the file feeds another system: numbers stay numbers and dates stay in their source representation (`Date` values are written as ISO 8601). Formatted values are best when a person will read the file: currency symbols, thousands separators and localized dates appear as they do in the grid.

```ts
const forImport = grid.exportCsv();

const forPeople = grid.exportCsv({ formatted: true, separator: ';' });
```

### Choosing columns

```ts
const csv = grid.exportCsv({
  columns: ['id', 'customer', 'region', 'revenue'],
});
```

To export a column that users normally keep hidden, show it for the export and hide it again:

```ts
grid.setColumnHidden('internalNotes', false);
const withNotes = grid.exportCsv();
grid.setColumnHidden('internalNotes', true);
```

The selection checkbox column is never exported.

### Exporting the selection

`onlySelected: true` exports the selected rows that pass the current filters, in display order.

```ts
document.querySelector('#export-selected')!.addEventListener('click', () => {
  if (grid.getSelectedIds().length === 0) return;
  grid.downloadCsv({ onlySelected: true, fileName: 'selected-orders.csv' });
});
```

## What the file contains

- Lines end with `\r\n`, as RFC 4180 specifies.
- Fields that contain the separator, a double quote or a line break are wrapped in double quotes, and embedded quotes are doubled.
- Empty values (`null` and `undefined`) are written as empty fields.
- The header row uses each column's `header` text.
- Group and total rows from [Grid Pro](https://docs.birchui.com/grid-pro/row-grouping.md) are exported with their aggregate values; full-width rows such as master/detail panels are skipped.
- `downloadCsv()` prefixes the file with a UTF-8 byte order mark so spreadsheet apps detect the encoding and show accented customer names correctly.

### Formula injection protection

A cell whose text starts with `=`, `+`, `-`, `@`, a tab or a carriage return can be interpreted as a formula when the CSV is opened in a spreadsheet. The grid prefixes such string values with a single quote (`=HYPERLINK("https://example.com")` is written as `'=HYPERLINK("https://example.com")`), which spreadsheet apps display as text. Numbers are never prefixed, so negative amounts stay numeric.

## Sending CSV to a server

`exportCsv()` is synchronous and returns a string, so you can post it directly:

```ts
await fetch('/api/reports/orders', {
  method: 'POST',
  headers: { 'content-type': 'text/csv; charset=utf-8' },
  body: grid.exportCsv({ formatted: false }),
});
```

## Excel files

> **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> For real `.xlsx` files with styles, number formats, frozen headers, column widths and grouped rows, install the `ExcelModule` from Grid Pro and call `grid.exportExcel?.()`. The method is optional on `GridApi` because it only exists once the module is installed.
>
> Like CSV export, Excel export includes every page of the result by default, not only the current one. It also respects collapsed groups: a collapsed group is written as its group row, and `exportExcel({ allRows: true })` adds the collapsed rows as hidden outline rows that users can expand in the spreadsheet. See [Excel export & import](https://docs.birchui.com/grid-pro/excel-export.md).

**`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface GridApi<TRow = RowData> extends Widget<GridOptions<TRow>, GridEvents<TRow>>, GridFeatureApi<TRow>
```

| Property | Type | Description |
| --- | --- | --- |
| `exportCsv` | `(options?: CsvExportOptions) => string` |  |
| `downloadCsv` | `(options?: CsvExportOptions) => void` |  |
