Export as csv in yii2
- By Preneesh AV --
- 20-May-2018 --
- 48 Comments
We will be using yii2tech/csv-grid extension to export data in csv format.
Installation
The preferred way to install this extension is through composer.
Either run
php composer.phar require --prefer-dist yii2tech/csv-grid
or add
"yii2tech/csv-grid": "*"
to the require section of your composer.json.
Detail usage can be found on github:
https://github.com/yii2tech/csv-grid
Controller :
use yii\data\ActiveDataProvider;
use yii2tech\csvgrid\CsvGrid;
public function actionIndex() {
$query = new Query;
$query->select(' ') /** Your sql query should be here **/
$command = $query->createCommand();
$view = $command->queryall();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$request = Yii::$app->request;
if ($request->isPost) {
$exporter = new CsvGrid([
'dataProvider' => $dataProvider, 'csvFileConfig' => [//formatting csv output
'enclosure' => '',
],
]);
return $exporter->export()->send('file.csv');
}
}
View:
<?= Html::a( '<i class="fa fa-plus" ></i> Export as csv', Url::to(['default/index']),
[ 'data-method' => 'post',
'class'=>'btn btn-wide btn-light-purple pull-right',
'style'=>'margin-right:25px;margin-bottom:10px;', ] ); ?>