<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
class LogExport implements FromCollection,WithHeadings
{
use Exportable;
private $data;
private $headings;
//数据注入
public function __construct($data, $headings)
{
$this->data = $data;
$this->headings = $headings;
}
//实现FromCollection接口
public function collection()
{
//文档这个地方是查询的方法,我移动到了外面,其实是一样的道理
return collect($this->data);
}
//实现WithHeadings接口
public function headings(): array
{
return $this->headings;
}
}
<?php
namespace App\Http\Controllers;
use App\Exports\LogExport;
use App\Services\LogService;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
class LogController extends Controller
{
public function aaa()
{
$fileName = '各事业部登录人数.xlsx';
$data = (new LogService())->exportApiRecord(); //这个我写的service 写了好多逻辑,读出来的数据
return Excel::download(new LogExport($data['data'], $data['headings']), $fileName);
}
}
第二种更加灵活,我是看见了laravel-admin 的代码给我的启发
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
class LogExport implements FromCollection,WithHeadings
{
use Exportable;
private $data;
//数据注入
public function __construct($data)
{
$this->data = $data;
}
protected $columns = [
'id' => 'ID',
'name' => '姓名',
'status' => '状态',
];
//实现FromCollection接口
public function collection()
{
//文档这个地方是查询的方法,我移动到了外面,其实是一样的道理
return collect($this->data);
}
//实现WithHeadings接口
public function headings(): array
{
return $this->columns;
}
}
public function map($user) : array
{
return [
$user->id,
$user->name,
$user->status ? 'yes' : 'no'; // 字段数据替换
];
}
}