将 Laravel 模型导出到 Excel 但将 created_at 列修改为仅日期而非日期时间

Exporting Laravel Model to Excel but with modification of created_at column to only date not datetime

我试图在 return 将其导出到 maatwebsite Excel 之前修改一个集合。我试图修改的列是 created_date 列(laravel 的默认 created_date),因此当导出到 excel 时,我只得到日期而不是日期时间。

我试过了:

namespace App\Exports;

use App\Invoice;
use Maatwebsite\Excel\Concerns\FromCollection;

class InvoicesExport implements FromCollection
{
    public function collection()
    {
        $temp = Invoice::all();
        $len = count($temp);
        for($i=0;$i<$len;$i+=1){
            $temp[$i]->created_at = $temp[$i]->created_at->format('m/d/Y')
        }
        return $temp;
    }
}

在控制器中:

public function export() 
{
    return Excel::download(new InvoicesExport, 'invoices.xlsx');
}

但是,导出时,excel 文件中的结果是,例如:'07/26/2016T00:00:00.000000Z'

我注意到时间变成了零,当我尝试时:

$temp[$i]->created_at = "some random string"

网页 return 中的 laravel 错误表示 Carbon Class 构造函数无法将“一些随机字符串”解析为日期时间。

我怎样才能使导出不使用我在 'created_at' 列中提供的字符串构建日期时间,而只是 return 纯字符串?如果让我们说,我不能修改数据库,所以我不能为这个简单的事情创建额外的列和额外的列太多了,我想。

如果您正在使用 Maatwebsite\Excel 2.1 尝试通过 setColumnFormat($array) 方法格式化列。

如果Maatwebsite\Excel 3.1,尝试使用WithMapping界面。

默认情况下,

created_at 在模型的 $cast 属性 中标记为 'datetime',因此当您设置它时,它会自动转换为日期(使用 Carbon::parse('the value you gave'))

如果您想导出带有某些格式化值的集合,则不应改变原始对象的对象,而应创建新的专用 objects/arrays,既不会干扰模型行为,也不会破坏现有对象。