先下載phpexcel文件 將classes文件重命名為phpexcel 復制到 \extend 目錄
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <title>表格上傳</title> </head> <body> <form id="input-excel" method="post" action="{:url('excel_import')}" enctype="multipart/form-data"> <div class="form-group"> <input type="hidden" name="table" value="tablename"/> <input type="file" name="excel" id="excel"> <input type="submit" value="導入"/> <p class="help-block"></p> </div> </form> </body> </html>
<?php namespace app\index\controller; use think\Controller; use think\Request; use think\File; use think\loader; class User extends Controller { public function test() { return $this->fetch(); } public function add() { if (request()->ispost()) { $post = input('post.'); $file = request()->file('excel'); dump($file);die; excel_import($file); } else { $role_data = db('role')->select(); $this->assign('role_data', $role_data); return $this->fetch(); } } public function excel_import($file) { // dump($file);die; // 移動到框架應用根目錄/public/uploads/ 目錄下 $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel'); if ($info) { //獲取文件所在目錄名 $path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel/' . $info->getSaveName(); //加載PHPExcel類 // vendor("PHPExcel.PHPExcel"); Loader::import('PHPExcel.PHPExcel'); Loader::import('PHPExcel.PHPExcel.IOFactory.PHPExcel_IOFactory'); //實例化PHPExcel類(注意:實例化的時候前面需要加'\') // $objReader=new \PHPExcel_Reader_Excel5(); $filename = $info->getSaveName(); //獲取文件名后綴 $suf = substr($filename, strrpos($filename, '.')); if ($suf == '.xlsx') { $objReader = new \PHPExcel_Reader_Excel2007(); } else if($suf == '.xls'){ $objReader = new \PHPExcel_Reader_Excel5(); }else{ return '文件類型錯誤'; } $objPHPExcel = $objReader->load($path, $encode = 'utf-8'); //獲取excel文件 $sheet = $objPHPExcel->getSheet(0); //激活當前的表 $highestRow = $sheet->getHighestRow(); // 取得總行數 $highestColumn = $sheet->getHighestColumn(); // 取得總列數 $a = 0; //將表格里面的數據循環到數組中 for ($i = 2; $i <= $highestRow; $i++) { //*為什么$i=2? (因為Excel表格第一行應該是姓名,年齡,班級,從第二行開始,才是我們要的數據。) $data[$a]['name'] = $objPHPExcel->getActiveSheet()->getCell("A" . $i)->getValue(); //姓名 $data[$a]['age'] = $objPHPExcel->getActiveSheet()->getCell("B" . $i)->getValue(); //年齡 $data[$a]['class'] = $objPHPExcel->getActiveSheet()->getCell("C" . $i)->getValue(); //班級 // 這里的數據根據自己表格里面有多少個字段自行決定 $a++; } //往數據庫添加數據 // $res = Db::name('student')->insertAll($data); // if($res){ // $this->success('操作成功!'); // }else{ // $this->error('操作失敗!'); // } dump($data); } else { // 上傳失敗獲取錯誤信息 $this->error($file->getError()); } } }