使用hutool给excel单元格标黄和添加批注

打印 上一主题 下一主题

主题 849|帖子 849|积分 2547

  1. package com.yc.cloud.excel.util;
  2. import cn.hutool.poi.excel.ExcelWriter;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
  5. import org.apache.poi.hssf.usermodel.HSSFRichTextString;
  6. import org.apache.poi.ss.usermodel.*;
  7. import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
  8. import org.apache.poi.xssf.usermodel.XSSFRichTextString;
  9. /**
  10. * Excel工作类扩展
  11. *
  12. * @author wanghuidong
  13. * 时间: 2022/10/10 18:58
  14. */
  15. @Slf4j
  16. public class ExcelUtilExt {
  17.     /**
  18.      * 给单元格标黄
  19.      *
  20.      * @param excelWriter excel写对象
  21.      * @param x           列号
  22.      * @param y           行号
  23.      */
  24.     public static void markCellYellow(ExcelWriter excelWriter, int x, int y) {
  25.         Cell cell = excelWriter.getCell(x, y);
  26.         CellStyle cellStyleSrc = cell.getCellStyle();
  27.         //必须新创建单元格样式,直接修改原单元格样式可能影响到其它单元格,因为样式可以复用的
  28.         CellStyle cellStyleDest = excelWriter.createCellStyle(x, y);
  29.         //原单元格样式不为空,先拷贝原单元格样式至新创建的单元格样式
  30.         if (cellStyleSrc != null) {
  31.             cellStyleDest.cloneStyleFrom(cellStyleSrc);
  32.         }
  33.         cellStyleDest.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  34.         cellStyleDest.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
  35.     }
  36.     /**
  37.      * 给Cell添加批注
  38.      *
  39.      * @param cell   单元格
  40.      * @param value  批注内容
  41.      * @param isXlsx 是否是xlsx格式的文档
  42.      */
  43.     public static void addCellComment(Cell cell, String value, boolean isXlsx) {
  44.         Sheet sheet = cell.getSheet();
  45.         cell.removeCellComment();
  46.         Drawing drawing = sheet.createDrawingPatriarch();
  47.         Comment comment;
  48.         if (isXlsx) {
  49.             // 创建批注
  50.             comment = drawing.createCellComment(new XSSFClientAnchor(1, 1, 1, 1, 1, 1, 1, 1));
  51.             // 输入批注信息
  52.             comment.setString(new XSSFRichTextString(value));
  53.             // 将批注添加到单元格对象中
  54.         } else {
  55.             // 创建批注
  56.             comment = drawing.createCellComment(new HSSFClientAnchor(1, 1, 1, 1, (short) 1, 1, (short) 1, 1));
  57.             // 输入批注信息
  58.             comment.setString(new HSSFRichTextString(value));
  59.             // 将批注添加到单元格对象中
  60.         }
  61.         cell.setCellComment(comment);
  62.     }
  63. }
复制代码
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

忿忿的泥巴坨

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表