model-grid
内置的导出功能只是实现了简单的csv格式文件的导出,如果遇到文件编码问题或者满足不了自己需求的情况,可以按照下面的步骤来自定义导出功能
Laravel-admin1.5.*教程点击跳转:https://blog.csdn.net/qq175023117/article/details/80681533
Laravel-admin1.6.*教程点击跳转:https://blog.csdn.net/qq175023117/article/details/86133101
参考laravel-admin文档来进行扩展的方法:http://laravel-admin.org/docs/zh/model-grid-export
首先安装好它:
composer require maatwebsite/excel:~2.1.0
在config/app.php中的providers中添加: \Maatwebsite\Excel\ExcelServiceProvider::class,
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
创建扩展文件、比如app/Admin/Extensions/ExcelExpoter.php
:
<?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);
}
如案例不详细,可查看我开源项目源码:https://github.com/WXiangQian/stationery-cms
喜欢的可以给个star