先下载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>
<?phpnamespace appindexcontroller; use thinkController; use thinkRequest; use thinkFile; use thinkloader;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()); } } }