—— 阿尔伯特·爱因斯坦

程序员の奇妙冒险

JavaJavaPOI
2025-04-03 15:27阅读:296评论:0

java EasyExcel自定义表头

ExcelUtils.getResponse 工具类

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
public void exportRecordResult(@RequestParam("templatesId") Long templatesId, HttpServletResponse response) throws Exception {
List<RoutesTaskRecordResultDetailsVO> resultDetailsList = routesTaskRecordResultServiceClient.fetchRecordResultByTemplatesId(templatesId);
if (resultDetailsList == null) {
throw new BusinessException("检查结果记录不存在");
}
 
List<Map<String, Object>> resultListMap = new ArrayList<>();
 
for (RoutesTaskRecordResultDetailsVO routesTaskRecordResultDetailsVO : resultDetailsList) {
// {"输入框":"1","下拉框":"1","是否检查":"是"} 数据导出xlsx ,key为表头,value 为行单元格值
/**
* xlsx
*
* 1 1
*/
Map<String, Object> recordResultMap = JsonMapperUtils.objectToMap(routesTaskRecordResultDetailsVO.getResult());
resultListMap.add(recordResultMap);
}
 
// 收集所有key
Set<String> allKeys = new HashSet<>();
for (Map<String, Object> map : resultListMap) {
allKeys.addAll(map.keySet());
}
 
// 确保每个Map都包含了所有键,缺失的键值设为""
for (Map<String, Object> map : resultListMap) {
for (String key : allKeys) {
if (!map.containsKey(key)) {
map.put(key, "");
}
}
}
List<Map<String, Object>> listMap = new ArrayList<>();
for (Map<String, Object> unsortedMap : resultListMap) {
// 根据key进行排序,避免因为某个Map缺失的键值,补充键值顺序不一致问题
Map<String, Object> sortedMap = unsortedMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue,
LinkedHashMap::new));
listMap.add(sortedMap);
}
// 存储表头
List<List<String>> headList = new ArrayList<>();
// 存储每一行数据
List<List<Object>> list2 = new ArrayList<>();
for (Map<String, Object> map : listMap) {
if (headList.isEmpty()) {
map.forEach((k, v) -> {
headList.add(Collections.singletonList(k));
});
}
List<Object> dataList = new ArrayList<>();
map.forEach((k, v) -> {
if (v instanceof List) {
dataList.add(String.join(",", (List) v));
} else {
dataList.add(v);
}
});
// list2 存储的是 一行数据
list2.add(dataList);
}
 
 
String templateName = resultDetailsList.get(0).getTemplateName();
 
ExcelUtils.getResponse(response, templateName + "-" + DateUtils.dateToStr(new Date(), "yyyyMMddHHmmss"));
 
 
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
 
// 设置表头字体
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontName("宋体");
headWriteFont.setFontHeightInPoints((short) 13);
headWriteFont.setBold(false);
headWriteCellStyle.setWriteFont(headWriteFont);
 
// 去掉表头背景颜色和边框
headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
headWriteCellStyle.setBorderBottom(BorderStyle.THIN);
headWriteCellStyle.setBottomBorderColor(IndexedColors.GREY_25_PERCENT.getIndex());
headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
headWriteCellStyle.setLeftBorderColor(IndexedColors.GREY_25_PERCENT.getIndex());
headWriteCellStyle.setBorderRight(BorderStyle.THIN);
headWriteCellStyle.setRightBorderColor(IndexedColors.GREY_25_PERCENT.getIndex());
headWriteCellStyle.setBorderTop(BorderStyle.THIN);
headWriteCellStyle.setTopBorderColor(IndexedColors.GREY_25_PERCENT.getIndex());
headWriteCellStyle.setWrapped(true);
 
EasyExcel.write(response.getOutputStream())
.head(headList)
.registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, new WriteCellStyle()))
.registerWriteHandler(new DynamicLongestMatchColumnWidthStyleStrategy())
.sheet(templateName)
.doWrite(list2);
}
 
  • ExcelUtils.getResponse 工具类
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Excel
*
* @param response
* @return
*/
public static HttpServletResponse getResponse(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码,所有通过后端的文件下载都可以如此处理
fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
//建议加上该段,否则可能会出现前端无法获取Content-disposition
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
return response;
}
 
评论(0)
暂无评论来抢沙发吧~