函数 Maatwebsite\Excel\Excel::import() 的参数太少,1 个通过,至少 2 个预期

Too few arguments to function Maatwebsite\Excel\Excel::import(), 1 passed and at least 2 expected

我正在尝试将 Excel 数据导入 Laravel 并插入数据库。我正在使用 maatwebsite/excel 版本 3 作曲家包和 laravel 版本 5.8

截图错误: https://imgur.com/a/2KXCE0g

Blade 文件:import.blade.php

           <form action="{{ url('/import-excel/import') }}" method="POST" enctype="multipart/form-data">
                {{ csrf_field() }}
                <div class="form-group">
                    <label for="importFile">Select Import File</label>
                    <input type="file" name="select_file" class="form-controll">
                </div>
                <input type="submit" name="upload" class="btn btn-success" value="Import File">
            </form>

控制器文件:ImportExcelController.php

public function import(Request $request){

    $this->validate($request, [
        'select_file' => 'required|mimes:xls,xlsx'
    ]);

    $path = $request->file('select_file')->getRealPath();

    $data = Excel::import($path)->get();

    if($data->count() > 0){
        foreach($data->toArray() as $key => $value){
            foreach($value as $row){
                $insert_data[] = array(
                    'CustomerName'  => $row['customer_name'],
                    'Gender'        => $row['gender'],
                    'Address'       => $row['address'],
                    'City'          => $row['city'],
                    'PostalCode'    => $row['postal_code'],
                    'Country'       => $row['country'],
                );
            }
        }
        if(!empty($insert_data)){
            DB::table('tbl_customer')->inset($insert_data);
        }
    }
    return back()->with('success', 'Import data successfully!');
}

我已经检查 excel.php 文件是否存在于配置文件夹中。添加了提供者和别名。

路线

Route::get('/import-excel', 'ImportExcelController@index');
Route::post('/import-excel/import',  'ImportExcelController@import');

请问如何解决?

这是导入方法的方法签名:

public function import($import, $filePath, string $disk = null, string $readerType = null);

这意味着路径是第二个参数,但是您缺少第一个参数。

第一个应该是import class,你创建一个这样的作为例子

php artisan make:import UsersImport --model=User

然后使用它:

Excel::import(new UsersImport, $path);

您需要让库知道如何将文件中的每一行映射到一个对象以供您使用。

-- 编辑

所以我会创建一个模型,但你也可以这样做:

class CustomersImport implements ToCollection
{
    public function collection(Collection $rows)
    {
        $data = [];

        foreach ($rows as $row) 
        {
            $data[] = array(
                    'CustomerName'  => $row[0],
                    'Gender'        => $row[1],
                    'Address'       => $row[2],
                    'City'          => $row[3],
                    'PostalCode'    => $row[4],
                    'Country'       => $row[5],
                );
        }

        DB::table('tbl_customer')->insert($data);
    }
}

类似这样,但调试 rows 包含的内容并确保在迭代时获得数据库中正确列的正确键。