基于ModelAndView 导出可自定义字段的Map集合

项目使用的jeecgboot开源框架,里面的autopoi用起来很方便,不方便的是导出的记录是通过类的一系列定义来的,比如导出哪些字段,字段名称是什么,在导出过程中,还要根据字典的字典定义取值,数据量大的时候就出错了,实际使用中,导出一万多条学生记录,学生对象定义中有不到十个字典定义,结果导出一直超时,并且因为是主子表的设计,导出内容不够灵活,需要能让用户选择导出的字段,因此自定义了查询sql,得到mapList,定义了一个ExcelView,把这个map集合传进去。

public class ExcelView extends MiniAbstractExcelView {
    
    
    public ExcelView(){
    
    

    }

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    
    
        String codedFileName = "临时文件";
        Workbook workbook = null;
        String[] exportFields = null;
        Object exportFieldStr = model.get("exportFields");
        if (exportFieldStr != null && exportFieldStr != "") {
    
    
            exportFields = exportFieldStr.toString().split(",");
        }

        if (model.containsKey("mapList")) {
    
    
            List<ExcelExportEntity> list = (List)model.get("mapList"); //maplist 做字段映射用
            if (list.size() == 0) {
    
    
                throw new RuntimeException("MAP_LIST IS NULL");
            }
            workbook = ExcelExportUtil.exportExcel((ExportParams) model.get("params"), list, (Collection) model.get("data"));

        }

        if (model.containsKey("fileName")) {
    
    
            codedFileName = (String)model.get("fileName");
        }

        if (workbook instanceof HSSFWorkbook) {
    
    
            codedFileName = codedFileName + ".xls";
        } else {
    
    
            codedFileName = codedFileName + ".xlsx";
        }

        if (this.isIE(request)) {
    
    
            codedFileName = URLEncoder.encode(codedFileName, "UTF8");
        } else {
    
    
            codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1");
        }

        response.setHeader("content-disposition", "attachment;filename=" + codedFileName);
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
    }
}

控制器中使用:

@RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Student student) {
    
    
        // Step.1 组装查询条件查询数据
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Map map = JSONObject.parseObject(JSONObject.toJSONString(student),Map.class);

        //Step.2 获取导出数据
        List<Map<String,Object>> queryList = studentService.queryStu(map);

        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<Map<String,Object>> studentList = new ArrayList<>();
        if (oConvertUtils.isEmpty(selections)) {
    
    
            studentList = queryList;
        } else {
    
    
            List<String> selectionList = Arrays.asList(selections.split(","));
            studentList = queryList.stream().filter(item -> selectionList.contains(item.get("id"))).collect(Collectors.toList());
        }

        List<Map<String, Object>> dicts = studentService.queryDict(); //获取字典表,这个方法加的有@Cacheable(value = CacheConstant.SYS_DICT_CACHE)
        for(Map<String,Object> xs: studentList ){
    
    
            setMapValue(xs, dicts);//给xs 增加字典字段
        }

        List<ExcelExportEntity> mapList = new ArrayList<ExcelExportEntity>();//这部分可修改为按选择字段导出
        mapList.add(new ExcelExportEntity("院系","yxmc"));
        mapList.add(new ExcelExportEntity("专业","zymc"));
        mapList.add(new ExcelExportEntity("年级","njmc"));
        mapList.add(new ExcelExportEntity("班级","bjmc"));
        mapList.add(new ExcelExportEntity("姓名","xm"));
        mapList.add(new ExcelExportEntity("学号","xh"));
        mapList.add(new ExcelExportEntity("性别","xbm_dictText"));
     
        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new ExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "学生基本信息列表");
        mv.addObject(NormalExcelConstants.MAP_LIST,mapList);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("学生基本信息数据", "导出人:" + sysUser.getRealname(), "学生基本信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, studentList );
        return mv;
    }

前端还是框架的代码:

downFile(this.url.exportXlsUrl, param).then((data) => {
    
    
        if (!data) {
    
    
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
    
    
          window.navigator.msSaveBlob(new Blob([data], {
    
     type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
    
    
          let url = window.URL.createObjectURL(new Blob([data], {
    
     type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })

downFile就是个axios使用

export function downFile(url,parameter){
    
    
  return axios({
    
    
    url: url,
    params: parameter,
    method:'get' ,
    responseType: 'blob'
  })
}

猜你喜欢

转载自blog.csdn.net/wyljz/article/details/108940490