公司有个需求要实现大屏页面统计数据的导出功能,要求支持多个sheet,一个sheet支持多个表格的模板导出,故先写了个demo,以供参考。(注:项目已引入的poi工具包为3.2.0版本)。预先设定的导出模板如下:
具体代码:
controller
/**
* 大数据地图统计-总下载
*
* @param res
*/
@PostMapping("/export/analyse")
public void exportAnalyse(HttpServletResponse res, @RequestBody StatisticsVo vo) {
service.exportAnalyse(res, vo);
}
service
public void exportAnalyse(HttpServletResponse response, StatisticsVo vo) {
try {
// 获取workbook对象
// 单sheet或多sheet 只需要更改此处即可
Workbook workbook = exportMoreSheetByTemplate() ;
// 设置excel的文件名称
String excelName = "大数据地图总体下载" ;
// 重置响应对象
response.reset();
// 当前日期,用于导出文件名称
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String dateStr = "["+excelName+"-"+sdf.format(new Date())+"]";
// 指定下载的文件名--设置响应头
response.setHeader("Content-Disposition", "attachment;filename=" +dateStr+".xls");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 写出数据输出流到页面
OutputStream output = response.getOutputStream();
BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
workbook.write(bufferedOutPut);
bufferedOutPut.flush();
bufferedOutPut.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 模版多sheet导出示例
* @return
*/
public Workbook exportMoreSheetByTemplate() throws IOException {
List<Map<String, Object>> list1 = Lists.newArrayList();
List<Map<String, Object>> list2 = Lists.newArrayList();
List<Map<String, Object>> list3 = Lists.newArrayList();
// 手动创建导出数据,需根据具体业务进行查询
for (int i=0;i<3;i++){
Map<String, Object> map = new HashMap<String, Object>();
map.put("content", "张三" + i);
map.put("value", i);
list1.add(map);
}
for (int j=0;j<6;j++){
Map<String, Object> map2 = Maps.newHashMap();
map2.put("name", "赵四" + j);
map2.put("age", j);
list2.add(map2);
}
for (int k=0;k<4;k++){
Map<String, Object> map3 = Maps.newHashMap();
map3.put("address", "刘能" + k);
map3.put("phone", k);
list3.add(map3);
}
// sheet1内容
Map<String,Object> map1 = new HashMap<String, Object>() ;
map1.put("list",list1) ;
map1.put("resultList",list3) ;
// sheet2内容
map1.put("lists",list2) ;
// 设置导出配置
// 获取导出excel指定模版
File file1 = new File("zhzf-check/build/resources/main/doc/map/wholeAnalyse.xlsx");
String realPath = file1.getCanonicalPath();
TemplateExportParams params = new TemplateExportParams(realPath,true);
// 设置sheetName,若不设置该参数,则使用得原本得sheet名称
// String[] sheetNameArray = {"执法分析","整体趋势"} ;
// params.setSheetName(sheetNameArray);
// 导出excel
return ExcelExportUtil.exportExcel(params , map1 );
}
结果展示:
使用postman调用,结果如下图:
搞定!求关注求三连,感谢感谢!