# CSV Export

> CSV data export for Yii2 data providers and queries

Package entry: `yii2-extensions/csv-export`. Requires PHP `>=8.3`, Yii2 `~2.0.55 || ^22.0@dev`. Checked 2026-11-29. [View the entry in the package directory](</docs/packages/yii2-extensions/csv-export/index.md>)

**CSV data export for Yii2 data providers and queries**

_Batched reads, file splitting, ZIP archiving, spreadsheet-safe text, and download delivery_

Export a data provider or a query to CSV through a grid-style column configuration. The exporter reads one batch at a
time, can split the result into several files, and delivers it as a saved file or a browser download.

## Features

![Feature Overview](https://raw.githubusercontent.com/yii2-extensions/csv-export/main/docs/svgs/features.svg)

## Quick start

### Installation

Requires PHP 8.3 or later. The built-in archiver needs the `zip` extension when an export produces several files.

```bash
composer require yii2-extensions/csv-export:^0.1
```

For development installs, follow the
[installation guide](https://github.com/yii2-extensions/csv-export/blob/main/docs/installation.md).

### Usage

A sales schema: `order` has a `number`, a `status`, a `total` and a `created_at` timestamp, and references `customer`
(`name`, `email`) through a `customer_id` foreign key. `Order` declares the `customer` relation.

```php
use yii2\extensions\csvexport\CsvExporter;
use yii2\extensions\csvexport\SerialColumn;

$exporter = new CsvExporter(
    [
        // Read 500 orders at a time. with() loads the customers of each batch in one query.
        'query' => Order::find()
            ->with('customer')
            ->where(['status' => 'paid'])
            ->orderBy(['id' => SORT_ASC]),
        'batchSize' => 500,
        'columns' => [
            // A row number that keeps counting across batches and files.
            ['class' => SerialColumn::class],
            // Shorthand: attribute, attribute:format or attribute:format:label.
            // Without a label, the header is the attribute label of the model.
            'number',
            'created_at:datetime:Placed at',
            // A value read through the relation.
            ['attribute' => 'customer.name', 'header' => 'Customer'],
            // A computed value.
            [
                'header' => 'Contact',
                'value' => static fn(Order $order): string => strtolower($order->customer->email),
            ],
            // A formatter format with arguments, and a footer cell.
            ['attribute' => 'total', 'format' => ['decimal', 2], 'footer' => 'Paid orders only'],
        ],
        'showFooter' => true,
        // The limit counts the header and the footer: each file holds up to 49,998 orders and repeats both rows.
        'maxEntriesPerFile' => 50000,
        'csvFileConfig' => [
            'cellDelimiter' => ';',
            // A byte order mark for spreadsheet import.
            'writeBom' => true,
            // An apostrophe before text that a spreadsheet would run as a formula, such as =HYPERLINK(...).
            'spreadsheetSafe' => true,
        ],
        // Files are named orders-001.csv, orders-002.csv; several files are delivered as orders.zip.
        'resultConfig' => ['fileBaseName' => 'orders'],
    ],
);
```

`export()` returns an `ExportResult` that owns the temporary files until they are delivered:

```php
use yii2\extensions\csvexport\ExportResult;

// In a controller action: a download. One file is offered as orders.csv,
// a split export as orders.csv.zip. The temporary files are removed after the response is sent.
return $exporter->export()->send('orders.csv');

// In a console command: publish to a path. A failed delivery returns false
// and leaves the result in place, so it can be saved somewhere else.
$result = $exporter->export();

// Archive even when the orders fit in one file, so the destination is always a ZIP.
$result->forceArchive = true;

if (!$result->saveAs('/reports/orders.zip')) {
    $result->saveAs('/backup/orders.zip');
}

// In a maintenance task: remove the workspaces that interrupted exports left behind more than a day ago.
ExportResult::purgeExpired('@runtime/csv-export', 86400);
```

Data providers, custom archivers and tab-separated output are in the
[Usage Examples](https://github.com/yii2-extensions/csv-export/blob/main/docs/examples.md). The
[Configuration Guide](https://github.com/yii2-extensions/csv-export/blob/main/docs/configuration.md) details every
option, the CSV dialect and the cleanup of temporary files.

## Documentation

Practical guides and complete examples for batched exports, CSV output and delivery.

- 📚 [Installation Guide](https://github.com/yii2-extensions/csv-export/blob/main/docs/installation.md): requirements,
  development installation and the runtime directory.
- ⚙️ [Configuration Guide](https://github.com/yii2-extensions/csv-export/blob/main/docs/configuration.md): data sources,
  columns, splitting, CSV dialect and temporary files.
- 💡 [Usage Examples](https://github.com/yii2-extensions/csv-export/blob/main/docs/examples.md): providers, queries,
  downloads, archives and cleanup.
- 🧪 [Testing Guide](https://github.com/yii2-extensions/csv-export/blob/main/docs/testing.md): development checks.

The guides and the [API reference](https://yii2-framework.github.io/docs/extensions/csv-export/reference/) generated
from the PHPDoc in `src/` are published at <https://yii2-framework.github.io/docs/extensions/csv-export/>.

## AI assistance

AI agents: read the [documentation index](https://yii2-framework.github.io/docs/llms.txt) and fetch the Markdown version
of a page by appending `index.md` to its URL. The
[AI agents guide](https://yii2-framework.github.io/docs/project/ai-agents/) covers skill installation, client setup and
verification.

- 🤖 [`yii2-csv-export` skill](https://github.com/yii2-extensions/csv-export/blob/main/docs/agents.md): batched CSV
  export from data providers and queries, CSV dialect and spreadsheet policy, archiving, delivery and workspace cleanup.
- 🧭 [`yii2-framework` skill](https://yii2-framework.github.io/docs/guide/skills/yii2-framework/): Yii 22.0 application
  conventions.

The hosted documentation covers Yii 22.0. If it does not match the installed revision or is unavailable, use the
[repository guides](#documentation), the [skill source](https://github.com/yii2-extensions/csv-export/blob/main/skills/yii2-csv-export/SKILL.md), the source PHPDoc and the
[changelog](https://github.com/yii2-extensions/csv-export/blob/main/CHANGELOG.md).

## Our social networks

[Follow on X](https://x.com/Terabytesoftw)
[Follow on Facebook](https://www.facebook.com/wilmer.arambula.9)
[Join our Subreddit](https://www.reddit.com/r/Yii2/)
[Join on Telegram](https://t.me/yii_framework_in_english)

## Credits

Inspired by [`yii2tech/csv-grid`](https://github.com/yii2tech/csv-grid) by Paul Klimov.

## License

[License](https://github.com/yii2-extensions/csv-export/blob/main/LICENSE)

## Package

- Source code and issues: [yii2-extensions/csv-export](https://github.com/yii2-extensions/csv-export). Star the repository if the package is useful to you.
- Composer package: [yii2-extensions/csv-export](https://packagist.org/packages/yii2-extensions/csv-export).
- Changelog: [CHANGELOG.md](https://github.com/yii2-extensions/csv-export/blob/main/CHANGELOG.md).