java 生成excel (多级表头)导出

依赖工具包 

<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.5</version>
</dependency>
</dependencies>
该工具包是对 Apache POI包的分装
    private void export(HttpServletResponse response, String fileName, List<?> projects, List<SummarizeDownloadColumns> columns) throws IOException {
        ExcelWriter bigWriter = ExcelUtil.getBigWriter();
//创建一行空表头占个位置 bigWriter.writeHeadRow(
new LinkedList());
//创建需要展示的的二级表头,{filedName,中文名}
int lastCol = 0; for (int i = 0; i < columns.size(); i++) { if (columns.get(i).getChildren() != null) { for (int j = 0; j < columns.get(i).getChildren().size(); j++) { bigWriter.addHeaderAlias(columns.get(i).getChildren().get(j).getProp(), columns.get(i).getChildren().get(j).getLabel() + columns.get(i).getProp()); bigWriter.setColumnWidth(lastCol++, 30); } } }
//根据需要合并添加第一列表头 bigWriter.merge(
0, 1, 0, 0, columns.get(0).getLabel(), true); bigWriter.merge(0, 0, 1, 14, "第一类(个人)", true); bigWriter.merge(0, 0, 15, 28, "第一类(企业)", true); bigWriter.merge(0, 0, 29, 42, "第二类(个人)", true); bigWriter.merge(0, 0, 43, 56, "第二类(企业)", true); bigWriter.merge(0, 0, 57, 64, "总计项", true); // 只导出配置好的列名 bigWriter.setOnlyAlias(true); bigWriter.write(projects, true); StyleSet styleSet = bigWriter.getStyleSet(); styleSet.setWrapText(); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("filename", URLEncoder.encode(fileName + ".xlsx", "UTF-8")); ServletOutputStream out = response.getOutputStream(); bigWriter.flush(out, true); bigWriter.close(); IoUtil.close(out); }

导出效果

动态生成模板(只需要表头)

      String fileName = "sdjhds";
        try {
            ExcelWriter bigWriter = ExcelUtil.getBigWriter();
            List list = new ArrayList();
            list.add("表头1");
            list.add("表头2");
            bigWriter.writeHeadRow(list);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + ".xls");
            response.setHeader("filename", URLEncoder.encode(fileName, "utf-8") + ".xls");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Content-type", "application/octet-stream;charset=UTF-8");
            ServletOutputStream out = response.getOutputStream();
            bigWriter.flush(out, true);
            bigWriter.close();
            IoUtil.close(out);
        } catch (IOException e) {
            e.printStackTrace();
        }

 

 

 




posted @ 2021-03-05 19:26  挖坑大王  阅读(5533)  评论(0编辑  收藏  举报