依赖
依赖,该项目是gradle管理依赖,需要maven的可以去maven仓库找一下对应的依赖
implementation 'com.alibaba:easyexcel:2.2.10'
控制层
@Operation(summary = "导出excel")
@GetMapping("/export")
public void exportExcel(@RequestParam String startTime, @RequestParam String endTime, HttpServletResponse response) {
userDownloadStatisticsService.exportExcel(startTime, endTime, response);
}
业务层
public void exportExcel(String startTime, String endTime, HttpServletResponse response) {
LambdaQueryWrapper<UserDownloadStatistics> wrapper = new LambdaQueryWrapper<>();
wrapper.between(UserDownloadStatistics::getDownloadTime, startTime, endTime);
wrapper.orderBy(true, true, UserDownloadStatistics::getDownloadTime);
List<UserDownloadStatistics> statisticsList = list(wrapper);
List<UserStatisticsExcel> excelList = new ArrayList<>();
statisticsList.forEach(date -> excelList.add(new UserStatisticsExcel(date.getDayDownloadNum(), date.getDownloadTime().toString())));
String fileName = startTime + "~" + endTime + ".新增注册用户数.xlsx";
ClassPathResource classPathResource = new ClassPathResource("/template/新增注册用户数.xlsx");
InputStream inputStream = classPathResource.getStream();
try {
ServletOutputStream out = response.getOutputStream();
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).build();
WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
excelWriter.fill(excelList, fillConfig, writeSheet);
excelWriter.finish();
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
模板位置
模板样式
这个只是简单的模板导出,上手即用