Revision #226 has been created by rackycz on Aug 21, 2020, 6:43:15 PM with the memo:
Export to CSV
« previous (#225) next (#227) »
Changes
Title
unchanged
Yii v2 snippet guide
Category
unchanged
Tutorials
Yii version
unchanged
2.0
Tags
unchanged
tutorial,beginner,yii2
Content
changed
[...]
$pdf->Cell(20, 10, 'ABC123', $displayBorders, 0, 'L', false);
$pdf->Output('D', 'hello.pdf');
```
Note to tFPFD: Once you use it, it creates a few PHP and DAT files in folder **unifont**. Delete them before uploading to the internet. They will contain hardcoded paths to fonts and must be recreated.
**Export (not only GridView) to CSV in UTF-8 without extensions **
---
I will describe how to easily export GridView into CSV so that filers and sorting is kept. I do not use any extentions which are so famous today.
Note that GridView is not needed, I just want to show the most complicated situation.
Let's say you have page on URL user/index and it contains GridView where you can list and filter users.
> Note: In class yii\data\Sort, in method getAttributeOrders(), is the sorting parameter takem from Yii::$app->getRequest() so the name of the sorted column must be in the URL you are using at the moment. This is why sorting might not work if you want to run UserSearch->search() manually without any GET parameters available in Yii::$app->request->queryParams.
The basic method for exporting DataProvider is here:
```php
public function exportDataProviderToCsv($dataProvider) {
// Setting infinite number of rows per page to receive all pages at once
$dataProvider->pagination->pageSize = -1;
// All text-rows will be placed in this array.
// We will later use implode() to insert separators and join everything into 1 large string
$rows = [];
// UTF-8 header = chr(0xEF) . chr(0xBB) . chr(0xBF)
// Plus column names in format:
// ID;Username;Email etc based on your column names
$rows [] = chr(0xEF) . chr(0xBB) . chr(0xBF) . Invoice::getCsvHeader();
foreach ($dataProvider->models as $m) {
// Method getCsvRow() returns CSV row with values. Example:
// 1;petergreen;peter.green@gmail.com ...
$row = trim($m->getCsvRow());
if ($row!='') {
$rows[] = $row;
}
}
// Here we use implode("\n",$rows) to create large string with rows separated by new lines.
// Double quotes must be used around \n !
$csv = implode("\n", $rows);
$currentDate = date('Y-m-d_H-i-s');
return \Yii::$app->response->sendContentAsFile($csv, 'invoices_' . $currentDate . '.csv', [
'mimeType' => 'application/csv',
'inline' => false
]);
}
```
If you want o use it to export data from your GridView, modify your action like this:
```php
public function actionIndex($exportToCsv=false) {
// These 2 rows already existed
$searchModel = new InvoiceSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams)
if ($exportToCsv) {
$this->exportDataProviderToCsv($dataProvider);
return;
}
// ...
}
```
And right above your GridView place this link:
```php
<?php
$csvUrl = \yii\helpers\Url::current(['exportToCsv'=>1]);
echo Html::a('Export', $csvUrl, ['class' => 'btn btn-info', 'target'=>'_blank']);
?>
```
In my code above are there were used 2 methods in the model which export things to the CSV format. My implementatino is here:
```php
public static function getCsvHeader() {
$result = [];
$result[] = "ID";
$result[] = "Username";
$result[] = "Email";
// ...
return implode(";", $result);
}
public function getCsvRow() {
$result = [];
$result[] = $this->id;
$result[] = $this->username;
$result[] = $this->email;
// ...
return implode(";", $result);
}
```