1. 程式人生 > >laravel上傳並匯入excel

laravel上傳並匯入excel

前端頁面:

匯入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("匯入成功");
        
    }