laravel上传并导入excel

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/amazingdyd/article/details/72842593

前端页面:

导入EXCEL添加学生
                <form action="/admin/student/import" method='post' enctype="multipart/form-data">
                    <input id="fileId1" type="file" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" name="file"/> 
                    <input type="submit" value="确认">
                </form>

后端处理

 public function import(Request $request){

        if(!$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();  
        });
        for($i = 1;$i<count($res);$i++){
            $check = Students::where('name',$res[$i][0])->where('title',$res[$i][4])->count();
            if($check){
                continue;
            }
            $stu = new Students;
            $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 Redirect::to('/admin/student')->withSuccess("导入成功");
        
    }


猜你喜欢

转载自blog.csdn.net/amazingdyd/article/details/72842593