需要导出的表头有一行是统计时间,需要导出时动态生成.
导出实体类,创建createHead方法,手写表头,动态生成第二行表头统计日期
@Data
public class ExportEntity {
@ExcelIgnore
private String id;
private String projectCode;
private String areaName;
private String projectName;
private String organizationUnit;
private BigDecimal totalFund;
private BigDecimal projectProgress;
private BigDecimal fundProgress;
public List<List<String>> createHead() {
List<List<String>> head = new ArrayList<>();
Date date = new Date();
String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
head.add(Arrays.asList("统计表", "统计日期:" + dateStr, "项目基本信息", "项目编号"));
head.add(Arrays.asList("统计表", "统计日期:" + dateStr, "项目基本信息", "城市"));
head.add(Arrays.asList("统计表", "统计日期:" + dateStr, "项目基本信息", "项目名称"));
head.add(Arrays.asList("统计表", "统计日期:" + dateStr, "项目基本信息", "单位"));
head.add(Arrays.asList("统计表", "统计日期:" + dateStr, "资金信息", "总金额"));
head.add(Arrays.asList("统计表", "统计日期:" + dateStr, "资金信息", ")"));
head.add(Arrays.asList("统计表", "统计日期:" + dateStr, "进度", "项目进度"));
head.add(Arrays.asList("统计表", "统计日期:" + dateStr, "进度", "资金进度"));
return head;
}
}
导出方法
public static void writeExcel(HttpServletResponse response, String filename, Class header, List dataList, List<List<String>> head) {
log.info("开始写excel文件,文件名:{}", filename);
log.info("header==",header);
response.setCharacterEncoding("utf-8");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
String fileName;
try {
fileName = URLEncoder.encode(filename+".xlsx", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
EasyExcel.write(response.getOutputStream(), header)
.autoCloseStream(Boolean.FALSE)
.head(head)//添加表头
.sheet("sheet1").doWrite(dataList);
} catch (IOException e) {
log.info("写excel失败,异常栈信息:{}", e);
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = new HashMap<String, String>();
map.put("status", "failure");
map.put("message", "导出失败" + e.getMessage());
try {
response.getWriter().println(JSON.toJSONString(map));
} catch (IOException ioException) {
log.info("写excel失败,异常栈信息:{}", e);
}
}
}