我需要在db中导入excel数据。但是给了我艰难的时间。 这是我的控制器功能
$path = Input::file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = ['product_id' => $value->price, 'details' =>
$value->stock];
}
if(!empty($arr)){
\DB::table('stock')->insert($arr);
dd('Insert Record successfully.');
}
}
其中价格和库存是excel中的字段。 以下是错误
Property [price] does not exist on this collection instance.
当我尝试在db中保存excel数据时,这是我的控制器功能的dd()。
SheetCollection {#375 ▼
#title: ""
#items: array:3 [▼
0 => RowCollection {#498 ▼
#heading: array:2 [▼
0 => "stock"
1 => "price"
]
#title: "Sheet1"
#items: array:3 [▼
0 => CellCollection {#462 ▼
#title: null
#items: array:2 [▼
"stock" => 2.0
"price" => 3.0
]
}
1 => CellCollection {#481 ▼
#title: null
#items: array:2 [▼
"stock" => 3.0
"price" => 2.0
]
}
2 => CellCollection {#480 ▼
#title: null
#items: array:2 [▶]
}
]
}
1 => RowCollection {#533 ▶}
答案 0 :(得分:0)
我会在此处粘贴我的导入功能,根据您的需要进行修改。
我的Excel模板只有一张,第一行包含字段名称。
// Retrieve file
$file = $request->file('file');
$ext = $file->getClientOriginalExtension();
// Just my helper method to create filenames
$filename = Helper::create_filename($ext);
// Move file
$path ="uploads/import";
$file->move($path, $filename);
Excel::selectSheetsByIndex(0)->load("{path}/{$filename}", function($reader) {
$sheet = $reader->all();
foreach ($sheet as $i => $row) {
$data = $row->toArray(); // Utilize this data to fill your model
}
});
答案 1 :(得分:0)
更改EXCEL SHEET COLUMN NAME,就像那样
100 400
200 15
12 167