sigd/app/Exports/CrfExport.php

106 lines
3.6 KiB
PHP

<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Illuminate\Contracts\View\View;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
class CrfExport implements FromView, WithStyles
{
protected $sector;
protected $crfData;
protected $worksheets;
public function __construct($sector, $crfData, $worksheets)
{
$this->sector = $sector;
$this->crfData = $crfData;
$this->worksheets = $worksheets;
}
public function view(): View
{
return view('modules.reports.crf.report', [
'sector' => $this->sector,
'crfData' => $this->crfData,
'worksheets' => $this->worksheets,
'isExport' => true
]);
}
public function styles(Worksheet $sheet)
{
// Apply styles to the header rows
$tableStartRow = 6;
$tableHeaderRow = $tableStartRow; // + ($this->wsData->ws_header - 1);
$tableEndRow = $sheet->getHighestRow();
$columnStart = 'A';
$columnEnd = $sheet->getHighestColumn();
$sheet->getStyle('A1:A3')->applyFromArray([
'font' => ['bold' => true],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_LEFT],
]);
// Apply table header styles
$sheet->getStyle($columnStart . $tableStartRow . ':' . $columnEnd . $tableHeaderRow)->applyFromArray([
'font' => ['bold' => true],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
]);
// Apply borders to the entire table
$sheet->getStyle($columnStart . $tableStartRow . ':' . $columnEnd . $tableEndRow)->applyFromArray([
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
'color' => ['argb' => 'FF000000'],
],
],
]);
// Set dynamic column styles based on data
foreach ($sheet->getRowIterator() as $row) {
$rowIndex = $row->getRowIndex();
// Skip the header rows
if ($rowIndex >= $tableStartRow && $rowIndex <= $tableHeaderRow) {
continue;
}
foreach ($row->getCellIterator() as $cell) {
$value = $cell->getValue();
$formatCode = NumberFormat::FORMAT_GENERAL;
// Check if value is numeric
if (is_numeric($value)) {
$cell->getStyle()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
// Apply number formatting
// $cell->setValue($value);
$formatCode = floor($value) != $value ? '#,##0.0#' : '#,##0';
$cell->getStyle()->getNumberFormat()->setFormatCode($formatCode);
} else {
$cell->getStyle()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
}
}
}
// Auto-fit columns
foreach (range('A', $sheet->getHighestColumn()) as $col) {
$sheet->getColumnDimension($col)->setAutoSize(true);
}
// // Style footer row
// $sheet->getStyle($columnStart . $tableEndRow . ':' . $columnEnd . $tableEndRow)->applyFromArray([
// 'font' => ['bold' => true],
// 'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT],
// ]);
return [];
}
}