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.
79 lines
1.9 KiB
79 lines
1.9 KiB
<?php
|
|
|
|
namespace App\Exports;
|
|
|
|
use Illuminate\Support\Collection;
|
|
use Maatwebsite\Excel\Concerns\FromCollection;
|
|
use Maatwebsite\Excel\Concerns\WithStyles;
|
|
use Maatwebsite\Excel\Concerns\WithColumnWidths;
|
|
use Maatwebsite\Excel\Concerns\WithEvents;
|
|
use Maatwebsite\Excel\Events\AfterSheet;
|
|
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
|
|
use PhpOffice\PhpSpreadsheet\Style\Alignment;
|
|
|
|
class SheetExport implements FromCollection, WithStyles, WithColumnWidths, WithEvents
|
|
{
|
|
protected $data;
|
|
protected $fields;
|
|
protected $sheetName;
|
|
|
|
public function __construct($data, $fields, $sheetName = 'Sheet1')
|
|
{
|
|
$this->data = $data;
|
|
$this->fields = $fields;
|
|
$this->sheetName = $sheetName;
|
|
}
|
|
|
|
public function collection()
|
|
{
|
|
$newList = [];
|
|
|
|
// 添加表头
|
|
$header = array_values($this->fields);
|
|
$newList[] = $header;
|
|
|
|
// 添加数据行
|
|
foreach ($this->data as $row) {
|
|
$temp = [];
|
|
foreach (array_keys($this->fields) as $field) {
|
|
$temp[] = $row[$field] ?? '';
|
|
}
|
|
$newList[] = $temp;
|
|
}
|
|
|
|
return new Collection($newList);
|
|
}
|
|
|
|
public function styles(Worksheet $sheet)
|
|
{
|
|
return [
|
|
1 => [
|
|
'font' => ['bold' => true],
|
|
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
|
|
],
|
|
];
|
|
}
|
|
|
|
public function columnWidths(): array
|
|
{
|
|
$widths = [];
|
|
$column = 'A';
|
|
foreach ($this->fields as $field) {
|
|
$widths[$column] = 15;
|
|
$column++;
|
|
}
|
|
return $widths;
|
|
}
|
|
|
|
public function registerEvents(): array
|
|
{
|
|
return [
|
|
AfterSheet::class => function (AfterSheet $event) {
|
|
$sheet = $event->sheet->getDelegate();
|
|
$sheet->setTitle($this->sheetName);
|
|
},
|
|
];
|
|
}
|
|
}
|
|
|