我正在尝试在Laravel中导入Excel数据并将其插入数据库。我正在使用maatwebsite / excel 3版作曲家软件包和laravel 5.8版
错误屏幕截图: https://imgur.com/a/2KXCE0g
刀片文件: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文件是否在config文件夹中退出。提供程序和别名添加。
路线
Route::get('/import-excel', 'ImportExcelController@index');
Route::post('/import-excel/import', 'ImportExcelController@import');
如何解决这个问题?
答案 0 :(得分:3)
这是导入方法的方法签名:
public function import($import, $filePath, string $disk = null, string $readerType = null);
这意味着路径是第二个参数,但是您缺少第一个参数。
第一个应该是import
类,您将创建一个像这样的示例
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
包含的内容,并确保在进行迭代时获得正确的键,以指向数据库中的正确列。