官方導出文檔
laravel-admin自帶的導出excel會導出與此模型關聯的其他資料。是以參考官方文檔調整代碼
文章表:id,title,user_id
使用者表:id,username
//文章模型關聯使用者
public function user(){
return $this->belongsTo(User::class, 'user_id', 'id');
}
複制
//ExcelExporter.php
<?php
namespace App\Admin\Extensions;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Exporters\AbstractExporter;
use Maatwebsite\Excel\Facades\Excel;
class ExcelExpoter extends AbstractExporter
{
protected $head = [];
protected $body = [];
public function setAttr($head, $body){
$this->head = $head;
$this->body = $body;
}
public function export()
{
Excel::create('Filename', function($excel) {
$excel->sheet('Sheetname', function($sheet) {
// 這段邏輯是從表格資料中取出需要導出的字段
$head = $this->head;
$body = $this->body;
$bodyRows = collect($this->getData())->map(function ($item)use($body) {
foreach ($body as $keyName){
$arr[] = array_get($item, $keyName);
}
return $arr;
});
$rows = collect([$head])->merge($bodyRows);
$sheet->rows($rows);
});
})->export('xls');
}
}
複制
使用方法:
$excel = new ExcelExpoter();
$excel->setAttr(['id', '标題', '作者'], ['id', 'title', 'user.username']);
$grid->exporter($excel);
複制
釋出者:全棧程式員棧長,轉載請注明出處:https://javaforall.cn/112804.html原文連結:https://javaforall.cn