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.
63 lines
1.6 KiB
63 lines
1.6 KiB
<?php
|
|
|
|
namespace App\Exports;
|
|
|
|
use App\Models\CustomFormField;
|
|
use Illuminate\Support\Collection;
|
|
use Maatwebsite\Excel\Concerns\FromCollection;
|
|
|
|
class BaseFormExport implements FromCollection
|
|
{
|
|
public $fields;
|
|
public $data;
|
|
|
|
public function __construct($exportFields, $data)
|
|
{
|
|
$this->fields = $this->checkFields($exportFields);
|
|
$this->data = $data;
|
|
}
|
|
|
|
|
|
/**
|
|
* 检测导出字段合法性
|
|
* @param array $exportFields
|
|
* @return array|mixed
|
|
*/
|
|
public function checkFields($exportFields = [])
|
|
{
|
|
// 获取所有数据表字段
|
|
$table_name = request('table_name');
|
|
$rowTableFields = (new CustomFormField())->getRowTableFieldsByComment($table_name);
|
|
// 获取交集,则是需要导出的字段
|
|
if (!empty($exportFields)) {
|
|
foreach ($rowTableFields as $key => $item) {
|
|
if (!in_array($key, $exportFields)) {
|
|
unset($rowTableFields[$key]);
|
|
}
|
|
}
|
|
}
|
|
return $rowTableFields;
|
|
}
|
|
|
|
//数组转集合
|
|
public function collection()
|
|
{
|
|
return new Collection($this->createData());
|
|
}
|
|
|
|
//业务代码
|
|
public function createData()
|
|
{
|
|
// 表头
|
|
$header = array_values($this->fields);
|
|
$newList = [];
|
|
foreach ($this->data as $key => $info) {
|
|
foreach ($this->fields as $k => $v) {
|
|
$newList[$key][$k] = ($info->$k) ?? '';
|
|
}
|
|
}
|
|
array_unshift($newList, $header); //插入表头
|
|
return $newList;
|
|
}
|
|
}
|