有的时候,我们需要通过操作Apache POI,在生成Cell数据的同时,能对其生成的Cell,加上注解(comments),类似于下面的。
那么对于这种情况,我们的代码应该如何写呢? 借花献佛,我就用Apache POI官方提供的例子,然后加上一些注解,给大家看一下。本例子的测试代码是基于POI-3.12的。
执行完后,将会生成上图所示的Excel工作表单(sheet)
- importorg.apache.poi.ss.usermodel.*;
- importorg.apache.poi.xssf.usermodel.XSSFSheet;
- importorg.apache.poi.xssf.usermodel.XSSFWorkbook;
- importjava.io.IOException;
- importjava.io.FileOutputStream;
- /**
- *Demonstrateshowtoworkwithexcelcellcomments.
- *<p>
- *Excelcommentisakindofatextshape,
- *soinsertingacommentisverysimilartoplacingatextboxinaworksheet
- *</p>
- *
- *@authorYegorKozlov
- */
- publicclassCellComments{
- publicstaticvoidmain(String[]args)throwsIOException{
- //1.创建一个工作簿对象
- XSSFWorkbookwb=newXSSFWorkbook();
- //2.得到一个POI的工具类
- CreationHelperfactory=wb.getCreationHelper();
- //3.创建一个工作表
- XSSFSheetsheet=wb.createSheet();
- //4.得到一个换图的对象
- Drawingdrawing=sheet.createDrawingPatriarch();
- //5.ClientAnchor是附属在WorkSheet上的一个对象,其固定在一个单元格的左上角和右下角.
- ClientAnchoranchor=factory.createClientAnchor();
- //6.创建一个单元格(2A单元格)
- Cellcell0=sheet.createRow(1).createCell(0);
- //6.1.对这个单元格设置值
- cell0.setCellValue("Test");
- //6.2.对这个单元格加上注解
- Commentcomment0=drawing.createCellComment(anchor);
- RichTextStringstr0=factory.createRichTextString("Hello,World!");
- comment0.setString(str0);
- comment0.setAuthor("ApachePOI");
- cell0.setCellComment(comment0);
- //7.创建一个单元格(4F单元格)
- Cellcell1=sheet.createRow(3).createCell(5);
- //7.1.对这个单元格设置值
- cell1.setCellValue("F4");
- //7.2.对这个单元格加上注解
- Commentcomment1=drawing.createCellComment(anchor);
- RichTextStringstr1=factory.createRichTextString("Hello,World!");
- comment1.setString(str1);
- comment1.setAuthor("ApachePOI");
- cell1.setCellComment(comment1);
- //8.创建一个单元格(4F单元格)
- Cellcell2=sheet.createRow(2).createCell(2);
- cell2.setCellValue("C3");
- Commentcomment2=drawing.createCellComment(anchor);
- RichTextStringstr2=factory.createRichTextString("XSSFcansetcellcomments");
- //9。为注解设置字体
- Fontfont=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("ApachePOI");
- comment2.setColumn(2);
- comment2.setRow(2);
- //10.保存成Excel文件
- Stringfname="comments.xlsx";
- FileOutputStreamout=newFileOutputStream(fname);
- wb.write(out);
- out.close();
- }
- }