多表导出结合easyExcel
https://blog.csdn.net/L1569850979/article/details/110671240
导出工具类
/**
* 一键导出所有数据多个sheet
* @author zhenhuaxiang
*/
public void downloadAll(HttpServletResponse response, Map<String,List<?>> map, String fileNames) throws IOException {
if (ObjectUtils.isEmpty(map)) {
throw new RuntimeException();
}
if (StringUtils.isEmpty(fileNames)) {
fileNames = new Date().toString();
}
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode(fileNames, "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
int sheetNo = 0;
for (Map.Entry<String,List<?>> entry:map.entrySet()
) {
String sheetName = entry.getKey();
List<?> list = entry.getValue();
excelWriter.write(list, EasyExcel.writerSheet(sheetNo,sheetName).head(list.get(0).getClass()).build());
sheetNo++;
}
// 关闭流
excelWriter.finish();
} catch (Exception e) {
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> hashMap = new HashMap<String, String>(16);
hashMap.put("status", "failure");
hashMap.put("message", "下载文件失败" + e.getMessage());
response.getWriter().println(JSON.toJSONString(map));
}
}
使用示例
/**
* 一键导出所有数据多个sheet
*/
public void downloadAll(HttpServletResponse response, String examId) throws IOException {
if (StringUtils.isEmpty(examId)) {
throw new BusinessException(2002, "请选择考试批次!!!");
}
Map<String, List<?>> map = new HashMap<>(16);
List<SchoolOneTwoScore> listOne = getSchoolOneTwoScores(examId);
List<CityBatchOnline> listTwo = getCityBatchOnlines(examId);
List<CitySingleScore> listThree = getCitySingleScores(examId);
List<CitySubjectScore> listFour = getCitySubjectScores(examId);
List<TotalScoreSubsection> listFive = scoreDownService.getTotalScoreSubsections(examId, AdsSubsection.ONESTR);
List<TotalScoreSubsection> listSix = scoreDownService.getTotalScoreSubsections(examId, AdsSubsection.TWOSTR);
List<SchoolSubjectCompare> listSeven = scoreDownService.getSchoolSubjectCompares(examId);
map.put("学校一段二段统计表", listOne);
map.put("全市批次上线统计表", listTwo);
map.put("全市单科成绩统计表", listThree);
map.put("全市学科一分一段表", listFour);
map.put("全市总分一分一段表(原始成绩)", listFive);
map.put("全市总分一分一段表(赋分成绩)", listSix);
map.put("学校学科对比表-等级分布", listSeven);
easyExcelUtil.downloadAll(response, map, "全表导出");
}
注意list中的实体使用了easyExcel注解