首先需要把获取到的数据转化成List格式
然后通过创建ExcelWriter对象把List格式的数据写进去
最后设置文件格式后直接导出
@Override
public void dataSourceDownload(String progressId, HttpServletResponse response) {
//从内存中获取数据,可换成读取数据库拿数据
Element element = cache.get(progressId);
Map objectValue = (Map) element.getObjectValue();
List<DataAnalyseDto> exportList = (List<DataAnalyseDto>) objectValue.get("alreadyData");
// 创建ExcelWriter对象
ExcelWriter excelWriter = EasyExcel.write("DataAnalyse.xlsx", DataAnalyseDto.class).build();
// 创建WriteSheet对象
WriteSheet writeSheet = EasyExcel.writerSheet("分析数据").build();
// 将数据写入Excel
excelWriter.write(exportList, writeSheet);
// 关闭ExcelWriter对象
excelWriter.finish();
// 设置为导出件格式为excel
// response.setContentType("application/vnd.ms-excel");
// response.setCharacterEncoding("utf-8");
String filePrefix = "分析数据文件";
try {
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode(filePrefix, "UTF-8").replaceAll("\\+", "%20");
//Content-disposition 的 attachment参数将文件作为附件下载
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), DataAnalyseDto.class).sheet("模板").doWrite(exportList);
} catch (Exception e) {
log.error("下载文件失败!", e.getMessage());
} finally {
cache.remove(progressId);
}
log.info("下载数据大小为:{}", exportList.size());
}