I want to format one of the columns which is a date column (as a string) to another format.
The solution I found was to use withMapping
:
class ModelExcelExport implements FromCollection, WithColumnFormatting, withMapping
{
public function collection()
{
return Model::select('id','email','date')->get();
}
public function map($model): array
{
return [
$model->id,
$model->email,
PhpOfficePhpSpreadsheetSharedDate::stringToExcel($model->date),
];
}
public function columnFormats(): array
{
return [
'C' => NumberFormat::FORMAT_DATE_DDMMYYYY,
];
}
}
But for that to work I have to map all of the columns, even if some of them do not need any formatting.
In my case there are many more columns (Not just 3 like in the example) so it’s cumbersome to copy each and every column to the map()
method just because I need a single column (the date
column) to be in another format.
When I only place the date
column in the map()
it will not work:
public function map($model): array
{
return [
PhpOfficePhpSpreadsheetSharedDate::stringToExcel($model->date)
];
}
2
Answers
It might not be the best answer, but in order to map one single column you can do that using laravel built-in collection map method
Try this maybe it will helpful for you