thinkphp5 使用phpoffice/phpspreadsheet导入和导出excel

PHPExcel已经被废弃在PHP7.2中已经无法获取更新,官方重新开了一个新包phpspreadsheet

composer安装:

composer require phpoffice/phpspreadsheet

一,导出,

1,view中:

导出

,2,在控制器中写方法

public function outExcel(){
        $param = input();
        $where = [];
        $where['a.order_status'] = ['between',[1,7]];
        if (isset($param['order_num']) && !empty($param['order_num']))$where['a.order_num'] = $param['order_num'];
        if (isset($param['order_status']) && !empty($param['order_status']))$where['a.order_status'] = $param['order_status'];
        if (isset($param['addr_name']) && !empty($param['addr_name']))$where['a.addr_name|addr_phone'] = ['like','%'.$param['addr_name'].'%'];
        if (isset($param['user_name']) && !empty($param['user_name']))$where['b.user_name|b.mobile'] = ['like','%'.$param['user_name'].'%'];
        if (isset($param['goods_type']) && !empty($param['goods_type']))$where['a.goods_type'] = $param['goods_type'];
        if (isset($param['addtime']) && !empty($param['addtime'])){
            list($start,$end) = explode('~',trim($param['addtime']));
            $where['a.addtime'] = [['gt',strtotime($start)],['lt',strtotime($end)]];
        }
        $sql =   $this->model->alias('a')->join('member b','a.user_id = b.id')->where($where)->field('a.*,b.user_name,b.mobile')->order('id desc')->select();

        $newExcel = new Spreadsheet();  //创建一个新的excel文档
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        $objSheet->setTitle('管理员表');  //设置当前sheet的标题

        $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);


        $objSheet->setCellValue('A1', '订单编号')
                    ->setCellValue('B1', '会员')
                    ->setCellValue('C1', '收件人')
                    ->setCellValue('D1', '手机号')
                    ->setCellValue('E1', '订单总价')
                    ->setCellValue('F1', '下单时间')
                    ->setCellValue('G1', '分类')
                    ->setCellValue('H1', '状态');
        /*--------------开始从数据库提取信息插入Excel表中------------------*/
        //$i=2;  //定义一个i变量,目的是在循环输出数据是控制行数
        $count = count($sql);  //计算有多少条数据

        for ($i = 2; $i <= $count+1; $i++) {
            $objSheet->setCellValue('A' . $i, $sql[$i-2]['order_num'])
                    ->setCellValue('B' . $i, $sql[$i-2]['user_name'].'('.$sql[$i-2]['mobile'].')')
                    ->setCellValue('C' . $i, $sql[$i-2]['addr_name'])
                    ->setCellValue('D' . $i, $sql[$i-2]['addr_phone'])
                    ->setCellValue('E' . $i, $sql[$i-2]['total_price'])
                    ->setCellValue('F' . $i, date('Y-m-d H:i:s',$sql[$i-2]['addtime']))
                    ->setCellValue('G' . $i, $sql[$i-2]['goods_type'] == 1?'团品':'引流')
                    ->setCellValue('H' . $i, $sql[$i-2]['order_status']);
        }


        /*--------------下面是设置其他信息------------------*/
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=".$param['addtime'].'订单'.".xls");
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, 'Xls');
        $objWriter->save('php://output');

//通过php保存在本地的时候需要用到
        //$objWriter->save($dir.'/demo.xlsx');

        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        //header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        //header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        //header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        //header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        //header('Pragma: public'); // HTTP/1.0
        exit();
    }

二,导入

控制器方法

 public function uplaod()
    {
        //获取表格的大小,限制上传表格的大小5M
        $file_size = $_FILES['myfile']['size'];
        if ($file_size > 5 * 1024 * 1024) {
            $this->error('文件大小不能超过5M');
            exit();
        }

        //限制上传表格类型
        $fileExtendName = substr(strrchr($_FILES['myfile']["name"], '.'), 1);
        //application/vnd.ms-excel  为xls文件类型
        if ($fileExtendName != 'xls') {
            $this->error('必须为excel表格,且必须为xls格式!');
            exit();
        }

        if (is_uploaded_file($_FILES['myfile']['tmp_name'])) {
            // 有Xls和Xlsx格式两种
            $objReader = IOFactory::createReader('Xls');

            $filename = $_FILES['myfile']['tmp_name'];
            $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格,或者是指定的表格
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            // $highestColumn = $sheet->getHighestColumn();   // 取得总列数

            //定义$usersExits,循环表格的时候,找出已存在的用户。
            $usersExits = [];
            //循环读取excel表格,整合成数组。如果是不指定key的二维,就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {
                $data[$j - 2] = [
                    'admin_username' => $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue(),
                    'admin_password' => $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue(),
                    'create_time' => time()
                ];
                //看下用户名是否存在。将存在的用户名保存在数组里。
                $userExist = db('admin')->where('admin_username', $data[$j - 2]['admin_username'])->find();
                if ($userExist) {
                    array_push($usersExits, $data[$j - 2]['admin_username']);
                }
            }
            //halt($usersExits);

            //如果有已存在的用户名,就不插入数据库了。
            if ($usersExits != []) {
                //把数组变成字符串,向前端输出。
                $c = implode(" / ", $usersExits);
                $this->error('Excel中以下用户名已存在:' . $c, "/backend/admin/create", '', 20);
                exit();
            }

            //halt($data);
            //插入数据库
            $res = db('admin')->insertAll($data);
            if ($res) {
                $this->success('上传成功!', '/backend/admin', '', 1);
            }
        }
    }

 

你可能感兴趣的:(tp5)