0

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,
            \PhpOffice\PhpSpreadsheet\Shared\Date::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 [
        \PhpOffice\PhpSpreadsheet\Shared\Date::stringToExcel($model->date)
    ];
}
2
  • 1
    you can ->selectRaw from eloquent changing the format via SQL query. If i've understood the question Commented May 10, 2023 at 13:23
  • Yes this is what's currently being used and it's working, but some people preferred to try the package's built-in methods (No idea why if the raw query + format works..) Commented May 10, 2023 at 17:44

1 Answer 1

0

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;
        });
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.