第一步:下载官方的PHPExcel文件,下载地址https://github.com/PHPOffice/PHPExcel
第二步:解压打开,将PHPExcel\Classes\全部文件拷贝到thinkhp项目的根目录\ThinkPHP\Library\Vendor\,如下图所示
第三步:
HTML代码如下:
<form action="{:U(‘Index/impUser‘)}" method="post" enctype="multipart/form-data"> <input type="file" name="import"/> <input type="submit" value="提交"/> </form>
控制器层实现如下代码:
function impUser(){ if (!empty($_FILES)) { //import("@.ORG.UploadFile"); $config=array( ‘exts‘=>array(‘xlsx‘,‘xls‘), ‘rootPath‘=>"./Public/", ‘savePath‘=>‘Upload/‘, //‘autoSub‘ => true, ); $upload = new \Think\Upload($config); if (!$info=$upload->upload()) { $this->error($upload->getError()); } /*else { //$info = $upload->getUploadFileInfo(); } */ vendor("PHPExcel.PHPExcel"); $file_name=$upload->rootPath.$info[‘import‘][‘savepath‘].$info[‘import‘][‘savename‘]; // var_dump($file_name); // exit; $objReader = \PHPExcel_IOFactory::createReader(‘Excel5‘); $objPHPExcel = $objReader->load($file_name,$encode=‘utf-8‘); $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); // 取得总行数 $highestColumn = $sheet->getHighestColumn(); // 取得总列数 for($i=4;$i<=$highestRow;$i++) { $data[‘name‘] = $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue(); $data[‘age‘] = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue(); $data[‘school‘]= $objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();=$data[‘jion_time‘]= gmdate("Y-m-d H:i:s", \PHPExcel_Shared_Date::ExcelToPHP($objPHPExcel->getActiveSheet()->getCell("M".$i)->getValue()));//其中gmdate函数是对excel表格中的时间进行格式化处理 M(‘detail_config‘)->add($data); } $this->success(‘导入成功!‘,‘index‘); }else { $this->error("请选择上传的文件"); } }
时间: 2024-10-11 07:11:23