java反射+vue+element实现动态导出excel列表

1. 表设计

总共三个表:t_sys_export_config(导出配置表)、t_sys_export_config_col(导出配置字段映射表)、t_sys_export_config_arg(导出配置参数类型表)

表结构

  • t_sys_export_config(导出配置表)
字段名字段类型字段说明
IDvarchar(64)主键
MODULECODEvarchar(64)模块代码
FUNCODEvarchar(64)功能代码
MODULENAMEvarchar(64)模块名称
ClASSNAMEvarchar(128)类名全路径
METHODNAMEvarchar(128)方法名
  • t_sys_export_config_col(导出配置字段映射表)
字段名字段类型字段说明
IDvarchar(64)主键
CONFIGIDvarchar(64)配置表ID
CTITLEvarchar(64)标题
CVALUEvarchar(64)字段名
SORTint排序
  • t_sys_export_config_arg(导出配置参数类型表)
字段名字段类型字段说明
IDvarchar(64)主键
CONFIGIDvarchar(64)配置表ID
ARGTYPEvarchar(64)参数类型
SORTint参数顺序

2.实现逻辑

  1. 写配置页面,用于导出配置信息的维护。
    导出配置页面

index.vue:

<template>
  <div class="export-config">
    <div class="search-div">
      <div class="son">
        <span class="search-label">模块代码</span>
        <el-input v-model="moduleCode" clearable placeholder="输入模块代码" style="width:200px;" @input="onSearch" />
      </div>
      <div class="son">
        <span class="search-label">模块名称</span>
        <el-input v-model="modulename" clearable placeholder="输入模块名称" style="width:200px;" @input="onSearch" />
      </div>
      <div class="son">
        <span class="search-label">功能代码</span>
        <el-input v-model="funCode" clearable placeholder="输入功能代码" style="width:200px;" @input="onSearch" />
      </div>
      <div class="son">
        <span class="search-label">功能名称</span>
        <el-input v-model="funname" clearable placeholder="输入功能名称" style="width:200px;" @input="onSearch" />
      </div>
    </div>
    <div class="content-div">
      <div class="button-div">
        <div class="caozuo">
          <el-button type="primary" icon="el-icon-plus" @click="addExport">新建导出配置</el-button>
        </div>
      </div>
      <div class="table-div">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          :row-class-name="tableRowClassName"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
          />
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="75"
          />
          <el-table-column
            prop="modulecode"
            label="模块代码"
            align="center"
          />
          <el-table-column
            prop="modulename"
            label="模块名称"
            align="center"
          />
          <el-table-column
            prop="funcode"
            label="功能代码"
            align="center"
          />
          <el-table-column
            prop="funname"
            label="功能名称"
            align="center"
          />
          <el-table-column
            prop="classname"
            label="类名全路径"
            align="center"
          />
          <el-table-column
            prop="methodname"
            label="方法名"
            align="center"
          />
          <el-table-column label="操作" align="center">
            <template v-slot="scope">
              <el-button type="text" @click="edit(scope.row.id)">修改</el-button>
              <el-button type="text" @click="del(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="my-pagination">
        <el-pagination
          :current-page="page.pageIndex"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <exportDialog v-if="showdialog" :id="id" />
  </div>
</template>

