新建基礎匯出類
<?php
namespace App\Admin\Extensions\Exports;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Exporters\AbstractExporter;
use Illuminate\Database\Eloquent\Model;
class BaseExport extends AbstractExporter
{
public function __construct(Grid $grid = null)
{
parent::__construct($grid);
}
protected $fileName;
protected $headings = [];
protected $columns = ['*'];
public function query()
{
if (!empty($this->columns)) {
return $this->getQuery()->select($this->columns);
}
return $this->getQuery();
}
public function export()
{
$this->csv($this->fileName,$this->headings,$this->query());
}
public function map(Model $model){
return [];
}
protected function csv($sFileName,Array $aTitle, $oQuery)
{
set_time_limit(0);
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'. $sFileName .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$fp = fopen('php://output', 'a');
fwrite($fp, "\xEF\xBB\xBF");
fputcsv($fp, $aTitle);
$perSize = 10000;
$oQuery->chunkById($perSize,function ($collection) use($fp){
foreach($collection as $obj) {
$rowData = $this->map($obj);
fputcsv($fp, $rowData);
}
unset($oCollection);
if (ob_get_level() > 0) {
ob_flush();
}
});
fclose($fp);
exit();
}
}
建立匯出類
<?php
namespace App\Admin\Extensions\Exports;
use Illuminate\Database\Eloquent\Model;
class UserExport extends BaseExport
{
public $fileName = 'test.csv';
public $headings = [
'ID','使用者名稱','建立時間','使用者角色'
];
public $columns = [
'id', 'username', 'created_at', 'role_id'
];
public function map(Model $model)
{
return [
$model->id,
$model->username,
$model->created_at,
data_get($model,'role.name','')
];
}
在laravel-admin 控制器中 使用
protected function grid()
{
$grid = new Grid(new Application);
$grid->exporter(new UserExport());
}
已釋出成 composer summer-wind 包 ,歡迎下載使用
本作品採用《CC 協議》,轉載必須註明作者和本文連結