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 PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class ClientsExport implements FromCollection, WithHeadings, WithStyles
{
/**
* @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 ["#", "name", "surname", "email", "city", "date", "diagnosis", "stay"];
}
public function styles(Worksheet $sheet)
{
return [
// Style the first row as bold text.
1 => ['font' => ['bold' => true]],
];
}
public function columnFormats(): array
{
return [
'F' => NumberFormat::FORMAT_DATE_DDMMYYYY,
];
}
/**
* @var Client $client
*/
public function map($client): array
{
return [
$client->name,
$client->surname,
$client->email,
// other data
$client->city,
Date::dateTimeToExcel($client->date),
$client->diagnosis,
$client->stay
];
}
}
With F I have indicated the date column.
Can anyone kindly help me?
CodePudding user response:
After checking the source code of the NumberFormat::FORMAT_DATE_DDMMYYYY
it looks like this
const FORMAT_DATE_DDMMYYYY = 'dd/mm/yyyy';
so it looks fine but The problem here is that you format the wrong column so all you need is to format column E
instead of F
like that
public function columnFormats(): array
{
return [
'E' => NumberFormat::FORMAT_DATE_DDMMYYYY,
];
}
public function map($client): array
{
return [
$client->name, // A
$client->surname, // B
$client->email, // C
$client->city, // D
Date::dateTimeToExcel($client->date), // E
$client->diagnosis, // F
$client->stay // G
];
}
CodePudding user response:
You can do this from the Promo side using format:
$client->date->format('d-m-Y')