java EasyExcel自定义表头

 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 工具类
/**
 * 设置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;
}
posted @ 2025-04-03 15:27  程序员の奇妙冒险  阅读(215)  评论(0)    收藏  举报