thinkPHP5——PHPexcel文件导入

所涉及文件:

1.Member.php文件的代码:

 public function member_import(){
    //file(path,include_path,context)把整个文件读入一个数组中
    $file = request()->file('file');

    //调用upload方法上传文件,取到文件地址
    $mfile = new Excel();
    $file_url = $mfile->upload($file);

        //通过上传验证    
        if($file_url['code']){

            //调用import方法,取到EXcel数据处理后的数组
            $data = $mfile -> import($file_url['data']);

            //开启事务,初始化 status =1
            Db::startTrans();
            $status = 1;

            //循环数组,判断每条数据是否合法,不合法,status=0,break;退出循环
            //调用静态验证方法importcheck()
            $vali_data = VExcel::importcheck();
            //遍历输出
            foreach ($data as $key => $value) {
                $title_data['username'] = empty($value['A']) ? 0 : $value['A'];
                $title_data['password'] = empty($value['B']) ? 0 : $value['B'];
                $title_data['status'] = empty($value['C']) ? 0 : $value['C'];
                //验证    
                $validate = new ValidateFun($vali_data['rule'],$vali_data['message']);
                $validatecheck = $validate->check($title_data);
                if(!$validatecheck){
                    $status = 0;
                    break;
                }
                else{
                    $gen = new User();//加密
                    $title_data['encrypt'] = $gen->generate_password();//随机码
                    $title_data['password'] =  md5(md5($title_data['password']). $title_data['password'].$title_data['encrypt']);

                    db('member')->insert($title_data);
                }
            }
            //判断status,0事务回滚,1事务提交
            //返回对应提示语和结果
            if($status == 1){
                // 更新成功 提交事务
                Db::commit();
                return json(['code' => 200,'msg'=>'成功上传']);
            }
            else{
                // 更新失败 回滚事务
                Db::rollback();
                return json(['code' => 400,'msg'=>'第'.$key."行,".$validate->getError()]);
            }
        }
        else{
            return json(['code' => 400,'msg' =>$file_url['msg']]);
        }
    }

2.Excel.php的代码

class Excel{
    
    /**
     * 上传图片
     */
    public function upload($file){
        //接收文件流数据
        //dump($file);exit();
        if (empty($file)) {
            return ['code' => false,'msg' => '请选择上传文件'];
        }
        //判断文件类型
        if($_FILES['file']['type'] != "application/vnd.ms-excel") {
            return ['code' => false,'msg'=>'上传失败,只能上传excel的xls格式!'];
        }
        if($_FILES["file"]["error"] > 0){
            return ['code' => false,'msg' => '文件格式错误',"data" => $_FILES["file"]["error"]];
        }
        //整理路径/文件名
        // 转化文件名字符
        else{
            $savename = iconv("UTF-8", "gbk",$file->getInfo()['name']);
            //移动到框架应用根目录/public/uploads/ 目录下
            //保存文件
            $info = $file -> move(ROOT_PATH . 'public' . DS . 'uploads', $savename);
            //返回文件路径
            $file_url = './public/uploads/' . $file->getInfo()['name'];
            //返回文件路径
            if ($info) {
                return ['code'=>true,'data'=>$file_url];
            }
            else {
                //上传失败获取错误信息
                return json(["code" => false, "msg" => "文件上传失败", "data" => $file->getError()]);
            }
        }
    }
    
     /**
     * 导入Excel表格
     * @param $file_url string Excel地址
     * @return array 
     */
    public function import($file_url){
        //判断Excel文件是否存在
        $file = iconv("UTF-8", "gbk", $file_url);   //转码
        if(empty($file) OR !file_exists($file)) {
            die('文件不存在!');
        }

        //实例化PHPExcel插件(根据Excel文件后缀名选择不同版本)
        vendor('PHPExcel.PHPExcel');// 将Vendor目录中的PHPExcel/PHPExcel.php类文件引入
        $objRead = new \PHPExcel_Reader_Excel2007();   //建立reader对象
        if(!$objRead->canRead($file)){
            $objRead = new \PHPExcel_Reader_Excel5();
            if(!$objRead->canRead($file)){
                die('上传文件格式不正确!');
            }
        }

        //获取Excel表格内容
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
            'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ',
            'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

        $obj = $objRead->load($file);  //建立excel对象
        $currSheet = $obj->getSheet();   //获取指定的sheet表
        $columnH = $currSheet->getHighestColumn();   //取得最大的列号
        $columnCnt = array_search($columnH, $cellName);
        $rowCnt = $currSheet->getHighestRow();   //获取总行数

        //整理数据
        $data = array();
        for($_row=3; $_row<=$rowCnt; $_row++){  //读取内容
            for($_column=0; $_column<=$columnCnt; $_column++){
                $cellId = $cellName[$_column].$_row;
                $cellValue = $currSheet->getCell($cellId)->getValue();
                if($cellValue instanceof PHPExcel_RichText){   //富文本转换字符串
                    $cellValue = $cellValue->__toString();
                }
                $data[$_row][$cellName[$_column]] = $cellValue;
            }
        }
        //返回整理后的数组

        return $data;

    }
}

3.验证方法参考https://blog.csdn.net/angryshan/article/details/81485512

4.输出该模块的方法,可下载postman,输入以下内容

猜你喜欢

转载自blog.csdn.net/angryshan/article/details/81535626