基于easypoi的自定义excel表头导出

Love The Way You Lie 2022-04-10 01:49 2079阅读 1赞

easypoi可以实现动态excel表头的定制,但是仅限于2行标题,超过2行就需要通过模板来实现动态配置的功能。

配置模板导出Excel请参照easypoi实现自定义模板导出excel

开发指南:https://opensource.afterturn.cn/doc/easypoi.html

假设要实现这样一个表单导出
demo

第一步:项目中引入Maven依赖

  1. <dependency>
  2. <groupId>cn.afterturn</groupId>
  3. <artifactId>easypoi-base</artifactId>
  4. <version>3.0.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>cn.afterturn</groupId>
  8. <artifactId>easypoi-web</artifactId>
  9. <version>3.0.1</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>cn.afterturn</groupId>
  13. <artifactId>easypoi-annotation</artifactId>
  14. <version>3.0.1</version>
  15. </dependency>

第二步:编写代码

  1. public static void main(String[] args) {
  2. // 表头定义 可以将表头配置在数据库中,然后在代码里动态生成表头
  3. // 这里只是展示如何用代码生成表头
  4. List<ExcelExportEntity> columnList = new ArrayList<ExcelExportEntity>();
  5. ExcelExportEntity colEntity1 = new ExcelExportEntity("序号", "id");
  6. colEntity1.setNeedMerge(true);
  7. columnList.add(colEntity1);
  8. ExcelExportEntity colEntity2 = new ExcelExportEntity("班级", "class");
  9. colEntity2.setNeedMerge(true);
  10. columnList.add(colEntity2);
  11. ExcelExportEntity yhxxGroup = new ExcelExportEntity("用户信息", "yhxx");
  12. List<ExcelExportEntity> yyxxList = new ArrayList<ExcelExportEntity>();
  13. yyxxList.add(new ExcelExportEntity("姓名", "name"));
  14. yyxxList.add(new ExcelExportEntity("年龄", "age"));
  15. yyxxList.add(new ExcelExportEntity("性别", "sex"));
  16. yhxxGroup.setList(yyxxList);
  17. columnList.add(yhxxGroup);
  18. // 数据拉取 一般需要从数据库中拉取
  19. // 这里是手动模拟数据
  20. List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
  21. for (int i = 0; i < 10; i++) {
  22. Map<String, Object> values = new HashMap<>();
  23. values.put("id", i);
  24. values.put("class", "班级" + i);
  25. List<Map<String, Object>> yhxxList = new ArrayList<Map<String, Object>>();
  26. Map<String, Object> yhxxMap = new HashMap<String, Object>();
  27. yhxxMap.put("name", "姓名" + i);
  28. yhxxMap.put("age", "年龄" + i);
  29. yhxxMap.put("sex", "性别" + i);
  30. yhxxList.add(yhxxMap);
  31. values.put("yhxx", yhxxList);
  32. dataList.add(values);
  33. }
  34. // 定义标题和sheet名称
  35. ExportParams exportParams = new ExportParams("班级信息", "人员数据");
  36. Workbook workbook = ExcelExportUtil.exportExcel(exportParams, columnList, dataList);
  37. // 导入到本地目录,如果需要从浏览器导出,参看上一篇文章
  38. FileOutputStream fos = null;
  39. try {
  40. fos = new FileOutputStream("/Users/zqhao/Desktop/班级信息.xls");
  41. workbook.write(fos);
  42. workbook.close();
  43. fos.close();
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. }
  47. }

注意: 表头结构和表头字段名一定要和数据的的结果和数据字段名相对应,否则数据会导不出来。

第三步:运行结果
exportresult


-—————-本文结束感谢您的阅读——————

发表评论

表情:
评论列表 (有 0 条评论,2079人围观)

还没有评论,来说两句吧...

相关阅读