public void export(ObjectDTO dto, HttpServletResponse response) { try { if (ObjectUtils.isEmpty(dto.getObjNumberList())) { throw new BusinessException("编号不允许为空"); } ListResp result = objectService.getListResp(dto); if (ObjectUtils.isEmpty(result) || ObjectUtils.isEmpty(result.getList())) { return; } dto.getColumnList().addAll(getRequiredColumnList()); String encodedFileName = URLEncoder.encode(LocalDate.now().toString() + "-" + dto.getSheetName() + ".xlsx", "UTF-8"); List<T> writeList = convertMapToList(result.getList(), this.entityClass); response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("UTF-8"); response.setHeader("Access-Control-Expose-Headers", "Content-disposition"); response.setHeader("Content-disposition", "attachment;filename=" + encodedFileName + ""); // 自定义策略 Set<Integer> yellowRowsSet = new HashSet<>(getRequiredColumnIndex()); ObjCellWriteHandler seedDemandCellWriteHandler = new ObjCellWriteHandler(yellowRowsSet); // 导出 Excel 文件 EasyExcel.write(response.getOutputStream(), this.entityClass) .sheet(dto.getSheetName()) .includeColumnFiledNames(dto.getColumnList()) .registerWriteHandler(new CustomCellWriteWidthHandle()) /*自适应列宽*/ .registerWriteHandler(seedDemandCellWriteHandler) .doWrite(writeList); } catch (Exception e) { e.printStackTrace(); log.error("对象导出异常,{}", e); } }
public class ObjCellWriteHandler implements CellWriteHandler { /** * 导出字段索引 */ private final Set<Integer> rowIndex; public ObjCellWriteHandler(Set<Integer> rowIndex) { this.rowIndex = rowIndex; } @Override public void afterCellDispose(CellWriteHandlerContext context) { // 判断当前行是否在yellowRowIndex's中 if (context.getHead() && rowIndex.contains(context.getColumnIndex())) { // 设置背景颜色,也可以设置字体等其它元素 WriteCellData<?> cellData = context.getFirstCellData(); WriteCellStyle writeCellStyle = cellData.getOrCreateStyle(); writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); } } }
标签:dto,自定义,rowIndex,EasyExcel,表头,public,result,new,response From: https://www.cnblogs.com/deepalley/p/18278485