CakePHP 4 Export To CSV

CakePHP 4 Export To CSV

This tutorial will show how to export a list of record to .csv file format in CakePHP 4. This function is useful if you want to extract the record into .csv format which can be open using Microsoft Excel. The CakePHP-csvview plugin will be used to generate the .csv file.


Download the plugin from the Github repository using composer:

composer require friendsofcake/cakephp-csvview


Load the plugin using the console:

bin/cake plugin load CsvView


or manually load the plugin using the following code in ...\src\Application.php:

public function bootstrap(): void
{
	$this->addPlugin('CsvView');


File Location: ...\src\Controller\UsersController.php
Let assume that the list to be export is a user table. You need to create a new public function to process the request as shown below (it will export all column and download with file name user.csv):

public function csv()
{
    $this->response = $this->response->withDownload('user.csv');
    $users = $this->Users->find();
    $_serialize = 'users';

    $this->viewBuilder()->setClassName('CsvView.Csv');
    $this->set(compact('users', '_serialize'));
}


Or if you want to add a header to your .csv file, add $_header and $_extract as shown below:

public function csv()
{
    $this->response = $this->response->withDownload('user.csv');
    $users = $this->Users->find();
    $_serialize = 'users';
    $_header = ['ID', 'Name', 'Username', 'Role', 'Created', 'Modified'];
	$_extract = ['id', 'name', 'username', 'role', 'created', 'modified'];

    $this->viewBuilder()->setClassName('CsvView.Csv');
    $this->set(compact('users', '_serialize', '_header', '_extract'));
}


In your index file, create a link/button to download the .csv file:

<?= $this->Html->link('Download CSV', ['action' => 'csv']) ?>


That all. Happy coding :)