【laravel -excel】批量导入更新数据CSV,EXCEL等。

安装包

1
composer require maatwebsite/excel

我这里是导入CSV然后批量更新里面的数据,关键代码如下:

1
2
3
4
5
6
7
8
9
try{
Excel::import(new ExchangeImports(),request()->file('file'));
$data['code'] = 200;
$data['msg'] = '导入完成';
}catch (\Exception $e){
$data['data'] = $e->getMessage();


}

导入类:由于需要更新指定要求的数据,所以使用的是onRow来自定义操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class ExchangeImports implements OnEachRow
{
public function onRow(Row $row)
{

$row = $row->toArray();
$goods = ExchangeRecord::where('id',$row[0])->first();

if(!$goods) return;
if($goods['status'] != 2 ){
$data['status'] = 2;
$data['express_time'] = time();
$data['express_company'] = $row[8] ?? '未获取到';
$data['express_number'] = $row[9] ?? '未获取到';
$goods->update($data);
}


}
}