tp5 导入phpExcel的简单demo

1、下载PHPExcel扩展包 下载地址 链接: https://pan.baidu.com/s/1v_9ywN2YWJNfDESm1NHffg 密码: 8dqt

tp5 导入phpExcel的简单demo_第1张图片

 2、讲下载的解压并放进vendor目录,如下图

tp5 导入phpExcel的简单demo_第2张图片

3、HTML代码




    
    数据导入
    


   

下载导入模板


   

   

       
       
       
   

代码截图

tp5 导入phpExcel的简单demo_第3张图片

页面效果图

tp5 导入phpExcel的简单demo_第4张图片

4、PHP代码

namespace admin\index\controller;

use think\Controller;
use \org\Auth;
use \think\Db;
use think\Request;
use \admin\index\Model;
use \think\Session;
class Import extends Controller
{

    public function __construct(){
        parent::__construct();
        
    }
    /**
     * 数据导入
     * @return mixed
     */
    public function index(){
        
        return $this->fetch();
    }
    
    public function imp_data(){
        //获取表单上传文件
        $file = $this->request->file('files');
        $info = $file->move(ROOT_PATH . 'public' . DS . 'Excel');
        //移动到框架应用根目录
        if ($info) {
            

            $file_name = ROOT_PATH . 'public' . DS . 'excel' . DS . $info->getsaveName();
            // dump($file_name);
            $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION)); //判断导入表格后缀格式
            // dump($extension);die;
            vendor("PHPExcel.PHPExcel");
            $objPHPExcel = new \PHPExcel();
            // $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            $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);  //删除第一个数组(标题);
            // dump($excel_array);die;

            $pcNum = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            foreach ($excel_array as $key => $value) {
                $data['utel1'] = $value[0];
                $data['uname'] = $value[1];
                $data['uremark'] = $value[2];
                $data['ucol1'] = $value[3];
                $data['ucol2'] = $value[4];
                $data['ucol3'] = $value[5];
                $data['ucol4'] = $value[6];
                $data['ucol5'] = $value[7];
                $data['ucol6'] = $value[8];
                $data['ucol7'] = $value[9];
                $data['ucol8'] = $value[10];
                $data['ucol9'] = $value[11];
                $data['ucol10'] = $value[12];
                $data['upc'] = $pcNum;
                $data['uaddtime'] = date('Y-m-d H:i:s', time());
                // $data['entid'] = $_SESSION['user']['entid'];
                // $data['workno'] = $_SESSION['user']['workno'];
                $res = Db::table('cti_phone')->insert($data);
            }
            if($res){
                $this->success('导入成功!');
            }
        }else{
            //上传失败获取错误信息
            $this->error($file->getError());
        }

    }

}

你可能感兴趣的:(php,PHPExcel,thinkphp5)