在springboot2.x中利用jxls设置excel模板导出excel

1、添加依赖

<dependency>
      <groupId>net.sf.jxls</groupId>
      <artifactId>jxls-core</artifactId>
      <version>1.0.3</version>
</dependency>

2、excel模板
在这里插入图片描述
模板存放路径
在这里插入图片描述

3、代码块

@ResponseBody
    @RequestMapping("/exportScience/{printData}")
    public  ResponseEntity<byte[]>  exportScienceInfo(@PathVariable("printData") String params, HttpServletRequest request) throws Exception {
        
        Map<String, Object> condition = JSON.parseObject(params);
        String volumeType = String.valueOf(condition.get("volumeType"));
        String currentUserName = String.valueOf(condition.get("currentUserName"));
        String name = "";
        if ("1".equals(volumeType)) {
            name = "清单111";
        }else{
            name = "清单222";
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Map<String,Object> dataMap = new HashMap<>();

        String path = request.getServletContext().getRealPath("/");


        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");

        //String srcFilePath = ServletActionContext.getServletContext().getRealPath("WEB-INF/template/aaa.xls");
        //String srcFilePath = request.getServletContext().getRealPath("/finishedBorrowWaitTemplate.xls");
        List<BorrowTaskDto> list = borrowTaskService.getScienceInfo(condition);


        Map<String, List<BorrowTaskDto>> groupListMap = list.stream().collect(Collectors.groupingBy(BorrowTaskDto::getApplyUid));
        Set<String> keySet = groupListMap.keySet();


        int num = 1;
        for (String k : keySet) {
            //List<BorrowTaskDto> tempList = groupListMap.get(k).stream().sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime())).collect(Collectors.toList());
            List<BorrowTaskDto> tempList = groupListMap.get(k);
            for (int i = 0; i < tempList.size(); i++) {
                tempList.get(i).setNumber(i + 1);
                tempList.get(i).setApplyTimeStr(dateFormat.format(tempList.get(i).getApplyTime()));
            }
            UserDto printUser = new UserDto();
            printUser.setUserNo(tempList.get(0).getUserNo());
            printUser.setUserName(tempList.get(0).getApplyName());
            printUser.setOrgName(tempList.get(0).getOrgName());
            printUser.setCellphone(tempList.get(0).getUserCellPhone());
            printUser.setAddress(tempList.get(0).getUserAddress());
            dataMap.put("user"+num,printUser);
            dataMap.put("list"+num,tempList);
            dataMap.put("num",num);
            num++;

        }

        File sfile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "template/borrowChecklist/checkList10.xls");
        //File sfile = ResourceUtils.getFile("D:\\program\\jaf\\src\\main\\resources\\template\\borrowChecklist\\checkList10.xls");
        String srcFilePath = sfile.getAbsolutePath();



        // 公共部分
        dataMap.put("admin",currentUserName);
        dataMap.put("date", dateFormat.format(new Date()));





        XLSTransformer transformer = new XLSTransformer();
        File exportFile =  new File(String.format("%s%s.%s",path,name,"xls"));//File.createTempFile(String.format("%s%s",path,name), ".xls");
        transformer.transformXLS(srcFilePath, dataMap, exportFile.getAbsolutePath());



        String filename = String.format("%s.%s",name,"xls");
        File file = new File(path+filename);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名,解决中文名称乱码问题
        String downloadFileName = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        //通知浏览器以attachment(下载方式)打开图片
        headers.setContentDispositionFormData("attachment", downloadFileName);
        //application/octet-stream:二进制流数据(最常见的文件下载)
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //201 HttpStatus.CREATED
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }

导出结果:
本次导出的excel中和模板一样,一共有10个sheet,有数据的sheet1 和sheet2, 其余的sheet3到sheet10没数据留白
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
以上存在两个待优化项:
1、模板里面需要建固定个sheet(需要打10个,所以要10个sheet)不是动态的
2、在Linux上打出会报错,报取不到模板文件的错误

优化:
1、模板优化:sheet个数不在固定,可以动态生成
在这里插入图片描述
2、在Linux也可以找到模板文件
代码

  @ResponseBody
    @RequestMapping("/exportScience/{printData}")
    public  void exportScienceInfo(@PathVariable("printData") String params, HttpServletRequest request,HttpServletResponse response) throws Exception {
     
        Map<String, Object> condition = JSON.parseObject(params);
        String volumeType = String.valueOf(condition.get("volumeType"));
        String currentUserName = String.valueOf(condition.get("currentUserName"));
        String name = "";
        if ("1".equals(volumeType)) {
            name = "清单111.xls";
        }else{
            name = "清单222.xls";
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String path = request.getServletContext().getRealPath("/");
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");

        List<BorrowTaskDto> list = borrowTaskService.getScienceInfo(condition);
        Map<String, List<BorrowTaskDto>> groupListMap = list.stream().collect(Collectors.groupingBy(BorrowTaskDto::getApplyUid));
        Set<String> keySet = groupListMap.keySet();
        ArrayList<Map<String,Object>> objects = new ArrayList<>();
        List<String> sheetNameList = new ArrayList<String>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("admin",currentUserName);
        map.put("date", dateFormat.format(new Date()));

        int num = 0;
        for (String k : keySet) {
            List<BorrowTaskDto> tempList = groupListMap.get(k);
            for (int i = 0; i < tempList.size(); i++) {
                tempList.get(i).setNumber(i + 1);
                tempList.get(i).setApplyTimeStr(dateFormat.format(tempList.get(i).getApplyTime()));
            }
            UserDto printUser = new UserDto();
            printUser.setUserNo(tempList.get(0).getUserNo());
            printUser.setUserName(tempList.get(0).getApplyName());
            printUser.setOrgName(tempList.get(0).getOrgName());
            printUser.setCellphone(tempList.get(0).getUserCellPhone());
            printUser.setAddress(tempList.get(0).getUserAddress());
            Map<String,Object> dataMap = new HashMap<>();
            sheetNameList.add(tempList.get(0).getApplyName());// sheet的名称
            dataMap.put("user",printUser);
            dataMap.put("subList",tempList);
            objects.add(dataMap);
            map.put("list"+num,tempList );

            num++;

        }


        ClassPathResource classPathResource = new ClassPathResource("template/borrowChecklist/checkList10.xls");

        //File sfile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "template/borrowChecklist/checkList10.xls");
        //FileInputStream fis = new FileInputStream(sfile);;
//这种方式 在linux下可以找到模板文件流
        InputStream inputStream = classPathResource.getInputStream();
       
        OutputStream outputStream=new FileOutputStream(String.format("%s%s.%s",path,"checkList10","xls"));
        int b=0;
        while((b=inputStream.read())!=-1){
            outputStream.write(b);
        }
        inputStream.close();
        outputStream.close();

        //FileInputStream fis = new FileInputStream(classPathResource.getFile());;
        FileInputStream fis = new FileInputStream(String.format("%s%s.%s", path, "checkList10", "xls"));


        OutputStream out = null;
        String contentType = "application/vnd.ms-excel";
        response.setContentType(contentType);

        String downloadFileName = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        response.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Cache-Control", "public");
        response.setHeader("Expires", "0");
        response.setHeader("Content-Transfer-Encoding", "binary");

        XLSTransformer transformer = new XLSTransformer();
        																				// 这里的list,是map中存放的list
        Workbook  workbook = transformer.transformMultipleSheetsList(fis, objects, sheetNameList, "list", map, 0);

        out = response.getOutputStream();
        workbook.write(out);
        out.flush();
        out.close();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值