前期准備工作:
1.下載PHPExcel放到vendor下
2.前端頁面:
<form action="save" method="post" enctype="multipart/form-data"> <div class="time-add clearfix"> <input type="submit" disabled name="submit" class="submit" value="提交" /> <a class="dianji" href="javascript:;"> <input type="file" name="file" id="fileupload" class="inputfile" style="position: absolute;display: none;"/> <label class="span" for="fileupload">批量導入用餐記錄</label> </a> </div> </form>
3.后端代碼
public function save(){ //設置文件上傳的最大限制 ini_set('memory_limit','1024M'); //加載第三方類文件 vendor("PHPExcel.PHPExcel"); //防止亂碼 header("Content-type:text/html;charset=utf-8"); //實例化主文件 //接收前台傳過來的execl文件 $file = $_FILES['file']; //截取文件的后綴名,轉化成小寫 $extension = strtolower(pathinfo($file['name'],PATHINFO_EXTENSION)); if($extension == "xlsx"){ //2007(相當於是打開接收的這個excel) $objReader =\PHPExcel_IOFactory::createReader('Excel2007'); }else{ //2003(相當於是打開接收的這個excel) $objReader = \PHPExcel_IOFactory::createReader('Excel5'); } $objContent = $objReader -> load($file['tmp_name']); if ($objContent){ $sheetContent = $objContent -> getSheet(0) -> toArray(); //刪除第一行標題 unset($sheetContent[0]); $time= $mothtime= strtotime(date("Y-m-d H:i:s", strtotime("-1 month"))); foreach ($sheetContent as $k => $v){ $arr['name'] = $v[1]; $arr['card_number'] = $v[2]; $arr['department_name'] = $v[3]; $arr['breakfast'] = $v[4]; $arr['lunch'] = $v[5]; $arr['dinner'] = $v[6]; $arr['supper'] = $v[7]; $arr['total'] = $v[8]; $arr['create_time'] = $time; $res[] = $arr; } //刪除最后一行匯總 array_pop($res); $re = Db::name('dining') ->insertAll($res); if($re){ $this->success('導入成功 !'); }else{ $this->error('導入失敗 !'); } }else{ $this->error('請導入表格 !'); } }