背景:
網上大部分都不能直接使用,為此總結一個方便入手且可用的工具,用自定義注解實現
依賴包:
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.3.4</version>
</dependency>
實現過程:
1.自定義ExcelRemark注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelRemark {/*** 文本內容*/String value( ) default "";/*** 批注行高, 一般不用設置* 這個參數可以設置不同字段 批注顯示框的高度*/int remarkRowHigh() default 0;/*** 批注列寬, 根據導出情況調整* 這個參數可以設置不同字段 批注顯示框的寬度*/int remarkColumnWide() default 0;
}
2.DTO
public class regionDo {@ExcelProperty("省份")@ExcelRemark(value = "必填")private String province;@ExcelIgnoreprivate String provinceCode;@ExcelProperty("地市")@ExcelRemark(value = "必填")private String city;
}
3.批注處理類
public class CommentCellWriteHandler implements CellWriteHandler {private final Map<Integer, ExcelComment> notationMap;public CommentCellWriteHandler(Map<Integer, ExcelComment> notationMap) {this.notationMap = notationMap;}@Overridepublic void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {//表頭批注if (isHead){Sheet sheet = writeSheetHolder.getSheet();//畫布Drawing<?> drawingPatriarch = sheet.createDrawingPatriarch();if (!CollectionUtils.isEmpty(notationMap) && notationMap.containsKey(cell.getColumnIndex())){ExcelComment excelComment = notationMap.get(cell.getColumnIndex());if (Objects.nonNull(excelComment)){Comment comment = drawingPatriarch.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), 0, (short) excelComment.getRemarkColumnWide(), 1));comment.setString(new XSSFRichTextString(excelComment.getRemarkValue()));cell.setCellComment(comment);}}}}/*** 獲取批注Map**/public static Map<Integer, ExcelComment> getNotationMap(Class<?> clazz) {Map<Integer, ExcelComment> notationMap = new HashMap<>();Field[] fields = clazz.getDeclaredFields();//不使用下面方法,就必須指定@ExcelProperty的indexint index = -1;for (Field field : fields) {++index;if (!field.isAnnotationPresent(ExcelRemark.class)) {//不需要批注 并且 是無需導出字段則 索引回歸if (field.isAnnotationPresent(ExcelIgnore.class)) {--index;}continue;}//批注存放實體ExcelComment excelComment = new ExcelComment();//獲取字段批注注解ExcelRemark ExcelRemark = field.getAnnotation(ExcelRemark.class);excelComment.setRemarkValue(ExcelRemark.value());excelComment.setRemarkColumnWide(ExcelRemark.remarkColumnWide());notationMap.put(index, excelComment);}return notationMap;}}
5.注冊器
EasyExcel.write(response.getOutputStream(), RegionDo.class).registerWriteHandler(new CommentCellWriteHandler(CommentCellWriteHandler.getNotationMap(RegionDo.class))).sheet("sheet1")..doWrite(regionDoList)
引用:
https://blog.csdn.net/qq_43049310/article/details/130697234
https://blog.csdn.net/m0_61013974/article/details/134947917