基于easypoi的自定义excel表头导出
easypoi可以实现动态excel表头的定制,但是仅限于2行标题,超过2行就需要通过模板来实现动态配置的功能。
配置模板导出Excel请参照easypoi实现自定义模板导出excel
开发指南:https://opensource.afterturn.cn/doc/easypoi.html
假设要实现这样一个表单导出
第一步:项目中引入Maven依赖
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.0.1</version>
</dependency>
第二步:编写代码
public static void main(String[] args) {
// 表头定义 可以将表头配置在数据库中,然后在代码里动态生成表头
// 这里只是展示如何用代码生成表头
List<ExcelExportEntity> columnList = new ArrayList<ExcelExportEntity>();
ExcelExportEntity colEntity1 = new ExcelExportEntity("序号", "id");
colEntity1.setNeedMerge(true);
columnList.add(colEntity1);
ExcelExportEntity colEntity2 = new ExcelExportEntity("班级", "class");
colEntity2.setNeedMerge(true);
columnList.add(colEntity2);
ExcelExportEntity yhxxGroup = new ExcelExportEntity("用户信息", "yhxx");
List<ExcelExportEntity> yyxxList = new ArrayList<ExcelExportEntity>();
yyxxList.add(new ExcelExportEntity("姓名", "name"));
yyxxList.add(new ExcelExportEntity("年龄", "age"));
yyxxList.add(new ExcelExportEntity("性别", "sex"));
yhxxGroup.setList(yyxxList);
columnList.add(yhxxGroup);
// 数据拉取 一般需要从数据库中拉取
// 这里是手动模拟数据
List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
for (int i = 0; i < 10; i++) {
Map<String, Object> values = new HashMap<>();
values.put("id", i);
values.put("class", "班级" + i);
List<Map<String, Object>> yhxxList = new ArrayList<Map<String, Object>>();
Map<String, Object> yhxxMap = new HashMap<String, Object>();
yhxxMap.put("name", "姓名" + i);
yhxxMap.put("age", "年龄" + i);
yhxxMap.put("sex", "性别" + i);
yhxxList.add(yhxxMap);
values.put("yhxx", yhxxList);
dataList.add(values);
}
// 定义标题和sheet名称
ExportParams exportParams = new ExportParams("班级信息", "人员数据");
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, columnList, dataList);
// 导入到本地目录,如果需要从浏览器导出,参看上一篇文章
FileOutputStream fos = null;
try {
fos = new FileOutputStream("/Users/zqhao/Desktop/班级信息.xls");
workbook.write(fos);
workbook.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
注意: 表头结构和表头字段名一定要和数据的的结果和数据字段名相对应,否则数据会导不出来。
第三步:运行结果
-—————-本文结束感谢您的阅读——————
还没有评论,来说两句吧...