【问题标题】:Import excel file to database using Laravel使用 Laravel 将 excel 文件导入数据库
【发布时间】:2021-06-23 07:54:27
【问题描述】:

为什么在使用 laravel 将 excel 文件导入数据库时​​得到未定义的偏移量。

UserImport.php

public function model(array $row)
{
    var_dump($row);
    
    return new User([
        'name' =>$row[0],
        'email'=>$row[1],
        'password' => Hash::make('password'),

    ]);
}

UserImportController

public function store(Request $request){

    $file = $request->file('file');
    Excel::import(new UsersImport, $file);
    return back()->withStatus('Successfully');
}

上传excel文件时,这样显示。 enter image description here

我使用 var_dump() 来查看数组。我在 excel 文件中输入了 4 行。但显示5个数组数据。为什么??? (显示在输入的图像中。 )

【问题讨论】:

    标签: excel laravel excel-import


    【解决方案1】:

    我相信这是因为文件末尾的新行。

    您应该检查它是否只包含一个新行并跳过导入。

    【讨论】:

    • 我在 UserImport.php 中添加了 if 条件 if($row[0] !=""){ return new User([ 'name' =>$row[0], 'email'=> $row[1], 'password' => Hash::make('password'), ]); }
    【解决方案2】:

    为 UserImport.php

    设置 if 条件
    if($row[0] !=""){ 
        return new User([ 
            'name' =>$row[0], 
            'email'=>$row[1], 
            'password' => Hash::make('password'), 
       ]); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      相关资源
      最近更新 更多