laravel Excel数据导出

项目碰到需要使用Excel导出,使用ajax异步提取。

直接贴代码,后期备用。

 public function exportTeacher(Request $request){

        $start = $request->input('start');
        $end = $request->input('end');
        $this->_result['code']=100;
        if($start!='' && $end==''){
            $this->_result['message']='结束时间不能为空';
            echo json_encode($this->_result);
            exit();
        }
        if($start=='' && $end!=''){
            $this->_result['message']='开始时间不能为空';
            echo json_encode($this->_result);
            exit();
        }
        if($start=='' && $end==''){
            $where = true;
        }else{




            $start = \DateTime::createFromFormat('d/m/y', $start);

            $start=  date_format($start, 'Y-m-d');
            $startTime = strtotime($start);

            $end = \DateTime::createFromFormat('d/m/y', $end);
            $end=  date_format($end, 'Y-m-d');


            $endTime = strtotime($end)+86399;
            if($startTime>$endTime){
                $this->_result['message']='结束时间不能大于开始时间';
                echo json_encode($this->_result);
                exit();

            }

            $where = " UNIX_TIMESTAMP(d.`ctime`)>='{$startTime}' AND UNIX_TIMESTAMP(d.`ctime`)<='{$endTime}' ";
        }

        $cellData =DB::select("SQL语句..................... ");

        if(count($cellData)==0){
            $this->_result['message']='未查询到数据';
            echo json_encode($this->_result);
            exit();
        }

        $cellData = array_map('get_object_vars',$cellData);

        array_unshift($cellData,array('老师姓名','老师手机号码','提现金额','提现后剩余总金额','提现申请id','提现时间'));



        /*
         * 如果你要导出csv或者xlsx文件,只需将 export 方法中的参数改成csv或xlsx即可。
         * 如果还要将该Excel文件保存到服务器上,可以使用 store 方法:
         */
        Excel::create(iconv('UTF-8', 'GBK', 'teacher'),function($excel) use ($cellData){
            $excel->sheet('score', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });
        })->store('xls');

        $this->_result['code']=200;
        $this->_result['message']='success';
        $this->_result['data']=URL('manage/downloadTeacher');
        header('Content-type:application/json');
        echo json_encode($this->_result);
    }

//生成的文件存于项目的/storage/exports目录中

  public function downloadStudent(){
        $file = storage_path().'/exports/student.xls';
        return response()->download($file);
    }

猜你喜欢

转载自www.cnblogs.com/liyante/p/9327483.html