<script>
import exportDialog from './exportDialog'
import { queryExportConfigList, deleteExportConfig } from '@/api/system-management/exportConfig.js'
export default {
  components: {
    exportDialog
  },
  data() {
    return {
      moduleCode: '',
      funCode: '',
      modulename: '',
      funname: '',
      total: 0,
      page: {
        conditions: '',
        orderBy: '[{ field: "modulecode", sortType: "asc" }]',
        pageIndex: 1,
        pageSize: 10,
        pageSizes: [5, 10, 20, 50],
        paginationEnable: false
      },
      tableData: [],
      showdialog: false,
      id: ''
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    onSearch() {
      var condition = []
      if (this.moduleCode) {
        condition.push({
          link: 'and',
          field: 'modulecode',
          op: 'like',
          value: this.moduleCode
        })
      }
      if (this.funCode) {
        condition.push({
          link: 'and',
          field: 'funcode',
          op: 'like',
          value: this.funCode
        })
      }
      if (this.modulename) {
        condition.push({
          link: 'and',
          field: 'modulename',
          op: 'like',
          value: this.modulename
        })
      }
      if (this.funname) {
        condition.push({
          link: 'and',
          field: 'funname',
          op: 'like',
          value: this.funname
        })
      }
      const conditions = {
        conditionGroup: []
      }
      if (condition.length > 0) {
        conditions.conditionGroup.push({
          link: 'and',
          condition: condition
        })
      }
      this.page.conditions = JSON.stringify(conditions)
      this.page.pageIndex = 1
      this.fetch()
    },
    fetch() {
      queryExportConfigList({ page: this.page }).then(res => {
        this.total = res.rowCount
        this.tableData = res.items
      })
    },
    del(id) {
      this.$confirm('删除后不可恢复,是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteExportConfig(id).then(res => {
          this.$message({
            message: res.message,
            type: res.result
          })
          this.onSearch()
        })
      }).catch(() => {
      })
    },
    edit(id) {
      this.id = id
      this.showdialog = true
    },
    addExport() {
      this.id = ''
      this.showdialog = true
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 0) {
        return 'table-div oushu-row'
      } else {
        return 'table-div jishu-row'
      }
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.page.pageIndex = 1
      this.fetch()
    },
    handleCurrentChange(val) {
      this.page.pageIndex = val
      this.fetch()
    }
  }
}
</script>

<style lang='less'>
.export-config{
  .search-div{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .son{
      margin-left: 20px;
      .search-label{
        font-size: 14px;
        color: #272727;
        letter-spacing: 0;
        text-align: right;
        padding-right: 8px;
      }
    }
  }
  .content-div{
    background: #FFFFFF;
    box-shadow: 0 1px 3px 0 rgba(0,0,0,0.08);
    border-radius: 6px;
    border-radius: 6px;
    height: 100%;
    padding: 10px 0px;
    margin-top: 20px;
    margin-left: 20px;
    .button-div{
      padding: 10px 0px 20px 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .caozuo{
        margin-left: 10px;
        .el-button{
          line-height: 1.5;
        }
      }
    }
    .table-div{
      .jishu-row{
        background: #FFFFFF;
      }
      .oushu-row{
        background: #F8F8F8;
      }
    }
  }
}

</style>

exportDialog.vue

<template>
  <el-dialog
    :close-on-click-modal="false"
    title="保存导出配置"
    :visible.sync="dialogVisible"
    width="35%"
    :before-close="handleClose"
  >
    <div class="export-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模块代码" prop="modulecode">
          <el-input
            v-model="form.modulecode"
            maxlength="20"
            show-word-limit
            style="width:420px;"
          />
        </el-form-item>
        <el-form-item label="模块名称" prop="modulename">
          <el-input
            v-model="form.modulename"
            maxlength="20"
            show-word-limit
            style="width:420px;"
          />
        </el-form-item>
        <el-form-item label="功能代码" prop="funcode">
          <el-input
            v-model="form.funcode"
            maxlength="20"
            show-word-limit
            style="width:420px;"
          />
        </el-form-item>
        <el-form-item label="功能名称" prop="funname">
          <el-input
            v-model="form.funname"
            maxlength="20"
            show-word-limit
            style="width:420px;"
          />
        </el-form-item>
        <el-form-item label="类名全路径" prop="classname">
          <el-input
            v-model="form.classname"
            maxlength="100"
            show-word-limit
            style="width:420px;"
          />
        </el-form-item>
        <el-form-item label="方法名" prop="methodname">
          <el-input
            v-model="form.methodname"
            maxlength="64"
            show-word-limit
            style="width:420px;"
          />
        </el-form-item>
        <el-form-item label="字段映射" prop="collist">
          <div
            v-for="(it,ind) in form.collist"
            :key="ind"
            style="margin-bottom:10px;"
          >
            <el-input
              v-model="it.ctitle"
              placeholder="标题"
              style="width:160px"
              maxlength="20"
            />
            <el-input
              v-model="it.cvalue"
              placeholder="字段名"
              style="width:160px"
              maxlength="20"
            />
            <el-input-number
              v-model="it.sort"
              style="width:100px"
              :step="1"
              :min="0"
              :max="99"
            />
            <el-button v-if="ind === form.collist.length -1" plain icon="el-icon-plus" size="mini" circle @click="addcol" />
            <el-button v-if="form.collist.length > 1" plain icon="el-icon-minus" size="mini" circle @click="removecol(ind)" />
          </div>
        </el-form-item>
        <el-form-item label="参数类型" prop="arglist">
          <div
            v-for="(it,ind) in form.arglist"
            :key="ind"
            style="margin-bottom:10px;"
          >
            <el-input
              v-model="it.argtype"
              placeholder="参数类型"
              style="width:210px"
              maxlength="20"
            />
            <el-input-number
              v-model="it.sort"
              style="width:210px"
              :step="1"
              :min="0"
              :max="99"
            />
            <el-button v-if="ind === form.arglist.length -1" plain icon="el-icon-plus" size="mini" circle @click="addarg" />
            <el-button v-if="form.arglist.length > 1" plain icon="el-icon-minus" size="mini" circle @click="removearg(ind)" />
          </div>
        </el-form-item>
      </el-form>
      <div class="button">
        <el-button type="primary" @click="save">确定</el-button>
        <el-button plain @click="handleClose">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { saveExportConfig, findExportConfigDetail } from '@/api/system-management/exportConfig.js'
