简体   繁体   English

使用 Laravel 将 excel 文件导入数据库

[英]Import excel file to database using Laravel

why get undefined offset when importing excel file to the database using laravel.为什么在使用 laravel 将 excel 文件导入数据库时得到未定义的偏移量。

UserImport.php 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');
}

when uploading the excel file, display it like this.上传 excel 文件时,显示如下。 enter image description here在此处输入图像描述

I used var_dump() to see the array.我使用 var_dump() 查看数组。 I entered 4 rows in the excel file.我在 excel 文件中输入了 4 行。 But display 5 array data.但显示5个数组数据。 Why that???为什么??? (display in entered image. ) (显示在输入的图像中。)

I believe it is because of the new line at the end of the file.我相信这是因为文件末尾的新行。

You should check if it contains only a new line and skip the import.您应该检查它是否只包含一个新行并跳过导入。

set if condition for UserImport.phpUserImport.php设置 if 条件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM