【问题标题】:Adding date and time to excel export in Laravel在 Laravel 中添加日期和时间以导出 Excel
【发布时间】:2021-05-04 12:43:33
【问题描述】:

我是 Laravel 的新手,我正在创建一个新项目,我正在使用 maatwebsite 将我的学校数据导出到电子表格中,我使用以下代码为其命名:

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

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

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

【问题讨论】:

  • 您想在标题中添加一个日期,您想使用哪个日期?它来自哪里?
  • 我只想要一个实时日期,比如下载时间
  • date("d/m/y") 应该这样做
  • @Maxime 这也有效!!1
  • @guycode12 您作为 cmets 发布的所有描述都应嵌入问题中

标签: php laravel laravel-8 maatwebsite-excel


【解决方案1】:

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

【讨论】:

  • 这行得通!但它将我的逗号转换为小数并将其四舍五入......值的对齐方式也是左右对齐
  • 你说的是另一个字段的日期格式还是数字格式。
  • 另一个字段,我为数据库版本添加了一个字段,例如一条记录在v18.5,另一条记录在v17
  • 尝试 FORMAT_NUMBER_00 而不是 0 并检查。
猜你喜欢
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 2021-02-21
  • 1970-01-01
  • 2021-07-21
相关资源
最近更新 更多