export default {
  props: {
    id: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: true,
      khjgid: '',
      khjgoptions: [],
      form: {
        id: '',
        modulecode: '',
        modulename: '',
        funcode: '',
        funname: '',
        classname: '',
        methodname: '',
        collist: [
          {
            ctitle: '',
            cvalue: '',
            sort: 0
          }
        ],
        arglist: [
          {
            argtype: '',
            sort: 0
          }
        ]
      },
      rules: {
        modulecode: [
          { required: true, message: '请输入模块代码', trigger: 'blur' },
          { max: 20, message: '长度不能超过20个字符', trigger: 'blur' }
        ],
        modulename: [
          { required: true, message: '请输入模块名称', trigger: 'blur' },
          { max: 20, message: '长度不能超过20个字符', trigger: 'blur' }
        ],
        funcode: [
          { required: true, message: '请输入功能代码', trigger: 'blur' },
          { max: 20, message: '长度不能超过20个字符', trigger: 'blur' }
        ],
        funname: [
          { required: true, message: '请输入功能名称', trigger: 'blur' },
          { max: 20, message: '长度不能超过20个字符', trigger: 'blur' }
        ],
        classname: [
          { required: true, message: '请输入类名全路径', trigger: 'blur' },
          { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
        ],
        methodname: [
          { required: true, message: '请输入方法名', trigger: 'blur' },
          { max: 64, message: '长度不能超过64个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (this.id !== '') {
      this.getDetail()
    }
  },
  methods: {
    getDetail() {
      findExportConfigDetail(this.id).then(res => {
        this.form = res
        if (res.arglist.length === 0) {
          const arglist = [
            {
              argtype: '',
              sort: 0
            }
          ]
          this.$set(this.form, 'arglist', arglist)
        }
        if (res.collist.length === 0) {
          const collist = [
            {
              ctitle: '',
              cvalue: '',
              sort: 0
            }
          ]
          this.$set(this.form, 'collist', collist)
        }
      })
    },
    addcol() {
      this.form.collist.push({
        ctitle: '',
        cvalue: '',
        sort: 0
      })
    },
    removecol(ind) {
      this.form.collist.splice(ind, 1)
    },
    addarg() {
      this.form.arglist.push({
        argtype: '',
        sort: 0
      })
    },
    removearg(ind) {
      this.form.arglist.splice(ind, 1)
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          saveExportConfig(this.form).then(res => {
            this.$message({
              message: res.message,
              type: res.result
            })
            this.$parent.fetch()
            this.handleClose()
          })
        }
      })
    },
    handleClose() {
      this.$parent.showdialog = false
    }
  }
}
</script>

<style lang='less'>
.export-dialog{
  .button{
    text-align: center;
    margin-top: 20px;
  }
}

