欢迎使用 StackOverflow 和 Laravel。
因此,如果要显示正确的格式,则必须在导出之前映射数据并指定 columnFormats 函数。
为此,您还必须使用 PhpOffice\PhpSpreadsheet\Style\NumberFormat 并使用 PhpOffice\PhpSpreadsheet\Shared\Date。
就我而言,我将导出用户公司的客户。根据您的用例更改代码。
参考。链接 - https://docs.laravel-excel.com/2.1/export/format.html
在 columnFormats 函数下,在我的例子中,您必须指定像 (K) 这样的列标题,并为日期格式指定“NumberFormat::FORMAT_DATE_DDMMYYYY”。
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
class ClientsExport implements FromCollection, WithHeadings, WithMapping, WithColumnFormatting
{
public function __construct()
{
}
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
$user = Auth::user();
return $user->company->clients;
}
public function headings(): array
{
return [
'Name',
'Email',
'Address',
'Country',
'Department',
'Zip',
'Fax',
'Phone',
'Mobile',
'Date'
];
}
public function columnFormats(): array
{
return [
'G' => 0,
'H' => 0,
'I' => '@',
'J' => '@',
'K' => NumberFormat::FORMAT_DATE_DDMMYYYY,
];
}
/**
* @var Client $client
*/
public function map($client): array
{
return [
$client->name,
$client->tax_id,
$client->email,
// other data
$client->fax,
$client->phone,
$client->mobile,
Date::dateTimeToExcel($client->created_at)
];
}
}