微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将日期和时间添加到 Laravel 中的 excel 导出

如何解决将日期和时间添加到 Laravel 中的 excel 导出

我是 Laravel 的新手,我正在制作一个新项目,我将我的学校数据导出到带有 maatwebsite 的电子表格,我给它起了一个标题代码如下:

   public function headings(): array
    {
        return [
            ['Staff Report'],[
                'staffid','name','emailaddress','faculty',]
        ];
    }

我想要完成的是在标题旁边加上日期,所以它应该是 Staff Report-04/05/21

我尝试使用日期时间,但这依赖于 db 中的 created_at 字段...以前有人用过吗?

解决方法

欢迎使用 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)
        ];
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。