如何使用apache poi为3个单元格设置注释

时间:2010-10-04 13:43:19

标签: java apache-poi

我想使用Apache POI为3个Excel单元格设置注释。

这是我的源代码:

import java.io.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;

public class CellComments
{
    public static void main(String[] args) throws IOException  {

      HSSFWorkbook wb = new HSSFWorkbook();
      HSSFSheet sheet = wb.createSheet("Cell comments in POI HSSF");


      HSSFPatriarch patr = sheet.createDrawingPatriarch();
      HSSFCell cell1 = sheet.createRow(3).createCell((short)1);
      cell1.setCellValue(new HSSFRichTextString("Hello, World"));

      //anchor defines size and position of the comment in worksheet
      HSSFComment comment1 = patr.createComment(new HSSFClientAnchor(100, 100, 100, 100, (short)1, 1, (short) 6, 5));
      comment1.setString(new HSSFRichTextString("FirstComments"));
      cell1.setCellComment(comment1);
      System.out.println("Cell comments: "+cell1.getCellComment().getString());

      patr = sheet.createDrawingPatriarch();
      comment1 = patr.createComment(new HSSFClientAnchor(100, 100, 100, 100, (short)1, 1, (short) 6, 5));
      //HSSFComment comment2=patr.createComment(new HSSFClientAnchor(100, 100, 100, 100, (short)1, 1, (short) 6, 5));
      HSSFCell cell2 = sheet.createRow(6).createCell((short)1);
      cell2.setCellValue(36.6);
      comment1.setString(new HSSFRichTextString("second commetns"));
      cell2.setCellComment(comment1);
      System.out.println("Cell comments: "+cell2.getCellComment().getString());

      patr = sheet.createDrawingPatriarch();
      comment1 = patr.createComment(new HSSFClientAnchor(100, 100, 100, 100, (short)1, 1, (short) 6, 5));
      //HSSFComment comment3=patr.createComment(new HSSFClientAnchor(100, 100, 100, 100, (short)1, 1, (short) 6, 5));
      cell2 = sheet.createRow(10).createCell((short)1);
      cell2.setCellValue(150);
      comment1.setString(new HSSFRichTextString("Third commetns"));
      cell2.setCellComment(comment1);
      System.out.println("Cell comments: "+cell2.getCellComment().getString());

      FileOutputStream out = new FileOutputStream("C:/Documents and Settings/saravanan/Desktop/cellcomments.xls");
      wb.write(out);
      out.close();

    }
}

在运行程序时,注释仅针对最后一个单元格设置。但是我打印了前两个单元格的评论。但是没有在excel表中显示?这里有什么不对?

1 个答案:

答案 0 :(得分:5)

有一次你问了一个问题让我试了一段时间。

您的问题是此行显示3次,每次评论前一次。

patr = sheet.createDrawingPatriarch();

此方法来自the docs

  

创建顶级绘图   族长。这将产生效果   删除任何现有的图纸   这张表。

因此,每次创建DrawingPatriarch时都会删除您之前的注释。

所以在comment1之前只做一次。另外2次,删除或注释掉这一行。