---
name: yii2-csv-export
description: Use when exporting Yii2 data providers or queries to CSV through yii2-extensions/csv-export - batching, columns, CSV dialect, spreadsheet policy, archiving, delivery and workspace cleanup. Not for importing or parsing CSV, for XLSX or other spreadsheet formats, or for code that still uses the legacy yii2tech\csvgrid namespace.
license: BSD-3-Clause
---

# Export Yii2 data through CSV Export

The Composer identity is `yii2-extensions/csv-export` and the namespace is `yii2\extensions\csvexport`, in the Yii2
Extensions checkout. Moving from `yii2tech/csv-grid` is a breaking migration: there are no legacy class aliases and no
Composer `replace`. Check PHP >=8.3 and the installed Yii 2.0 or 22 revision against composer.json.

## Inspect the installation

Resolve the actual package path and Composer-selected revision; compare current files and the lockfile. Read README and
the six classes in `src/` at that revision. A copied skill need not have the package beside it. If matching guides are
absent, use the installed source and state the limitation. Do not change dependencies merely to make an example pass.

## Configure export and ownership

Create `CsvExporter` with a data provider or query and explicit columns. `csvFileConfig` configures every `CsvFile` the
export creates (`cellDelimiter`, `enclosure`, `rowDelimiter`, `encoding`, `writeBom`, `spreadsheetSafe`), and
`resultConfig` configures its `ExportResult` (`basePath`, `fileBaseName`, `forceArchive`, `archiver`). An explicitly
configured provider takes precedence. Data-provider pagination controls export batches; disabling pagination removes
that batching. Query exports use `batch()` when available; inspect the fallback provider and `batchSize`. A bounded
batch size does not make an already materialized ArrayDataProvider memory-free.

Column `value`, formatter and CSV settings are distinct. Verify null, Unicode, delimiter, quote and line-break output
against the actual CsvFile implementation. CSV quoting is not spreadsheet-formula sanitization; apply an explicit
application policy for untrusted cells before delivery. The opted-in `spreadsheetSafe` policy changes formula-like text
but preserves genuine numeric values. Check output with the target importer.

Subclass `Column` for a custom column and override its `renderDataCellContent()`, `renderHeaderCellContent()` or
`renderFooterCellContent()`; a configured column class that does not extend `Column` throws `InvalidConfigException`.
`CsvFile` also works on its own: set `name`, call `writeRow()` (it opens the file) and `close()`; the closed-file rules
below apply, and a standalone file survives destruction.

`export()` returns `ExportResult`. `saveAs()` moves by default and can copy when its deletion flag is false. `send()`
prepares a web response and schedules temporary cleanup after sending; it is not a CLI export method. The result's
destructor removes its private workspace. Use a trusted runtime parent and an authorized destination. A failed move
leaves the source available for retry. Call `purgeExpired()` for expired, unlocked workspaces. Do not expose arbitrary
paths from user input.

## Intended behavior, not bugs

These contracts are covered by the package tests. Do not "fix" them in the package or work around them silently.

- Records are joined by `rowDelimiter`; the file has no line break after the last record.
- An empty source still produces one file. With configured columns it holds the header and footer rows that are enabled;
  without a schema it has zero bytes.
- Without `columns`, the schema is inferred from the first row only and each inferred name is literal: the key
  `created:at` is one attribute. Only string entries in `columns` use the `attribute:format:label` shorthand. Configure
  `columns` explicitly when rows differ.
- A `Column` instance in `columns` is cloned for each export, and each export builds its own schema, so a shared
  instance carries no state between exports.
- `DataColumn` formats with `raw` by default. A `null` value renders `nullDisplay` and does not reach the formatter.
- A provider export works on a clone, starts at page zero and ignores request pagination parameters. The caller's
  provider keeps its page, models and keys.
- The row index is global across pages and batches, so `SerialColumn` keeps counting. Columns receive provider keys; a
  `yii\db\Query` without `indexBy()` passes the global row index as the key.
- A query without `batch()` is wrapped in an `ActiveDataProvider` whose page size is `batchSize`.
- `maxEntriesPerFile` counts the header and footer rows. `null` or `0` disables splitting; a limit that cannot fit one
  data row throws `InvalidConfigException`.
- When the result is split, every file starts with the header (when `showHeader` is enabled) and, with `showFooter`,
  ends with the footer.
- `spreadsheetSafe` changes strings only. The string `'-42'` gets an apostrophe prefix, the integer `-42` does not.
  Leading whitespace before a formula character does not bypass the prefix.
- An empty `enclosure` rejects cells containing the delimiter or a line break instead of escaping them.
- `writeBom => true` writes the BOM of `encoding`; a string is written as a literal prefix, and a known BOM must match
  `encoding`.
- A closed `CsvFile` rejects further writes with `LogicException`, and a failed write makes the writer unusable.
  `ExportResult` only accepts closed, complete files that it owns.
- `basePath` (or `dirName`) names the parent. Each result owns a private `export-<32 hex>` child and removes it on
  `delete()`, after `send()` completes and on destruction. Keep the result object alive until delivery finishes.
- `getResultFileName()` returns `null` without files. Several files, or `forceArchive`, yield an archive; a custom
  archiver must return a readable file directly inside the private directory.
- `copy()`, `move()` and `saveAs()` return `false` when there is no result file or when reading its size, copying it or
  the final rename fails; the source stays in place and a retry can succeed. A destination inside the private workspace
  throws `InvalidConfigException`, and a destination parent that cannot be created, resolved or used for staging throws
  `yii\base\Exception`. A missing destination parent is created with mode `0700`.
- `send()` requires a Yii web application, appends the artifact extension (`items.csv` becomes `items.csv.zip` for an
  archive) and rejects names with path separators or control characters.
- `purgeExpired()` skips locked workspaces, workspaces younger than the retention and directories without a lease.

## Verify

Run an isolated export with empty data, multiple batches, nulls, quotes, line breaks and spreadsheet-like values. Read
the saved CSV with an independent parser, assert row/column counts and the chosen safety policy, and verify cleanup
without deleting unrelated files. Separate export correctness from actual browser download delivery and skill
activation.
