You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.2 KiB

<?php
/**
* 前端自定义的导出类
*/
namespace App\Exports;
use App\Exceptions\ErrorException;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
class BaseFormExport implements FromCollection
{
public $fields;
public $data;
public function __construct($data, $exportFields)
{
// 需要导出的字段。格式:['name'=>'名字','user.sex'=>'性别']
$this->fields = $exportFields;
// 数据
$this->data = $data;
}
/**
* 数组转集合
* @throws ErrorException
*/
public function collection()
{
if (empty($this->fields)) {
throw new ErrorException('导出字段不能为空');
}
if (!is_array($this->fields)) {
throw new ErrorException('导出字段必须是数组');
}
// 获取表头
$header = array_values($this->fields);
// 获取字段指向
$fields = array_keys($this->fields);
$newList = [];
foreach ($this->data as $info) {
$temp = [];
foreach ($fields as $field) {
if ($field == 'idcard') {
$temp[$field] = ' ' . $this->getDotValue($info, $field);
} else {
$temp[$field] = $this->getDotValue($info, $field);
}
}
$newList[] = $temp;
}
array_unshift($newList, $header); //插入表头
return new Collection($newList);
}
/**
* .号转数组层级并返回对应的值
* @param $key
* @param null $default
* @return mixed|null
*/
function getDotValue($config, $key, $default = null)
{
// 如果在第一层,就直接返回
if (isset($config[$key])) {
return $config[$key];
}
// 如果找不到,直接返回默认值
if (false === strpos($key, '.')) {
return $default;
}
// 临时数组
$tempArr = explode('.', $key);
foreach ($tempArr as $segment) {
if (!is_array($config) || !array_key_exists($segment, $config)) {
return $default;
}
$config = $config[$segment];
}
return $config;
}
}