# Usage examples

> The examples assume a Yii application and an Item ActiveRecord class. Options are described in configuration.

The examples assume a Yii application and an `Item` ActiveRecord class. Options are described in
[configuration](/docs/extensions/csv-export/configuration/index.md).

## Export a data provider

The pagination page size is the export batch size.

```php
<?php

use yii2\extensions\csvexport\CsvExporter;
use yii\data\ActiveDataProvider;

$exporter = new CsvExporter(
    [
        'dataProvider' => new ActiveDataProvider([
            'query' => Item::find()->orderBy('id'),
            'pagination' => [
                'pageSize' => 100, // export batch size
            ],
        ]),
    ],
);

$exporter->export()->saveAs('/path/to/file.csv');
```

If pagination is disabled in the data provider, no batch processing is performed.

## Export a query

```php
<?php

use yii2\extensions\csvexport\CsvExporter;

$exporter = new CsvExporter(
    [
        'query' => Item::find()->orderBy('id'),
        'batchSize' => 200, // export batch size
    ],
);

$exporter->export()->saveAs('/path/to/file.csv');
```

## Columns, serial numbers and a footer

```php
<?php

use yii2\extensions\csvexport\CsvExporter;
use yii2\extensions\csvexport\SerialColumn;
use yii\data\ArrayDataProvider;

$exporter = new CsvExporter(
    [
        'dataProvider' => new ArrayDataProvider([
            'allModels' => [
                ['name' => 'a', 'price' => 5],
            ],
        ]),
        'showFooter' => true,
        'columns' => [
            ['class' => SerialColumn::class],
            'name',
            [
                'attribute' => 'price',
                'header' => 'Price (USD)',
                'footer' => 'Total',
                'value' => static fn (array $model): string => number_format($model['price'], 2),
            ],
        ],
    ],
);

$exporter->export()->saveAs('/path/to/file.csv');
```

The file contains three records:

```text
"#","Name","Price (USD)"
"1","a","5.00"
"","","Total"
```

## Send a download from a controller

`send()` returns the Yii web response, sets the MIME type from the result and removes the temporary files after the
response is sent. It is not available in console applications.

```php
<?php

use yii2\extensions\csvexport\CsvExporter;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\Response;

class ItemController extends Controller
{
    public function actionExport(): Response
    {
        $exporter = new CsvExporter(
            [
                'dataProvider' => new ActiveDataProvider([
                    'query' => Item::find()->orderBy('id'),
                ]),
            ],
        );

        return $exporter->export()->send('items.csv');
    }
}
```

There is no need to check whether the result is archived. The extension of the result is appended when the name does not
end with it, so an archived export is offered as `items.csv.zip`.

## Split the result into several files

Spreadsheet programs limit the rows of a file: 65536 in 'Open Office' and 'MS Excel 97-2003', 1048576 in 'MS Excel
2007'. `maxEntriesPerFile` restricts the rows of each file, and several files are delivered as one archive.

```php
<?php

use yii2\extensions\csvexport\CsvExporter;

$exporter = new CsvExporter(
    [
        'query' => Item::find()->orderBy('id'),
        'maxEntriesPerFile' => 60000, // limit max rows per single file
        'resultConfig' => ['forceArchive' => true], // archive even when the rows fit in one file
    ],
);

$exporter->export()->saveAs('/path/to/archive-file.zip'); // output ZIP archive!
```

To process the files yourself, iterate over `ExportResult::$csvFiles` while the result object is alive:

```php
<?php

use yii2\extensions\csvexport\CsvExporter;

$exporter = new CsvExporter(
    [
        'query' => Item::find()->orderBy('id'),
        'maxEntriesPerFile' => 60000,
    ],
);

$result = $exporter->export();

foreach ($result->csvFiles as $csvFile) {
    copy($csvFile->name, '/path/to/dir/' . basename($csvFile->name));
}
```

## Always archive, or use another archive format

`forceArchive` archives a single file too.

```php
<?php

use yii2\extensions\csvexport\CsvExporter;

$exporter = new CsvExporter(
    [
        'query' => Item::find()->orderBy('id'),
        'resultConfig' => [
            'forceArchive' => true, // always archive the results
        ],
    ],
);

$exporter->export()->saveAs('/path/to/archive-file.zip');
```

A custom archiver receives the CSV paths and the private directory, and returns the archive it created there:

```php
<?php

use yii2\extensions\csvexport\CsvExporter;

$exporter = new CsvExporter(
    [
        'query' => Item::find()->orderBy('id'),
        'resultConfig' => [
            'forceArchive' => true,
            'archiver' => static function (array $files, string $dirName): string {
                $archive = $dirName . DIRECTORY_SEPARATOR . 'items.tar';

                $tar = new PharData($archive);

                foreach ($files as $file) {
                    $tar->addFile($file, basename($file));
                }

                return $archive;
            },
        ],
    ],
);

$exporter->export()->saveAs('/path/to/items.tar');
```

## Tab-separated values

```php
<?php

use yii2\extensions\csvexport\CsvExporter;

$exporter = new CsvExporter(
    [
        'query' => Item::find()->orderBy('id'),
        'csvFileConfig' => [
            'cellDelimiter' => "\t",
            'rowDelimiter' => "\n",
            'enclosure' => '',
        ],
    ],
);

$exporter->export()->saveAs('/path/to/file.txt');
```

Without an enclosure the export fails when a value contains a tab or a line break.

## Spreadsheet import with a BOM

```php
<?php

use yii2\extensions\csvexport\CsvExporter;

$exporter = new CsvExporter(
    [
        'query' => Item::find()->orderBy('id'),
        'csvFileConfig' => [
            'writeBom' => true,
            'spreadsheetSafe' => true,
        ],
    ],
);

$exporter->export()->saveAs('/path/to/file.csv');
```

## Saving and retrying

`saveAs()` stages the completed file beside the destination and then publishes it. It returns `false` when delivery
fails and leaves the complete source in place, so the same result can be saved again. Pass `false` as the second
argument to keep the temporary files after a successful save.

A destination directory that cannot be created, resolved or used for staging throws `yii\base\Exception`, and a
destination inside the private workspace throws `yii\base\InvalidConfigException`. Nothing is published in either case
and the source stays in place. The example below handles only the `false` result.

```php
$result = $exporter->export();

if (!$result->saveAs('/path/to/file.csv')) {
    $result->saveAs('/another/path/file.csv');
}
```

## Clean up interrupted exports

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

$removed = ExportResult::purgeExpired('@runtime/csv-export', 86400);
```

[Back to documentation](/docs/extensions/csv-export/index.md#documentation)