model-grid
內置的導出功能只是實現了簡單的csv格式文件的導出,若是遇到文件編碼問題或者知足不了本身需求的狀況,能夠按照下面的步驟來自定義導出功能php
Laravel-admin1.5.*教程點擊跳轉:juejin.im/post/5d0c39…laravel
Laravel-admin1.6.*教程點擊跳轉:juejin.im/post/5d0c44…git
參考laravel-admin文檔來進行擴展的方法:laravel-admin.org/docs/zh/mod…github
composer require maatwebsite/excel:~2.1.0
在config/app.php中的providers中添加: \Maatwebsite\Excel\ExcelServiceProvider::class,
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"複製代碼
<?php
namespace App\Admin\Extensions;
use Encore\Admin\Grid\Exporters\AbstractExporter;
use Maatwebsite\Excel\Facades\Excel;
class ExcelExpoter extends AbstractExporter
{
protected $file_name = 'file';
protected $sheet_name = 'sheet';
protected $head = [];
protected $body = [];
public function setAttr($file_name, $sheet_name, $head, $body)
{
$this->file_name = $file_name;
$this->sheet_name = $sheet_name;
$this->head = $head;
$this->body = $body;
}
public function export()
{
Excel::create($this->file_name, function($excel) {
$excel->sheet($this->sheet_name, function($sheet) {
// 這段邏輯是從表格數據中取出須要導出的字段
$body = $this->body;
$bodyRows = collect($this->getData())->map(function ($item) use($body) {
$arr = [];
foreach($body as $value) {
$arr[] = array_get($item, $value);
}
return $arr;
});
$rows = collect([$this->head])->merge($bodyRows);
$sheet->rows($rows);
});
})->export('xls');//.xls .csv ...
}
}複製代碼
use App\Admin\Extensions\ExcelExpoter;
protected function grid()
{
$grid = new Grid(new User);
// 導出
$excel = new ExcelExpoter();
$date = date('Y-m-d H:i:s', time());
$excel->setAttr('員工管理'.$date, '員工管理', ['id','姓名','性別'],['id','name','sex']);
$grid->exporter($excel);
}複製代碼
如案例不詳細,可查看我開源項目源碼:github.com/WXiangQian/…web
喜歡的能夠給個star
bash