用 PHPExcel 导入excel表格并展示到前台

  我的整体项目表:

  

  phpExce放在

  

  引入PHPExc路径是:

    require_once  dirname(dirname(dirname(dirname(__FILE__)))).'/system/libraries/PHPExcel/Classes/PHPExcel/IOFactory.php';   这样的绝对路径
    注:使用相对路径时,可能是我引入路径不对吧,我原本的相对路径是require_once '../../../system/libraries/PHPExcel/Classes/PHPExcel/IOFactory.php';

   前台
      
<input type="text" name="filename" id="filename" value="" class="am-form-field" placeholder="文件名"
       style="width:200px;text-align:left;height:40px">
<button type="button" id="selected" style="margin:-41px 0px 0px 201px;height:41px"
        class="am-btn am-btn-default" onclick="$('#cvsFile').click()"><span class="am-icon-archive"></span> 选择文件</button>
<button type="button" id="submit" style="margin:-41px 0px 0px 1px;height:41px" class="am-btn am-btn-default"
        onclick="btn_import_click()"><span class="am-icon-archive"></span> 导入</button>
<input type="file" id="cvsFile" name="cvsFile" value="" class="am-btn am-btn-default" style="display: none"
       onchange="document.getElementById('filename').value=this.value" />

  js:

    

 function btn_import_click() {
        var url = '<?php echo site_url("admin/operate/excelToArray") . "?sys=" . $sys."&mencode=yungl";?>';
        $.ajaxFileUpload({
            url: url,
            secureuri: false,
            fileElementId: 'cvsFile',
            dataType:'content',
            success: function (data,status) {
                var obj=JSON.parse(data);
                if (obj.code==1){
                    $('#batch_phone').empty();
                    $('#batch_phone').append(obj.msg);
                }
            },
            error: function (data,status,e) {
                console.log('报错了:'+e);
            }
        });
    }

    后台代码:

    

     /**
         * excel导入
         */
        public function excelToArray()
        {
            $addfile = $_FILES['cvsFile'];
            $excelfilename = $addfile['tmp_name'];

            if ($addfile['type'] != 'application/vnd.ms-excel' && $addfile['type'] != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
                echo '上传格式不正确,请重新上传';
                die;
            }

            require_once  dirname(dirname(dirname(dirname(__FILE__)))).'/system/libraries/PHPExcel/Classes/PHPExcel/IOFactory.php';
            $objPHPExcel=PHPExcel_IOFactory::load($excelfilename);
            //获取excel里面的数据
            $objworkSheet=$objPHPExcel->getSheet(0)->toArray();
            $phone_arr='';
            foreach ($objworkSheet as $k=>$v){
                $phone_arr .=$v[0].',';
            }
            $phone_arr = substr($phone_arr,0,strlen($phone_arr)-1);
            $data['code']=1;
            $data['msg']=$phone_arr;

            echo json_encode($data,JSON_UNESCAPED_UNICODE);
            die;

        }

 

     需要下载phpExce类库的可以去 http://pan.baidu.com/s/1qYLsbne  密码:012j

  

 

posted @ 2017-11-15 14:28  *琴  阅读(2348)  评论(0编辑  收藏  举报