package com.ly.cloud.util;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
/**
* @Author
* @Date Created in 2023/12/22 9:30
* @DESCRIPTION: 对 EasyExcel 添加 批注
* @Version V1.0
*/
public class CommentWriteHandler implements RowWriteHandler {
private static final String PI_ZHU = "由系统自动带出,无需修改";
private static final String PI_ZHU_TWO = "如果没有,可以不填;如果有多个审核人,用英文逗号“,”隔开";
@Override
public void afterRowDispose(RowWriteHandlerContext context) {
if (BooleanUtils.isTrue(context.getHead())) {
Sheet sheet = context.getWriteSheetHolder().getSheet();
Drawing<?> drawingPatriarch = sheet.createDrawingPatriarch();
// 假设 drawingPatriarch 是 DrawingPatriarch 对象
// 第一行第二列
Comment comment1 = drawingPatriarch.createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, (short) 1, 0, (short) 2, 1));
comment1.setString(new XSSFRichTextString(PI_ZHU));
// 将批注添加到单元格对象中
sheet.getRow(0).getCell(1).setCellComment(comment1);
// 第一行第四列
Comment comment2 = drawingPatriarch.createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 0, (short) 4, 1));
comment2.setString(new XSSFRichTextString(PI_ZHU));
sheet.getRow(0).getCell(3).setCellComment(comment2);
// 第一行第六列
Comment comment3 = drawingPatriarch.createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, (short) 5, 0, (short) 6, 1));
comment3.setString(new XSSFRichTextString(PI_ZHU_TWO));
sheet.getRow(0).getCell(5).setCellComment(comment3);
// 第一行第七列
Comment comment4 = drawingPatriarch.createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, (short) 6, 0, (short) 7, 1));
comment4.setString(new XSSFRichTextString(PI_ZHU_TWO));
sheet.getRow(0).getCell(6).setCellComment(comment4);
// 第一行第八列
Comment comment5 = drawingPatriarch.createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, (short) 7, 0, (short) 8, 1));
comment5.setString(new XSSFRichTextString(PI_ZHU_TWO));
sheet.getRow(0).getCell(7).setCellComment(comment5);
// 第一行第九列
Comment comment6 = drawingPatriarch.createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, (short) 8, 0, (short) 9, 1));
comment6.setString(new XSSFRichTextString(PI_ZHU_TWO));
sheet.getRow(0).getCell(8).setCellComment(comment6);
// 第一行第十列
Comment comment7 = drawingPatriarch.createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, (short) 9, 0, (short) 10, 1));
comment7.setString(new XSSFRichTextString(PI_ZHU_TWO));
sheet.getRow(0).getCell(9).setCellComment(comment7);
}
}
}
?调用:
//内部finish的时候会自动关闭流
EasyExcel.write(response.getOutputStream(), PzrtExportDto.class)
--添加批注
.inMemory(Boolean.TRUE).registerWriteHandler(new CommentWriteHandler())
.sheet(FILE_NAME)
.doWrite(pzry);
效果图: