程序员的公众号:源1024,获取更多资料,无加密无套路!
最近整理了一波电子书籍资料,包含《Effective Java中文版 第2版》《深入JAVA虚拟机》,《重构改善既有代码设计》,《MySQL高性能-第3版》,《Java并发编程实战》等等
获取方式: 关注公众号并回复 电子书 领取,更多内容持续奉上
概括:
1、使用easypoi导出excel文件
2、行头根据用户选择,动态生成
3、根据key进行列匹配,填充对应列数据
首先导入maven依赖:
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
示例代码:
public void exportExcel(HttpServletResponse response) {
/**
* 组装数据
*/
Map<String, Object> map = new HashMap<>();
map.put("name", "帕克");
map.put("age", "11");
map.put("subject", "语文");
map.put("score", "70");
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "火枪");
map1.put("age", "21");
map1.put("subject", "数学");
map1.put("score", "80");
/**
* maps 存储数据
*/
List<Map<String, Object>> maps = new ArrayList<>();
maps.add(map);
maps.add(map1);
/**
* entityList 存表头,name为列名,key为对应字段,需要跟数据key一一对应
*/
List<ExcelExportEntity> entityList = new ArrayList<>();
entityList.add(new ExcelExportEntity("姓名","name",20));
entityList.add(new ExcelExportEntity("年龄","age",20));
entityList.add(new ExcelExportEntity("学科","subject",20));
entityList.add(new ExcelExportEntity("成绩","score",20));
/**
* 生成workbook
*/
Workbook workbook = ExcelExportUtil.exportExcel(
new ExportParams("标题", "sheet页", ExcelType.XSSF)
, entityList
, maps);
downLoadExcel("test.xlsx",response,workbook);
}
导出下载excel
public void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
ServletOutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
导出文件效果
备注
详细说明请参照官方文档:Easypoi使用文档