Its been more than 2 years to the question but i will still answer it as it may be helpful. I have just added 1 title row but one can add any amount of rows needed. I have attached a screenshot below as how the export looks like.
<?php
namespace App\Exports;
use App\Models\Member;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
class MembersExport implements WithEvents, WithMapping, FromCollection, WithCustomStartCell, ShouldAutoSize, WithHeadings, WithStyles {
protected $index = 0;
public function registerEvents(): array {
return [
AfterSheet::class => function(AfterSheet $event) {
$sheet = $event->sheet;
$sheet->mergeCells('B2:H2');
$sheet->setCellValue('B2', "Members list.");
$styleArray = [
'font' => [
'size' => '20px',
'bold' => true,
],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
],
];
$cellRange = 'B2:H2';
$event->sheet->getDelegate()->getStyle($cellRange)->applyFromArray($styleArray);
},
];
}
public function startCell(): string {
return 'B3';
}
/**
* @return Collection
*/
public function collection(): Collection {
return Member::query()->select(['first_name', 'middle_name', 'last_name', 'gender', 'address', 'mobile'])->get();
}
public function prepareRows($rows): Collection
{
$rows = collect($rows);
return $rows->transform(function ($member) {
$member->gender = $member->gender == 'M' ? 'Male' : 'Female';
return $member;
});
}
public function map($row): array
{
// $fields = [
// ++$this->index,
// $row->first_name,
// $row->middle_name,
// $row->last_name,
// $row->gender,
// $row->address,
// $row->mobile,
// ];
// return $fields;
return array_merge(['srno' => ++$this->index], $row->toArray());
}
public function headings(): array {
return [
'Sr No',
'First Name',
'Middle Name',
'Last Name',
'Gender',
'Address',
'Contact',
];
}
public function styles(Worksheet $sheet) {
$styleArray = [
'font' => [
'bold' => true,
],
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
],
],
'fill' => [
'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
'color' => ['rgb' => 'b6c2d4']
],
];
$sheet->getStyle('B3:H3')->applyFromArray($styleArray);
$sheet->getStyle('B')->getAlignment()->setHorizontal('center');
$sheet->getStyle('H')->getAlignment()->setHorizontal('left');
}
}
