数据导出之:Laravel Excel
写在前面
写过无数次的代码,过了几年还得看手册的无奈。希望以后再也不写代码。。。
Laravel Excel:maatwebsite/excel:^3.1
# 安装指定版本版本
composer require maatwebsite/excel:^3.1.31
# 如果出现依赖报错,在确认无误后直接强制安装
# 参数:--update-with-dependencies
composer require maatwebsite/excel:^3.1.31 --update-with-dependencies
导出
命令生成核心导出类,文件路径 app/Exports:
php artisan make:export UserExport
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class DemoExport implements FromCollection, WithHeadings, WithMapping, WithStyles
{
const FILE_NAME = '测试数据导出.xlsx';
public array $sheetColumn = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z',
];
public mixed $params;
public int $total;
public function __construct($params = [])
{
$this->params = $params;
$this->_initConfig();
}
/**
* 配置
*/
public array $config = [
['column' => 'A', 'field' => 'id', 'name' => 'ID', 'width' => 15],
['column' => 'B', 'field' => 'nickname', 'name' => '昵称', 'width' => 20],
['column' => 'C', 'field' => 'username', 'name' => '用户名', 'width' => 30],
['column' => 'D', 'field' => 'realname', 'name' => '真实姓名', 'width' => 20],
['column' => 'E', 'field' => 'phone', 'name' => '手机号', 'width' => 40],
];
/**
* 配置初始化
* @return void
*/
public function _initConfig(): void
{
foreach ($this->config as $key => $val) {
$this->config[$key] = array_merge(['column' => $this->sheetColumn[$key]], $val);
}
}
/**
* 获取 model::query()。一般: (new XXXService())->getQuery()
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function query()
{
//return Demo::query();
}
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
$select = [
'*',
];
//根据 $params 组装查询条件
$this->total = $this->query()->count();
$res = $this->query()->select($select)->get();
return $res;
}
/**
* 表头
*/
public function headings(): array
{
return array_column($this->config, 'name');
}
/**
* 列的取值
*/
public function map($row): array
{
$fields = array_column($this->config, 'field');
$values = [];
foreach ($fields as $field) {
$values[] = $row->$field;
}
return $values;
}
/**
* 样式
*/
public function styles(Worksheet $sheet): void
{
foreach ($this->config as $key => $val) {
$sheet->getColumnDimension($val['column'])->setWidth($val['width']);
$sheet->getStyle($val['column'])->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
}
//表头加 1
for ($i = 1; $i <= $this->total + 1; $i++) {
$sheet->getRowDimension($i)->setRowHeight(24);
}
}
}
导出业务门面 use Maatwebsite\Excel\Facades\Excel;
Controller
调用:
return Excel::download(new UserExport($params), '用户导出.xlsx');
备注
写过一个excle导出,还写过一个Laravel Excle简要说明
官网文档:docs.laravel-excel.com/3.1/getting...
本作品采用《CC 协议》,转载必须注明作者和本文链接