</> Code The Pixel

CakePHP 4 Export To CSV

Asyraf Wahi Anuar - May 29, 2020

Estimated reading time: 1 minute, 22 seconds

This tutorial will show how to export a list of records 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 exported is a user table. You need to create a new public function to process the request as shown below (it will export all columns 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 :)


Cite this article (APA 6th Edition)

Popular
CakePHP 4 Print PDF Using CakePDF
May, 17 2020
CakePHP 4 Authentication Using Auth...
May, 14 2020
CakePHP 4 jQuery Date Time Picker
October, 01 2018
CakePHP 4 Export To CSV
May, 29 2020
CakePHP 4 Authentication Using...
May, 11 2020
CakePHP 4 File Upload Using Proffer Plugin
May, 15 2020
CakePHP 4 Find, Sort & Count
June, 02 2020
Share
Sharing Link
Click the icon to share