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