ActiveQuery
resultsNote: To write the Excel file, we use the excellent PHPExcel package.php
Here's a quick example to get you started:git
<?php $file = \Yii::createObject([ 'class' => 'codemix\excelexport\ExcelFile', 'sheets' => [ 'Users' => [ 'class' => 'codemix\excelexport\ActiveExcelSheet', 'query' => User::find(), ] ] ]); $file->send('user.xlsx');
Install the package with composer:github
composer require codemix/yii2-excelexport *
For now we only provide some usage examples instead of a full documentation.yii2
ActiveQuery resultscomposer
<?php $file = \Yii::createObject([ 'class' => 'codemix\excelexport\ExcelFile', // Default writer is `\PHPExcel_Writer_Excel2007`. You can use any other writer available from PHPOffice. //'writer' => '\PHPExcel_Writer_Excel5', 'sheets' => [ 'Active Users' => [ 'class' => 'codemix\excelexport\ActiveExcelSheet', 'query' => User::find()->where(['active' => true]), // If not specified, all attributes from `User::attributes()` are used 'attributes' => [ 'id', 'name', 'email', 'team.name', // Related attribute 'created_at', ], // If not specified, the label from the respective record is used. // You can also override single titles, like here for the above `team.name` 'titles' => [ 'D' => 'Team Name', ], // 'formats' and 'formatters' are autogenerated for `ActiveExcelSheet`. // For example if `created_at` is a `DATETIME` column in the DB, the // column will be formatted as a date. You could still override formats // here though, for example if you save a timestamp as INT. See the // raw data example below. ], ], ]); $file->send('demo.xlsx');
Raw datadom
<?php $file = \Yii::createObject([ 'class' => 'codemix\excelexport\ExcelFile', 'sheets' => [ // Array keys are used as Sheet names in the final excel file 'Result per Country' => [ 'data' => [ ['fr', 'France', 1.234, '2014-02-03 12:13:14'], ['de', 'Germany', 2.345, '2014-02-05 19:18:39'], ['uk', 'United Kingdom', 3.456, '2014-03-03 16:09:04'], ], // Set to `false` to suppress the title row 'titles' => [ 'Code', 'Name', 'Volume', 'Created At', ], // Excel format strings 'formats' => [ 'C' => '#,##0.00', // Instead of column names, the 0-based column index can be also used 3 => 'dd/mm/yyyy hh:mm:ss', ], // You'll usually only need this for date columns 'formatters' => [ // Dates and datetimes must be converted to Excel format 3 => function ($value, $row, $data) { return \PHPExcel_Shared_Date::PHPToExcel(strtotime($value)); }, ], ], 'Countries' => [ // Data for another sheet goes here ... ], ] ]); // Save on disk $file->saveAs('/tmp/export.xlsx');
Query builder resultsyii
<?php $file = \Yii::createObject([ 'class' => 'codemix\excelexport\ExcelFile', 'sheets' => [ 'Users' => [ 'data' => new (\yii\db\Query) ->select(['id','name','email']) ->from('user') ->each(100); 'titles' => ['ID', 'Name', 'Email'], ], ] ]); $file->send('demo.xlsx');