数据导出之: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 App\Models\CompanyBid;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class UserExport implements FromCollection, WithHeadings, WithMapping, WithStyles
{
public $params;
public function __construct($params = [])
{
$this->params = $params;
}
/**
* 配置
*/
public array $config = [
['column' => 'A', 'field' => 'id', 'name' => 'ID', 'width' => 15],
['column' => 'B', 'field' => 'nickname', 'name' => '昵称', 'width' => 20],
['column' => 'C', 'field' => 'username', 'name' => '用户名', 'width' => 20],
['column' => 'D', 'field' => 'id_card', 'name' => '身份证号', 'width' => 30],
['column' => 'E', 'field' => 'email', 'name' => 'Email', 'width' => 20],
['column' => 'F', 'field' => 'phone', 'name' => '手机号', 'width' => 20],
['column' => 'G', 'field' => 'area', 'name' => '区域', 'width' => 15],
['column' => 'H', 'field' => 'province', 'name' => '省份', 'width' => 15],
];
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
$select = [
'*',
];
//根据 $params 组装查询条件
$where = [];
$res = CompanyBid::query()->where($where)->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;
}
// dd($row->toArray(), $values);
return $values;
}
/**
* 样式
*/
public function styles(Worksheet $sheet)
{
foreach ($this->config as $key => $val) {
$sheet->getColumnDimension($val['column'])->setWidth($val['width']);
$sheet->getRowDimension($key)->setRowHeight(20);
}
}
}
导出业务 Controller 调用:
return Excel::download(new UserExport($params), '用户导出.xlsx');
备注
几年前写过一个简要说明:博客:新版 Laravel Excel maatwebsite/excel 3.* 使用说明
官网文档:docs.laravel-excel.com/3.1/getting...
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: