skip to Main Content

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


  1. 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

    class ModelExcelExport implements FromCollection, WithColumnFormatting, withMapping
    {
        public function collection()
        {
            return Model::select('id','email','date')->get()->map(function($item) {
                 $item->date = $item->format('dmY'); // formatting date using Carbon
    
                 return $item;
            });
        }
    }
    
    Login or Signup to reply.
  2. Try this maybe it will helpful for you

    public function query()
    {
        return Model::query()->select('id', 'email', 'date');
    }
    
    public function columnFormats(): array
    {
        return [
            'C' => NumberFormat::FORMAT_DATE_DDMMYYYY,
        ];
    }
    
    public function map($model): array
    {
        return [
            $model->id,
            $model->email,
            $model->date,
        ];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search