Laravel导入exl数据

文章描述:

laravel8导入exl数据到数据库中

1、使用composer命令创建Excle导入模型,文件位置app/Exports/UsersImport.php

php artisan make:import UsersImport --model=User

app/Imports/UsersImport.php

<?php

namespace App\Imports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
class UsersImport implements ToModel, WithStartRow
{

    public function model(array $row)
    {
        return new User([
            'name'     => $row[1],
            'email'    => $row[2],
            'password' => $row[3],
        ]);
    }
    /**
     * 从第几行开始处理数据 就是不处理标题
     * @return int
     */
    public function startRow(): int
    {
        return 2;
    }
}

 

2、user模型,位置app/Models/User.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    use HasFactory;

    protected $table = 'users';
    public $timestamps = false;

    protected $fillable = ['name', 'email','password'];
}

 

3、表单

<div>
    <form action="{{route('import')}}" method="post" enctype="multipart/form-data">
        @csrf
        <input type="file" name="users" required/>
        <input type="submit" value="submit" class="px-4 py-2 bg-indigo-500 hover:bg-indigo-700 text-white rounded-md" />
    </form>
</div>

4、控制器方法

use App\Imports\UsersImport;

 

public function import(Request $request){
     Excel::import(new UsersImport,$request->file('users'));
     return redirect('/')->with('success', 'All good!');
}

 

路由

Route::post('user/import',[UserController::class,'import'])->name('import');

 

发布时间:2023/04/07

发表评论