</style>

exportConfig.js

import request from '@/utils/request'
const baseURL = process.env.VUE_APP_BASE_API_XIONG
import { blobLoadFile } from '@/utils/blob-File-dowload'

// 查询导出配置列表
export function queryExportConfigList(data) {
  return request({
    url: '/TSysExportController/queryExportConfigList',
    method: 'post',
    baseURL,
    data
  })
}

// 保存配置信息
export function saveExportConfig(data) {
  return request({
    url: '/TSysExportController/saveExportConfig',
    method: 'post',
    baseURL,
    data
  })
}

// 找导出配置详情
export function findExportConfigDetail(id) {
  return request({
    url: `/TSysExportController/findExportConfigDetail/${id}`,
    method: 'post',
    baseURL
  })
}

// 删除配置信息
export function deleteExportConfig(id) {
  return request({
    url: `/TSysExportController/deleteExportConfig/${id}`,
    method: 'post',
    baseURL
  })
}

// 导出
export function exportData(moduleCode, funCode, data, fileName) {
  return new Promise(function(resolve, reject) {
    request({
      url: `/TSysExportController/exportData/${moduleCode}/${funCode}`,
      method: 'post',
      responseType: 'blob',
      baseURL,
      data
    }).then(blob => {
      blobLoadFile(blob, fileName, resolve, reject)
    })
  })
}

2.后台接口方法

TSysExportController.java

/**
 * @author bx.yin
 * @ClassName TSysExportController
 * @Description 导出配置
 * @Date 2020年12月18日 下午 1:59
 */
@Api(tags = "导出配置")
@RestController
@RequestMapping("api/TSysExportController")
public class TSysExportController {

    @Autowired
    private TSysExportService exportService;

    @ApiOperation(value = "查询导出配置列表")
    @PostMapping(value = "/queryExportConfigList")
    public ResponseEntity queryExportConfigList(@RequestBody BaseParam baseParam) {
        return new ResponseEntity(exportService.queryExportConfigList(baseParam), HttpStatus.OK);
    }

    @ApiOperation(value = "保存配置信息")
    @PostMapping(value = "/saveExportConfig")
    public ResponseEntity saveExportConfig(@RequestBody Map map) {
        return new ResponseEntity(exportService.saveExportConfig(map), HttpStatus.OK);
    }

    @ApiOperation(value = "找导出配置详情")
    @PostMapping(value = "/findExportConfigDetail/{id}")
    public ResponseEntity findExportConfigDetail(@PathVariable String id) {
        return new ResponseEntity(exportService.findExportConfigDetail(id), HttpStatus.OK);
    }

    @ApiOperation(value = "删除配置信息")
    @PostMapping(value = "/deleteExportConfig/{id}")
    public ResponseEntity deleteExportConfig(@PathVariable String id) {
        return new ResponseEntity(exportService.deleteExportConfig(id), HttpStatus.OK);
    }

