easyExcel导出多sheet页,及动态表头

首先引入jar包

       
                com.alibaba
                easyexcel
                2.1.6
            

这里给看下server实现成方法

    public void exportLedger(HttpServletRequest request, HttpServletResponse response, ProcessBimRate processBimRate) {
//        processBimRate.setUpdateOrgId(getChangeOrgId());
        List list = processBimRateDao.checkLedgerList(processBimRate);
        //1、根据子分部名称分组统计
        Map> listMap = list.stream()
                .collect(Collectors.groupingBy(ProcessBimRate::getLayerFourName));

        //导出
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            // 这里URLEncoder.encode可以防止中文乱码 导出文件名称
            String fileName = URLEncoder.encode("检验批台账", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //新建ExcelWriter
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();

            //遍历listMap 写入多个sheet页
            int i = 0;
            for (Map.Entry> entry : listMap.entrySet()) {
                //获取sheet对象
                //表头list的生成
                List> headList = new ArrayList>();
                List head0 = new ArrayList();
                head0.add(entry.getValue().get(0).getLayerTwoName()+"检验批台账");//第一列
                head0.add("工程名称: "+entry.getValue().get(0).getLayerThreeName());//第二列
                head0.add("日期");//第三列
                List head1 = new ArrayList();
                head1.add(entry.getValue().get(0).getLayerTwoName()+"检验批台账");//第一列
                head1.add("工程名称: "+entry.getValue().get(0).getLayerThreeName());//第二列
                head1.add("部位");//第三列
                headList.add(head0);
                headList.add(head1);

                //生成sheet页
                WriteSheet mainSheet = EasyExcel.writerSheet(i, entry.getValue().get(0).getLayerFourName()).head(headList)//i为第几个sheet页,从0开始;entry.getValue().get(0).getLayerFourName()为sheet名称
                        .registerWriteHandler(new SimpleColumnWidthStyleStrategy(30)) // 简单的列宽策略,列宽20
                        .registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 30, (short) 20))// 简单的行高策略:头行高30,内容行高20
                        .build();
                List voList = entry.getValue().stream()
                        .map(item -> new ProcessBimRateVo(DateUtil.dateToStr(item.getCreateTime(), "yyyy-MM-dd"), item.getLayerFiveName()))
                        .collect(Collectors.toList());
                //获取模型信息,向sheet写入数据
                excelWriter.write(voList, mainSheet);
                i++;
            }
            //关闭流
            excelWriter.finish();

        } catch (IOException e) {
            log.error("导出异常{}", e.getMessage());
        }
    }

你可能感兴趣的:(java,服务器)