ToB企服应用市场:ToB评测及商务社交产业平台

标题: 使用hutool给excel单元格标黄和添加批注 [打印本页]

作者: 忿忿的泥巴坨    时间: 2023-8-29 05:51
标题: 使用hutool给excel单元格标黄和添加批注
  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. }
复制代码
 

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




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4