thinkcmf5 导入excel

2018-08-16  本文已影响0人  cuihaomaster

目录:


image.png

php代码:

    public function excel()
    {
        import('PHPExcel_IOFactory',EXTEND_PATH.'/excel/PHPExcel');

        $file_url = input('file_url');
        $file_name = input('file_name');//文件名
        $file_url = './upload/'.$file_url;//文件url
        $extension = cmf_get_file_extension($file_name);//文件扩展名

        if(empty($file_url)){
            $this->error('请先上传excel!');
        }

        if($extension == 'xlsx'){
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
            $objPHPExcel = $objReader->load($file_url, $encode = 'utf-8');  //加载文件内容,编码utf-8
        }else if($extension == 'xls'){
            $objReader =\PHPExcel_IOFactory::createReader('Excel5');
            $objPHPExcel = $objReader->load($file_url, $encode = 'utf-8');  //加载文件内容,编码utf-8
        }else{
            $this->error('请上传Excel格式的文件!','');
        }

        $excel_array=$objPHPExcel->getsheet(0)->toArray();   //转换为数组格式
        array_shift($excel_array);  //删除第一个数组(标题);
        $data = [];
        foreach($excel_array as $k=>$v) {
            $data[$k]['re_user_name'] = $v[0];
            $data[$k]['re_user_tel'] = $v[1];
        }
        if(Db::name('report_user')->insertAll($data)){
            $this->success('导入数据成功!');
        } else {
            $this->error('导入数据失败!');
        }
    }

html代码:

    <form action="{:url('ReportUser/excel')}" method="post" class="form-horizontal js-ajax-form margin-top-20">
        <div class="row">
            <div class="col-md-2 col-md-offset-4">
                <input id="file-1" type="hidden" name="file_url" >
                <input  id="file-1-name" type="text" name="file_name" title="" class="form-control">

            </div>
            <div class="col-md-2">
                <a href="javascript:uploadOne('图片上传','#file-1','file');" class="btn btn-success">上传excel</a>
            </div>
        </div>
        <div class="form-group margin-top-20">
            <div class="col-md-offset-4 col-md-2">
                <button type="submit" class="btn btn-primary js-ajax-submit">确定</button>
                <a class="btn btn-default" href="{:url('ReportUser/index')}">{:lang('BACK')}</a>
            </div>
        </div>
    </form>

tip:使用cmf自带的上传文件插件

上一篇下一篇

猜你喜欢

热点阅读