Skip to content

Instantly share code, notes, and snippets.

@ctf0
Last active November 8, 2020 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctf0/cb2f7762c5ab38691e3c2435dcaa64c6 to your computer and use it in GitHub Desktop.
Save ctf0/cb2f7762c5ab38691e3c2435dcaa64c6 to your computer and use it in GitHub Desktop.
<?php
namespace App\Exports;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\BeforeExport;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
class BaseExport implements
WithStrictNullComparison,
WithMapping,
WithHeadings,
ShouldAutoSize,
WithEvents
{
use Exportable;
public function map($model): array
{
return [];
}
public function headings(): array
{
return [];
}
protected function beforeExport()
{
return [
BeforeExport::class => function (BeforeExport $event) {
$writer = $event->writer;
$writer->getDelegate()->getProperties()->setCreator(config('app.name'));
},
];
}
// https://i.stack.imgur.com/5llwN.png
// https://docs.laravel-excel.com/3.1/exports/extending.html
// https://phpspreadsheet.readthedocs.io/en/latest/topics/recipes/#setting-a-spreadsheets-metadata
// Vertical columns are numbered with alphabetic values such as A, B, C. Horizontal rows are numbered with numeric values such as 1, 2, 3.
protected function afterExport()
{
return [
AfterSheet::class => function (AfterSheet $event) {
$sheet = $event->sheet->getDelegate();
$sheet->getRowDimension(1)->setRowHeight(30);
// header row only
$header = $sheet->getStyle('A1:' . $sheet->getHighestDataColumn() . '1');
$this->defaultStyles($header);
$header->getFont()->setBold(true);
$header->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$header->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
// from second row to the end
$other = $sheet->getStyle('A2:' . $sheet->getHighestDataColumn() . $sheet->getHighestRow());
$this->defaultStyles($other);
},
];
}
protected function defaultStyles($item)
{
$item->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$item->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
$item->getAlignment()->setWrapText(true);
return $item;
}
public function registerEvents(): array
{
return array_merge($this->beforeExport(), $this->afterExport());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment