How to use time format excel cell in laravel uploaded excel?

こ雲淡風輕ζ 提交于 2021-01-29 02:53:32

问题


i am using laravel package maatwebsite/excel version 3.1 for excel file upload.

   $collection = Excel::toCollection(new UsersImport, storage_path('app/' . $newFile));

i have uploaded a file where the format of cell is time.

Here time in and time out cell has time format. when i upload this file the resulting output is:

in resulting output time in and time out cells data is converted into string. how to prevent this from converting or how to change this from text to time?


回答1:


You need to manually convert them or use a mapper.

Can use the built in function to convert one of the date as so in the following example:

\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($collection->first()[4])

You can also use Carbon I think

Carbon::parse($collection->first()[4])

If you use a mapper you can define that beforehand and don't worry about it.

https://docs.laravel-excel.com/3.1/imports/mapped-cells.html

namespace App\Imports;

use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithMappedCells;
use PhpOffice\PhpSpreadsheet\Shared\Date;

new Import implements WithMappedCells, ToModel 
{
public function mapping(): array
{
    return [
        'timecellA'  => 'A5',
        'timecellB' => 'A6',
        'timecellC' => 'A7',
        'timecellD' => 'A8',

    ];
}

public function model(array $row)
{
    return [
         'timecellA'  => Date::excelToDateTimeObject($row['timecellA'],
         'timecellB'  => Date::excelToDateTimeObject($row['timecellB'],
         'timecellC'  => Date::excelToDateTimeObject($row['timecellC'],
         'timecellD'  => Date::excelToDateTimeObject($row['timecellD'],
    ];
}
}


来源:https://stackoverflow.com/questions/59048652/how-to-use-time-format-excel-cell-in-laravel-uploaded-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!