Martin Carlin

Laravel Excel - Format Columns

Reading time: Only a minute

If you are using Laravel Excel to generate a template (i.e. a file with a header row and no other content), then you might find it tricky if you are looking to format all cells in each of the columns.

This is because the formatting is only applied to exported rows, which in this use case is only the header, so only the first row would have the formatting applied and all other cells would be General formatted.

In my situation, I wanted all columns to be Text to avoid dealing with dates in Excel and any other funny business, basically, what is in the template when it is uploaded is what will be imported.

At first, I had:

use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;

class MyClass implements WithColumnFormatting
{

    public function columnFormats(): array
    {
        $lastColumn = Coordinate::stringFromColumnIndex(count($this->headings()));

        return [
        	'A1:' . $lastColumn . '1000' => NumberFormat::FORMAT_TEXT,
        ]
    }

}

The downside to this approach is hardcoding the number of rows you want to be formatted, 1000 in this case. This obviously isn't ideal as no doubt there would come a time when more rows are imported that have been formatted.

The solution is to replace the above with:

use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class MyClass implements WithStyles
{

    public function styles(Worksheet $sheet): array
    {
        $lastColumn = Coordinate::stringFromColumnIndex(count($this->headings()));

        return [
            "A:$lastColumn" => ['numberFormat' => ['formatCode' => NumberFormat::FORMAT_TEXT]],
        ];
    }

}