Rapport-Laravel/app/Exports/IvaStyledExport.php

103 lines
3.6 KiB
PHP

<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
class IvaStyledExport implements FromArray, WithEvents, ShouldAutoSize
{
protected $data;
protected $merges;
protected $fills;
protected $headerRows;
protected $freeze;
public function __construct(array $payload)
{
$this->data = $payload['data'] ?? [];
$this->merges = $payload['merges'] ?? [];
$this->fills = $payload['fills'] ?? [];
$this->headerRows = (int) ($payload['header_rows'] ?? 1);
$this->freeze = $payload['freeze'] ?? 'A2';
}
public function array(): array
{
return $this->data;
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
$sheet = $event->sheet->getDelegate();
$rowCount = max(1, count($this->data));
$colCount = 1;
foreach ($this->data as $row) {
$colCount = max($colCount, count($row));
}
$lastCol = Coordinate::stringFromColumnIndex($colCount);
$lastCell = $lastCol . $rowCount;
foreach ($this->merges as $range) {
$sheet->mergeCells($range);
}
$sheet->getStyle('A1:' . $lastCell)->applyFromArray([
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER,
'wrapText' => true,
],
'borders' => [
'allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['rgb' => 'B0B0B0'],
],
],
'font' => [
'name' => 'Calibri',
'size' => 11,
],
]);
if ($this->headerRows > 0) {
$headerRange = 'A1:' . $lastCol . $this->headerRows;
$sheet->getStyle($headerRange)->getFont()->setBold(true);
$sheet->getRowDimension(1)->setRowHeight(22);
if ($this->headerRows > 1) {
$sheet->getRowDimension(2)->setRowHeight(30);
}
}
foreach ($this->fills as $range => $fill) {
$sheet->getStyle($range)->applyFromArray([
'font' => [
'bold' => true,
'color' => ['rgb' => $fill['fg'] ?? '000000'],
],
'fill' => [
'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => $fill['bg'] ?? 'FFFFFF'],
],
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER,
'wrapText' => true,
],
]);
}
$sheet->freezePane($this->freeze);
},
];
}
}