1、引入包文件
链接:https://pan.baidu.com/s/1TwtSXdQhj3B4m8NAuOcsVw?pwd=123a
提取码:123a
2、包文件减压发在 extend 文件夹下
在控制器中使用
public function save(){ header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE"); header("Access-Control-Allow-Headers: Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With"); header("Content-Type: text/html; charset=utf-8"); if(request() -> isPost()) { \think\Loader::import('PHPExcel.PHPExcel'); $objPHPExcel =new \PHPExcel(); //获取表单上传文件 $file = request()->file('file'); $info = $file->validate(['ext' => 'xlsx,xls'])->move(ROOT_PATH . 'uploads/file'); //上传验证后缀名,以及上传之后移动的地址 if($info) { $exclePath = $info->getSaveName(); //获取文件名 $file_name = ROOT_PATH . 'uploads/file' . DS . $exclePath;//上传文件的地址 $name = $this->getExt1($file_name); if($name =='xlsx' ){ $objReader = \PHPExcel_IOFactory::createReader('Excel2007'); }else { $objReader = \PHPExcel_IOFactory::createReader('Excel5'); } $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8'); //加载文件内容,编码utf-8 $excel_array=$obj_PHPExcel->getSheet(0)->toArray(); //转换为数组格式 array_shift($excel_array); //删除第一个数组(标题); $merchant = []; $i=0; $batch_id = time(); foreach($excel_array as $k=>$v) { //四要素基础验证 根据自己情况选择是否判断 $checkObj = new Check(); $result = $checkObj->check_info($v); //var_dump($result);die; $merchant[$k]['content'] = $result['msg'] . '+' . $result['data']['msg'] . '+' . $result['data']['desc']; $merchant[$k]['字段一'] = isset($v[1]) ? $v[1] : "无"; $merchant[$k]['字段二'] = isset($v[2]) ? $v[2] : "无"; $merchant[$k]['字段三'] = isset($v[3]) ? $v[3] : "无"; $merchant[$k]['字段四'] = $v[4] ? $v[4] : 0; $merchant[$k]['字段五'] = $v[5] ? $v[5] : 0; $merchant[$k]['字段六'] = $batch_id; $i++; } //插入数据总数 $count=Db::table("自己的表名")->insertAll($merchant); if ($count<$i) { return e('导入异常'); } return s('导入成功'); }else{ return $file->getError(); } } }
class Check extends Base { public function check_info($data) { //参数 $validate = new Validate([ '1' => 'require|max:25', '2' => 'require|max:11', '3' => 'require|number|max:19', '4' => 'require|number', ]); if (!$validate->check($data)) { return $validate->getError(); }else{ $res = "此处四要素验证,没有可以跳过"; return $res; } } }
注意:
此处一定要引入,要不会报错 找不到 PHPExcel 类文件 如下图
3、引入后就可以成功导入数据了
欢迎大家指点
标签:merchant,info,name,excel,字段,tp5,导入,file,PHPExcel From: https://blog.csdn.net/weixin_62291378/article/details/139181317