Laravel Excel Export with Merged Cells and Custom Column Formatting
This article demonstrates how to create a Laravel export class using Maatwebsite\Excel that supports merging cells, custom column formatting, and handling large numeric values, providing a complete PHP implementation with constructor, collection, event registration, and column format methods for generating Excel files.
This guide explains how to build a Laravel export class for generating Excel files with merged cells and custom formatting using the Maatwebsite\Excel package.
The core class extends StringValueBinder and implements several concerns such as FromCollection , ShouldAutoSize , WithColumnFormatting , WithCustomValueBinder , WithStrictNullComparison , and WithEvents . It stores the data rows, merge‑cell definitions, column names, and format mappings as private properties.
public function __construct($row = null, $data = null, $mergeCell = null, $columnName = null, $formatNumber = []) { $this->row = $row; $this->data = $data; $this->mergeCell = $mergeCell; $this->columnName = $columnName; $this->formatNumber = $formatNumber; }
The collection() method prepares the data for export, iterating over rows to build a two‑dimensional array that matches the header keys, and returns a Laravel collection.
public function registerEvents(): array { if ($this->mergeCell && $this->columnName) { return [ AfterSheet::class => function(AfterSheet $event) { foreach ($this->columnName as $column) { foreach ($this->mergeCell as $key => $value) { $event->sheet->getDelegate()->mergeCells($column . $key . ':' . $column . $value); } } } ]; } return []; }
The columnFormats() method defines the number format for specified columns to prevent scientific notation for long numbers.
public function columnFormats(): array { $formatNumber = []; foreach ($this->formatNumber as $column) { $formatNumber[$column] = \\PhpOffice\\PhpSpreadsheet\\Style\\NumberFormat::FORMAT_TEXT; } return $formatNumber; }
Finally, the export is triggered with a concise one‑liner:
return Excel::download(new Export($row, $list, $mergeCell, $columnName, $formatNumber), 'fileName');
This implementation enables developers to output richly formatted Excel reports directly from Laravel applications.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.