simedkom/app/Exports/NewsExport.php
2025-04-16 09:00:51 +07:00

106 lines
3.2 KiB
PHP

<?php
namespace App\Exports;
use App\Models\News;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class NewsExport implements FromCollection, WithHeadings, WithStyles, WithMapping
{
/**
* @return \Illuminate\Support\Collection
*/
protected $no = 1;
protected $category;
protected $year;
protected $month;
protected $date;
public function __construct($category, $year, $month, $date)
{
$this->category = $category;
$this->year = $year;
$this->month = $month;
$this->date = $date;
}
public function collection()
{
$query = News::query();
if($this->category !== 'all'){
if($this->category === 'news'){
$query->where('category', '0');
}else if($this->category === 'announcement'){
$query->where('category', '1');
}
}
if ($this->year) {
$query->whereYear('created_at', $this->year);
}
if ($this->month) {
$monthYear = Carbon::parse($this->month);
$query->whereYear('created_at', $monthYear->year)
->whereMonth('created_at', $monthYear->month);
}
if ($this->date) {
$query->whereDate('created_at', $this->date);
}
return $query->get();
}
public function map($news): array
{
return [
$this->no++,
$news->title,
$news->link ?? 'Tidak ada',
$news->tag ?? 'Tidak ada',
$news->category === '0' ? 'Berita' : 'Pengumuman',
$news->views == '0'? '0' : $news->views,
Carbon::parse($news->created_at)->locale('id')->translatedFormat('l, d F Y'),
$news->author->name,
];
}
public function headings(): array
{
return [
['Data Berita', '', '', '', '', '', '', ''],
['NO', 'Judul', 'Link', 'Tag', 'Kategori', 'Dilihat', 'Dibuat Pada', 'Dibuat Oleh']
];
}
public function styles(Worksheet $sheet)
{
$sheet->mergeCells('A1:D1'); // A1 sampai D1 digabung
// Set alignment untuk pusat horizontal dan vertikal
$sheet->getStyle('A1:H1')->getAlignment()->setHorizontal('center');
$sheet->getStyle('A1:H1')->getAlignment()->setVertical('center');
$sheet->getColumnDimension('A')->setAutoSize(true);
$sheet->getColumnDimension('B')->setAutoSize(true);
$sheet->getColumnDimension('C')->setAutoSize(true);
$sheet->getColumnDimension('D')->setAutoSize(true);
$sheet->getColumnDimension('E')->setAutoSize(true);
$sheet->getColumnDimension('F')->setAutoSize(true);
$sheet->getColumnDimension('G')->setAutoSize(true);
$sheet->getColumnDimension('H')->setAutoSize(true);
// Menambahkan gaya lain jika diperlukan
$sheet->getStyle('A1:H1')->getFont()->setBold(true);
$sheet->getStyle('A1:H1')->getFont()->setSize(14);
}
}