FastAdmin导出( phpoffice/phpexcel扩展包已停止维护所以仅支持7.3以下版本)

安装扩展包

composer require phpoffice/phpexcel(出现版本兼容问题可以追加 --ignore-platform-reqs)

index.html添加

 <a href="javascript:;" class="btn btn-success btn-export {:$auth->check('user/export')?'':'hide'}" title="{:__('Export')}" id="btn-export-file"><i class="fa fa-download"></i> {:__('Export')}</a>

index.js添加

$(document).on("click", ".btn-export", function () {
  var ids = Table.api.selectedids(table);
  var page = table.bootstrapTable('getData');
  var all = table.bootstrapTable('getOptions').totalRows;
  console.log(ids.length, page.length, all);
  Layer.confirm("请选择导出的选项<form action='" + Fast.api.fixurl("user/export") + "' method='post' id='cc' target='_blank'><input type='hidden' name='ids' id='kk' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'><input type='hidden' name='search'><input type='hidden' name='columns'></form>", {
    title: '导出数据',
    btn: ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
      success: function (layero, index) {
        $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
          }
        , yes: function (index, layero) {
          if (ids.length > 0) {
            var form = document.getElementById('cc');
            var custmoreInput = document.getElementById('kk');
              custmoreInput.setAttribute("value", ids.join(","));
              form.submit(ids.join(","), layero);
                return true;
                            }
                            return false;
                        }
                        ,
                        btn2: function (index, layero) {
                            var ids = [];
                            $.each(page, function (i, j) {
                                ids.push(j.id);
                            });
                            if (ids.length > 0) {
                                var form = document.getElementById('cc');
                                var custmoreInput = document.getElementById('kk');
                                custmoreInput.setAttribute("value", ids.join(","));
                                form.submit(ids.join(","), layero);
                                return true;
                            }
                            return false;
                        }
                        ,
                        btn3: function (index, layero) {
                            var form = document.getElementById('cc');
                            var custmoreInput = document.getElementById('kk');
                            custmoreInput.setAttribute("value", "all");
                            form.submit("all", layero);
                            return true;
                        }
                    })
                });

index.php(当前导出的控制器)导出代码

public function export()
    {
        if ($this->request->isPost()) {
            set_time_limit(0);
            $ids = $this->request->post('ids');

            $excel = new PHPExcel();
            $excel->getProperties()->setTitle("文档标题");

//设置表格参数
            $excel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
            $excel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
            $excel->getActiveSheet()->getColumnDimension('C')->setWidth(35);
//设置表头内容
            $worksheet = $excel->setActiveSheetIndex(0)
                ->setCellValue('A1', '序号')
                ->setCellValue('B1', '合同编号')
                ->setCellValue('C1', '姓名');

//根据情况搜索内容有其他条件可在select之前添加
                        if($ids=='all' || empty($ids)){
                $list = $this->model->select();
                        } else {
                                $list = $this->model->select($ids);
                        }

//循环添加表中内容 严谨一些可以在$val['']后添加 ?? '里面填入数据为空时的信息'
            foreach ($list as $k => $val) {
                $k = $k + 2;
                $worksheet->setCellValue('A' . $k, $val['id'])
                    ->setCellValue('B' . $k, $val['number'])
                    ->setCellValue('C' . $k, $val['name']);
            }

            $excel->createSheet();
            $title = "文档标题" . date("YmdHis");
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');

            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
            $objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
            $objWriter->save('php://output');
            exit;
            return;
        }
    }

FastAdmin导入( phpoffice/phpexcel扩展包已停止维护所以仅支持7.3以下版本)

安装扩展包

composer require phpoffice/phpexcel(出现版本兼容问题可以追加 --ignore-platform-reqs)

index.html添加

<a data-url="user/upload"  href="javascript:;" class="btn btn-success spec_add_btn" data-title="{:__('Import')}" ><i class="fa fa-upload"></i> {:__('Import')}</a>

index.js添加

 $(document).on('click','.spec_add_btn', function (event) {
        var url = $(this).attr('data-url');
        if(!url) return false;
        var msg = $(this).attr('data-title');
        var width = $(this).attr('data-width');
        var height = $(this).attr('data-height');
        var area = [$(window).width() > 800 ? (width?width:'800px') : '95%', $(window).height() > 600 ? (height?height:'600px') : '95%'];
        var options = {
            shadeClose: false,
            shade: [0.3, '#393D49'],
            area: area,
            callback:function(value){
                CallBackFun(value.id, value.name);//在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
            }
        };
        Fast.api.open(url,msg,options);
    });

index.php(当前导入的控制器)导入代码

public function upload()
    {
        if (!empty($this->request->post())){
            $path = $this->request->post('path');
            $school_id=$this->request->post('school_id');
            $school_class_id=$this->request->post('school_class_id');
            $fix=substr(strrchr($path, '.'), 1);
//            if ($fix!=='xls') {
//                $this->error('文件格式错误,请您上传后缀名为xls的文件!');
//            }
            //读取excel
//            $objReader = IOFactory::createReader('Xls');
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            $objPHPExcel = $objReader->load($_SERVER['DOCUMENT_ROOT'].$path);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            if ($highestRow<2) {
                $this->error('文件内容不能为空!');
            }
            $data = [];
            for ($j = 2; $j <= $highestRow; $j++) {
                $data[$j - 2] = [
                    'id' => $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue(),
                    'student_name' => $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue(),
                    'student_dept' => $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue(),
                    'student_class' => $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue(),
                    'student_counselor' => $objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue(),
                ];
            }

            $re =Db::table('sdmu_student')->insertAll($data);
            if ($re) {
                $this->success('导入成功');
            }
        }
        return $this->view->fetch();
    }