1.Composer安装依赖:
composer require "maatwebsite/excel:~2.1.0"
2.在config/app.php中注册服务提供者到providers数组:
Maatwebsite\Excel\ExcelServiceProvider::class,
3.在config/app.php中注册门面到aliases数组:
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
4.生成Laravel Excel的配置文件,使用如下命令:
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
二.安装好 Excel库之后,我们的上传前端页面这样写:
1.前端样式写法:
<form action="/device/imports" method='post' enctype="multipart/form-data">
{{ csrf_field() }}
<input id="fileId1" type="file" name="file"/>
<input type="submit" value="确认上传">
</form>
2.添加路由文件例如:
Route::group(['prefix' => 'device'],function(){
Route::post('imports', ['uses'=>'DeviceController@imports','permissions'=>'device/imports']);
});
3.后端写法,首先要文件开头要引入Excel门面类:
use Excel;
/**
* 批量导入设备
* 2018年08月22日09:58:26
*/
public function imports(){
if(!$this->_request->hasFile('file')){
exit('上传文件为空!');
}
$file = $_FILES;
$excel_file_path = $file['file']['tmp_name'];
$res = [];
Excel::load($excel_file_path, function($reader) use( &$res ) {
$reader = $reader->getSheet(0);
$res = $reader->toArray();
},'GBK');
for($i = 1;$i<count($res);$i++){
$check = Device::where('name',$res[$i][0])->where('title',$res[$i][4])->count();
if($check){
continue;
}
// $stu = new Device;
// $stu->name = $res[$i][0];
// $stu->group = $res[$i][1];
// $stu->teacher = $res[$i][2];
// $stu->school = $res[$i][3];
// $stu->mobile = $res[$i][4];
// $stu->title = $res[$i][5];
// $stu->save();
}
// return Device::to('/admin/student')->withSuccess("导入成功");
}
4.之后再for循环中实现你的业务逻辑,最后入库之类。其实蛮简单的。
---------------------
作者:yyb5683
来源:CSDN
原文:https://blog.csdn.net/yyb5683/article/details/81940428
版权声明:本文为博主原创文章,转载请附上博文链接!转载请注明出处:
未经允许不得转载:lxfamn » Laravel Excel