4

Laravel Excel: the date is not formatted in the export When I try to export, the date in Excel is shown to me as: YYYY-MM-DD.

What I want to get is the date in the following format: DD/MM/YYYY.

Going into detail, I have the columns shown in the following code; the date column is the one of interest.

This is the code:

<?php

namespace App\Exports;

use App\Models\Client;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithMapping;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class ClientsExport implements FromCollection, WithHeadings, WithStyles, WithMapping, WithColumnFormatting
{
    /**
    * @return \Illuminate\Support\Collection
    */

    public function __construct(private ?\App\Models\Client $client = null)
    {
        $this->client = $client;
    }

    public function collection()
    {
        return is_null($this->client) ? Client::all() : collect([$this->client]);
    }

    public function headings(): array
    {
        return ["#", "Nome", "Cognome", "Email", "Città", "Data", "Diagnosi", "Soggiorno", 'Data creazione','Data modifica'];
    }

    public function styles(Worksheet $sheet)
    {
        return [
        // prima riga con testo in grassetto
        1    => ['font' => ['bold' => true]],
        ];
    }

    public function columnFormats(): array
    {
        return [
            'F' => NumberFormat::FORMAT_DATE_DDMMYYYY,
        ];
    }

    /**
    * @var Client $client
    */
    public function map($client): array
    {
        //dd(Date::dateTimeToExcel($client->date));
        return [
            $client->id,
            $client->name,
            $client->surname,
            $client->email,
            $client->city,
            Date::dateTimeToExcel($client->date),
            $client->diagnosis,
            $client->stay
        ];
    } 

}

With F I have indicated the date column.

Can anyone kindly help me?

Sarah
  • 292
  • 1
  • 10

1 Answers1

-1

You can make manipulate the attribute in model file:

public function getDateAttribute() {
   return $this->attributes['fulldate'] = $this->date->format('Y-m-d');
}
OMi Shah
  • 5,768
  • 3
  • 25
  • 34