You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

导入Excel时出现transformDateTime参数类型错误的解决办法

Excel导入PHP代码报错及解决方法

导入代码

<?php

namespace App\Imports;
use Carbon\Carbon;
use App\Vch;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;

HeadingRowFormatter::default('none');

class VchImport implements ToModel, WithHeadingRow, WithBatchInserts, WithChunkReading
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */

    private function transformDateTime(string $value, string $format = 'd-m-Y')
    {
        try {
                return Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value))->format($format);
            } 
            catch (\ErrorException $e) 
            {
                return Carbon::createFromFormat($format, $value);
            }
    }
    
    public function model(array $row)
    {
        return new Vch([
            'no_vch' => $row[1],
            'nilai_vch' => $row[2],
            'batch' => $row[3],
            'expired' => $this->transformDateTime($row[4]),
            'nama_penerima' => $row[5],
            'alamat_penerima' => $row[6],
            'status' => $row[7],
        ]);
    }
}

报错信息

执行导入操作时触发类型错误:

App\Imports\VchImport::transformDateTime(): Argument #1 ($value) must be of type string, null given, called in C:\Apache24\htdocs\gmpro-dev\app\Imports\VchImport.php on line 41

调试结果

使用dd($row);输出的行数据(第4项应为日期值):

array:10 [▼
  0 => null
  1 => "CP/WS-GADD/III/23-MR001799"
  2 => 100000
  3 => "0269"
  4 => 45366
  5 => null
  6 => null
  7 => "Beredar"
  8 => null
  9 => null
]

已尝试的无效操作

  • 修改代码逻辑
  • 调整Excel文件内容
  • 修改电脑系统日期格式

解决方案

将Excel文件格式从.xlsx改为.xls即可解决该问题。


内容的提问来源于stack exchange,提问作者ITG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:37:21