有的時候,我們需要通過操作Apache POI,在生成Cell數據的同時,能對其生成的Cell,加上注解(comments),類似於下面的。
那么對於這種情況,我們的代碼應該如何寫呢? 借花獻佛,我就用Apache POI官方提供的例子,然后加上一些注解,給大家看一下。本例子的測試代碼是基於POI-3.12的。
執行完后,將會生成上圖所示的Excel工作表單(sheet)
- import org.apache.poi.ss.usermodel.*;
- import org.apache.poi.xssf.usermodel.XSSFSheet;
- import org.apache.poi.xssf.usermodel.XSSFWorkbook;
- import java.io.IOException;
- import java.io.FileOutputStream;
- /**
- * Demonstrates how to work with excel cell comments.
- * <p>
- * Excel comment is a kind of a text shape,
- * so inserting a comment is very similar to placing a text box in a worksheet
- * </p>
- *
- * @author Yegor Kozlov
- */
- public class CellComments {
- public static void main(String[] args) throws IOException {
- //1.創建一個工作簿對象
- XSSFWorkbook wb = new XSSFWorkbook();
- //2.得到一個POI的工具類
- CreationHelper factory = wb.getCreationHelper();
- //3. 創建一個工作表
- XSSFSheet sheet = wb.createSheet();
- //4.得到一個換圖的對象
- Drawing drawing = sheet.createDrawingPatriarch();
- //5. ClientAnchor是附屬在WorkSheet上的一個對象, 其固定在一個單元格的左上角和右下角.
- ClientAnchor anchor = factory.createClientAnchor();
- //6. 創建一個單元格(2A單元格)
- Cell cell0 = sheet.createRow(1).createCell(0);
- //6.1. 對這個單元格設置值
- cell0.setCellValue("Test");
- //6.2. 對這個單元格加上注解
- Comment comment0 = drawing.createCellComment(anchor);
- RichTextString str0 = factory.createRichTextString("Hello, World!");
- comment0.setString(str0);
- comment0.setAuthor("Apache POI");
- cell0.setCellComment(comment0);
- //7. 創建一個單元格(4F單元格)
- Cell cell1 = sheet.createRow(3).createCell(5);
- //7.1. 對這個單元格設置值
- cell1.setCellValue("F4");
- //7.2. 對這個單元格加上注解
- Comment comment1 = drawing.createCellComment(anchor);
- RichTextString str1 = factory.createRichTextString("Hello, World!");
- comment1.setString(str1);
- comment1.setAuthor("Apache POI");
- cell1.setCellComment(comment1);
- //8. 創建一個單元格(4F單元格)
- Cell cell2 = sheet.createRow(2).createCell(2);
- cell2.setCellValue("C3");
- Comment comment2 = drawing.createCellComment(anchor);
- RichTextString str2 = factory.createRichTextString("XSSF can set cell comments");
- //9。為注解設置字體
- Font font = wb.createFont();
- font.setFontName("Arial");
- font.setFontHeightInPoints((short)14);
- font.setBoldweight(Font.BOLDWEIGHT_BOLD);
- font.setColor(IndexedColors.RED.getIndex());
- str2.applyFont(font);
- comment2.setString(str2);
- comment2.setAuthor("Apache POI");
- comment2.setColumn(2);
- comment2.setRow(2);
- //10. 保存成Excel文件
- String fname = "comments.xlsx";
- FileOutputStream out = new FileOutputStream(fname);
- wb.write(out);
- out.close();
- }
- }