日期:2014-05-17  浏览次数:20788 次

POI操作EXCEL的问题,添加批注,设置背景色不成功,请指教。
读取一个现有的excel文件,对每行数据验证,在出错的地方加上批注,设置背景色,然后保存成另外一个文件,代码如下:
String fileName = "resource.xls";

POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(
"D:\\upload\\"
+ fileName));
HSSFWorkbook resourceFile = new HSSFWorkbook(fs);
// TODO 验证处理

// 单位工作表
HSSFSheet shOrg = resourceFile.getSheet("Sheet1");
if (shOrg == null) {
return;
}
int lastRowNum = shOrg.getLastRowNum();// 取得最后一行
HSSFRow curRow = null;
HSSFCell curCell = null;
HSSFComment comment = null;
HSSFCellStyle cellStyle = null;
// 创建HSSFPatriarch对象,HSSFPatriarch是所有注释的容器.
HSSFPatriarch patr = shOrg.createDrawingPatriarch();
for (int rowNum = 1; rowNum <= lastRowNum; rowNum++) {
curRow = shOrg.getRow(rowNum);
// 单位名称
curCell = curRow.getCell(0);
// 添加单元格注释
// 定义注释的大小和位置,详见文档
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0,
(short) 3, 3, (short) 5, 6);

comment = patr.createCellComment(anchor);
// 设置注释内容
comment.setString(new HSSFRichTextString(" 单位名称不正确! "));
comment.setAuthor("test");
curCell.setCellComment(comment);

// 设置单元格背景
cellStyle = resourceFile.createCellStyle();
cellStyle.setFillBackgroundColor(HSSFColor.DARK_RED.index);
curCell.setCellStyle(cellStyle);

}

// 保存文件
String outputFileName = "error_resource.xls";
FileOutputStream stream = new FileOutputStream(new File(
"D:\\upload\\"
+ outputFileName));
resourceFile.write(stream);
stream.close();

------解决方案--------------------

public static void main(String[] args) throws IOException { 
  //创建工作簿对象 
  HSSFWorkbook wb=new HSSFWorkbook(); 
  //创建工作表对象 
  HSSFSheet sheet=wb.createSheet("我的工作表"); 
  //创建绘图对象 
  HSSFPatriarch p=sheet.createDrawingPatriarch(); 
  //创建单元格对象,批注插入到4行,1列,B5单元格 
  HSSFCell cell=sheet.createRow(4).createCell(1); 
  //插入单元格内容 
  cell.setCellValue(new HSSFRichTextString("批注")); 
  //获取批注对象 
  //(int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2) 
  //前四个参数是坐标点,后四个参数是编辑和显示批注时的大小. 
  HSSFComment comment=p.createComment(new HSSFClientAnchor(0,0,0,0,(short)3,3,(short)5,6)); 
  //输入批注信息 
  comment.setString(new HSSFRichTextString("插件批注成功!插件批注成功!")); 
  //添加作者,选中B5单元格,看状态栏 
  comment.setAuthor("toad"); 
  //将批注添加到单元格对象中 
  cell.setCellComment(comment); 
  //创建输出流 
  FileOutputStream out=new FileOutputStream("writerPostil.xls");