parfum/app/Exports/CategoryExport.php

136 lines
3.7 KiB
PHP

<?php
namespace App\Exports;
use App\Models\Category;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class CategoryExport implements FromCollection, ShouldAutoSize, WithColumnWidths, WithEvents, WithHeadings, WithMapping, WithStyles, WithTitle
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return Category::all();
}
public function title(): string
{
return 'Data Kategori';
}
public function headings(): array
{
return [
'Nama',
'Deskripsi',
'Tanggal Dibuat',
'Tanggal Diperbarui',
];
}
/**
* @param Category $category
*/
public function map($category): array
{
return [
$category->name,
strip_tags($category->description) ?: '-',
formatDateLocalized($category->created_at, 'd/m/Y H:i'),
formatDateLocalized($category->updated_at, 'd/m/Y H:i'),
];
}
public function columnWidths(): array
{
return [
'A' => 20, // Category Name
'B' => 30, // Description
'C' => 18, // Created Date
'D' => 18, // Updated Date
];
}
/**
* @return array
*/
public function styles(Worksheet $sheet)
{
$lastRow = $sheet->getHighestRow();
$lastColumn = $sheet->getHighestColumn();
// Header style
$headerStyle = [
'font' => [
'bold' => true,
'size' => 12,
'color' => ['rgb' => 'FFFFFF'],
],
'fill' => [
'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => '78716C'], // Stone - elegant
],
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER,
],
'borders' => [
'allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['rgb' => '000000'],
],
],
];
// Data rows style
$dataStyle = [
'borders' => [
'allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['rgb' => '000000'],
],
],
'alignment' => [
'vertical' => Alignment::VERTICAL_TOP,
],
];
return [
// Header styling
1 => $headerStyle,
// Data rows styling
'A2:'.$lastColumn.$lastRow => $dataStyle,
];
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
// Auto-size columns with max width
foreach (range('A', 'D') as $column) {
$event->sheet->getColumnDimension($column)->setAutoSize(true);
}
// Set row height for header
$event->sheet->getRowDimension(1)->setRowHeight(25);
},
];
}
}