    @ApiOperation(value = "导出")
    @PostMapping(value = "/exportData/{moduleCode}/{funCode}")
    public ResponseEntity exportData(@PathVariable String moduleCode, @PathVariable String funCode, @RequestBody Object[] args, HttpServletResponse response) {
        try {
            exportService.exportData(moduleCode, funCode, args, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity(HttpStatus.OK);
    }
}

TSysExportService.java

/**
 * @author bx.yin
 * @ClassName TSysExportService
 * @Description 导出配置
 * @Date 2020年12月18日 下午 2:00
 */
public interface TSysExportService {

    /**
     * @return
     * @description 保存配置信息
     * @author bx.yin
     * @date 2020年12月18日 下午 2:41
     */
    Map saveExportConfig(Map map);

    /**
     * @return
     * @description 删除配置信息
     * @author bx.yin
     * @date 2020年12月18日 下午 2:42
     */
    Map deleteExportConfig(String id);

    /**
     * @return
     * @description 查询导出配置列表
     * @author bx.yin
     * @date 2020年12月18日 下午 2:43
     */
    ReturnMessageDataList queryExportConfigList(BaseParam baseParam);

    /**
     * @return
     * @description 找导出配置详情
     * @author bx.yin
     * @date 2020年12月18日 下午 2:45
     */
    Map findExportConfigDetail(String id);

    /**
     * @param moduleCode: 模块代码
     * @param funCode:    功能代码
     * @return
     * @description 导出数据
     * @author bx.yin
     * @date 2020年12月18日 下午 5:00
     */
    void exportData(String moduleCode, String funCode, Object[] args, HttpServletResponse response) throws Exception;

}

TSysExportServiceImpl.java

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TSysExportServiceImpl implements TSysExportService {

    @Autowired
    private TSysExportConfigRepository configRepository;

    @Autowired
    private BaseSqlDao sqlDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map saveExportConfig(Map map) {
        Map returnMap = new HashMap();
        try {
            TSysExportConfig exportConfig;
            String id = map.get("id") == null ? "" : map.get("id").toString();
            String moduleCode = map.get("modulecode").toString();
            String funCode = map.get("funcode").toString();
            String modulename = map.get("modulename").toString();
            String funname = map.get("funname").toString();
            String classname = map.get("classname").toString();
            String methodname = map.get("methodname").toString();
            List<Map> colList = (List<Map>) map.get("collist");
            List<Map> argList = (List<Map>) map.get("arglist");
            if (StringUtils.isEmpty(id)) { // 新增
                int exist = configRepository.countAllByModulecodeAndFuncode(moduleCode, funCode);
                if (exist > 0) {
                    returnMap.put("result", "error");
                    throw new BaseException("当前模块代码下已存在该功能代码");
                }
                exportConfig = new TSysExportConfig();
                exportConfig.setId(IdUtil.simpleUUID());
                exportConfig.setModulecode(moduleCode);
                exportConfig.setFuncode(funCode);
                exportConfig.setModulename(modulename);
                exportConfig.setFunname(funname);
                exportConfig.setClassname(classname);
                exportConfig.setMethodname(methodname);
                configRepository.save(exportConfig);
                // 插入字段映射
                String sql = "insert into t_sys_export_config_col values(:id,:configid,:ctitle,:cvalue,:sort) ";
                Map paramMap = new HashMap();
                paramMap.put("configid", exportConfig.getId());
                for (Map col : colList) {
                    if (col.get("ctitle") == null || StringUtils.isEmpty(col.get("ctitle").toString()) || col.get("cvalue") == null || StringUtils.isEmpty(col.get("cvalue").toString())) {
                        continue;
                    }
                    paramMap.put("id", IdUtil.simpleUUID());
                    paramMap.put("ctitle", col.get("ctitle"));
                    paramMap.put("cvalue", col.get("cvalue"));
                    paramMap.put("sort", col.get("sort"));
                    sqlDao.executeSql(sql, paramMap);
                }
                // 有参数的话,插入参数类型
                if (argList != null && argList.size() > 0) {
                    sql = "insert into t_sys_export_config_arg values(:id,:configid,:argtype,:sort) ";
                    paramMap.clear();
                    paramMap.put("configid", exportConfig.getId());
                    for (Map arg : argList) {
                        if (arg.get("argtype") == null || StringUtils.isEmpty(arg.get("argtype").toString()) || arg.get("sort") == null || StringUtils.isEmpty(arg.get("sort").toString())) {
                            continue;
                        }
                        paramMap.put("id", IdUtil.simpleUUID());
                        paramMap.put("argtype", arg.get("argtype"));
                        paramMap.put("sort", arg.get("sort"));
                        sqlDao.executeSql(sql, paramMap);
                    }
                }
            } else { // 修改
                int exist = configRepository.countAllByModulecodeAndFuncodeAndIdNot(moduleCode, funCode, id);
                if (exist > 0) {
                    returnMap.put("result", "error");
                    throw new BaseException("当前模块代码下已存在该功能代码");
                }
                Optional<TSysExportConfig> exportConfigOptional = configRepository.findById(id);
                if (!exportConfigOptional.isPresent()) {
                    returnMap.put("result", "error");
                    throw new BaseException("配置不存在");
                }
                exportConfig = exportConfigOptional.get();
                exportConfig.setModulecode(moduleCode);
                exportConfig.setFuncode(funCode);
                exportConfig.setModulename(modulename);
                exportConfig.setFunname(funname);
                exportConfig.setClassname(classname);
                exportConfig.setMethodname(methodname);
                configRepository.save(exportConfig);
                // 删除字段映射和参数类型
                String delColSql = "delete from t_sys_export_config_col where configid = :configid ";
                String delArgSql = "delete from t_sys_export_config_arg where configid = :configid ";
                Map paramMap = new HashMap();
                paramMap.put("configid", id);
                sqlDao.executeSql(delColSql, paramMap);
                sqlDao.executeSql(delArgSql, paramMap);
                // 插入字段映射
                String sql = "insert into t_sys_export_config_col values(:id,:configid,:ctitle,:cvalue,:sort) ";
                for (Map col : colList) {
                    if (col.get("ctitle") == null || StringUtils.isEmpty(col.get("ctitle").toString()) || col.get("cvalue") == null || StringUtils.isEmpty(col.get("cvalue").toString())) {
                        continue;
                    }
                    paramMap.put("id", IdUtil.simpleUUID());
                    paramMap.put("ctitle", col.get("ctitle"));
                    paramMap.put("cvalue", col.get("cvalue"));
                    paramMap.put("sort", col.get("sort"));
                    sqlDao.executeSql(sql, paramMap);
                }
                // 有参数的话,插入参数类型
                if (argList != null && argList.size() > 0) {
                    sql = "insert into t_sys_export_config_arg values(:id,:configid,:argtype,:sort) ";
                    paramMap.clear();
                    paramMap.put("configid", exportConfig.getId());
                    for (Map arg : argList) {
                        if (arg.get("argtype") == null || StringUtils.isEmpty(arg.get("argtype").toString()) || arg.get("sort") == null || StringUtils.isEmpty(arg.get("sort").toString())) {
                            continue;
                        }
                        paramMap.put("id", IdUtil.simpleUUID());
                        paramMap.put("argtype", arg.get("argtype"));
                        paramMap.put("sort", arg.get("sort"));
                        sqlDao.executeSql(sql, paramMap);
                    }
                }
            }
            returnMap.put("result", "success");
            returnMap.put("message", "保存成功");
        } catch (Exception e) {
            if (returnMap.get("result") != null) {
                returnMap.put("message", e.getMessage());
            } else {
                returnMap.put("message", "保存失败");
            }
            returnMap.put("result", "error");
            e.printStackTrace();
        }
        return returnMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map deleteExportConfig(String id) {
        Map returnMap = new HashMap();
        try {
            // 删除字段映射和参数类型
            String delColSql = "delete from t_sys_export_config_col where configid = :configid ";
            String delArgSql = "delete from t_sys_export_config_arg where configid = :configid ";
            Map paramMap = new HashMap();
            paramMap.put("configid", id);
            sqlDao.executeSql(delColSql, paramMap);
            sqlDao.executeSql(delArgSql, paramMap);
            // 删配置
            configRepository.deleteById(id);
            returnMap.put("result", "success");
            returnMap.put("message", "删除成功");
        } catch (Exception e) {
            if (returnMap.get("result") != null) {
                returnMap.put("message", e.getMessage());
            } else {
                returnMap.put("message", "删除失败");
            }
            returnMap.put("result", "error");
            e.printStackTrace();
        }
        return returnMap;
    }

    @Override
    public ReturnMessageDataList queryExportConfigList(BaseParam baseParam) {
        String sql = "select * from t_sys_export_config where 1=1 ";
        return sqlDao.querySqlDataListOnPage(sql, null, baseParam.getPage());
    }

    @Override
    public Map findExportConfigDetail(String id) {
        Map result;
        String sql = "select * from t_sys_export_config where id = '" + id + "' ";
        result = sqlDao.querySqlDataMap(sql, new HashMap<>());
        // 查字段映射
        String colSql = "select * from t_sys_export_config_col where configid = '" + id + "' order by sort asc ";
        result.put("collist", sqlDao.querySqlDataList(colSql, new HashMap<>()));
        // 查参数类型
        String argSql = "select * from t_sys_export_config_arg where configid = '" + id + "' order by sort asc ";
        result.put("arglist", sqlDao.querySqlDataList(argSql, new HashMap<>()));
        return result;
    }

    @Override
    public void exportData(String moduleCode, String funCode, Object[] args, HttpServletResponse response) throws Exception {
        // 查配置
        TSysExportConfig config = configRepository.findFirstByModulecodeAndFuncode(moduleCode, funCode);
        if (config != null) {
            Map detail = findExportConfigDetail(config.getId());
            List<Map> collist = (List<Map>) detail.get("collist");
            List<Map> arglist = (List<Map>) detail.get("arglist");
            HSSFWorkbook workbook = null;
            List<String> ctitleList = new ArrayList<>();
            List<String> cvalueList = new ArrayList<>();
            for (Map col : collist) {
                ctitleList.add(col.get("ctitle").toString());
                cvalueList.add(col.get("cvalue").toString());
            }
            Class clazz = Class.forName(config.getClassname()); // 加载类
            Object instance = SpringContextHolder.getBean(clazz);
            Class[] typeClass = new Class[arglist.size()];
            if (arglist.size() > 0) {
                for (int i = 0; i < arglist.size(); i++) {
                    switch (arglist.get(i).get("argtype").toString()) {
                        case "Object":
                            typeClass[i] = Object.class;
                            break;
                        case "int":
                        case "Integer":
                            typeClass[i] = int.class;
                            break;
                        case "Map":
                            typeClass[i] = Map.class;
                            break;
                        case "List":
                            typeClass[i] = List.class;
                            break;
                        default:
                            typeClass[i] = String.class;
                            break;
                    }
                }
            }
            Method method = clazz.getDeclaredMethod(config.getMethodname(), typeClass); // 获取方法
            Object invoke = method.invoke(instance, args);
            List<Map> exportList = (List<Map>) invoke;
            workbook = ExcelModelUtil.exp(config.getFunname(), ctitleList, cvalueList, exportList, null);
            FileDownloadUtil.download(workbook, "template.xls", response);
        }
    }
}

TSysExportConfigRepository.java

/**
 * @author bx.yin
 * @date 2020-09-28
 */
public interface TSysExportConfigRepository extends JpaRepository<TSysExportConfig, String>, JpaSpecificationExecutor {

    int countAllByModulecodeAndFuncode(String moduleCode, String funCode);

    int countAllByModulecodeAndFuncodeAndIdNot(String moduleCode, String funCode,String id);

    TSysExportConfig findFirstByModulecodeAndFuncode(String moduleCode, String funCode);
}

TSysExportConfig.java

/**
 1. @author bx.yin
 2. @date 2020-09-28
 */
@Entity
@Data
@Table(name = "t_sys_export_config")
public class TSysExportConfig implements Serializable {

    // 主键
    @Id
    private String id;

    // 模块代码
    private String modulecode;

    // 功能代码
    private String funcode;

    // 模块名称
    private String modulename;

    // 功能名称
    private String funname;

    // 类名全路径
    private String classname;

    // 方法名
    private String methodname;

    public void copy(TSysExportConfig source) {
        BeanUtil.copyProperties(source, this, CopyOptions.create().setIgnoreNullValue(true));
    }
}
  1. 前端调用示例
<template>
 <div class="caozuo">
     <el-button type="primary" icon="el-icon-download" @click="exportData">导出</el-button>
 </div>
</template>

<script>
import { exportData } from '@/api/system-management/exportConfig.js'
export default {
  data() {
    return {
    }
  },
  created() {
  },
  methods: {
    exportData() {
      const args = ['yx', 'root', this.xnxq, this.yx]
      exportData('dd', 'xxyfk-result-total', args, '结果统计.xls').then(res => {
        this.$message({
          message: '导出成功',
          type: 'success'
        })
      })
    }
}
</script>

解析:导出方法exportData传四个参数,第一个是配置的模块code,第二个是配置的功能code,第三个是参数数组(没有参数可以传空数组,具体传参根据实际要调用的方法和配置的参数传),第四个是导出的excel名。

3.呈现结果

样例

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值