我有一个应用程序,我正在编辑一个excel xls文件。我想要一段代码来演示如何添加包含png图像的注释。我已经找到了示例代码,显示了如何向单元格添加注释。我不确定如何在评论中添加图片。
答案 0 :(得分:1)
我从这个例子开始:https://poi.apache.org/spreadsheet/quick-guide.html(参见Cell Comments - HSSF和XSSF)并找到了setBackgroundImage方法。
HSSFPatriarch patriarch;
HSSFClientAnchor anchor;
HSSFCreationHelper factory;
HSSFComment comment;
ByteArrayOutputStream baos;
HSSFCell cell;
HSSFRow row;
int picIndex;
.
.
.
baos = getPicture2(lda.getRecNo());
if(baos != null) {
picIndex = wb.addPicture(baos.toByteArray(),
HSSFWorkbook.PICTURE_TYPE_JPEG);
/* add comment with picture in it */
int c = cell.getColumnIndex();
int r = cell.getRowIndex();
anchor = factory.createClientAnchor();
anchor.setCol1(c);
anchor.setCol2(c+4);
anchor.setRow1(r);
anchor.setRow2(r+8);
comment = patriarch.createCellComment(anchor);
//richTextString = factory.createRichTextString("optional text will appear on top of picture");
//comment.setString(richTextString);
//comment.setAuthor("Apache POI");
comment.setBackgroundImage(picIndex); // set picture as background image
cell.setCellComment(comment);
Log.v(TAG, "added comment to row: " +
String.valueOf(r) +
" col: " + String.valueOf(c));
}
.
.
.
/*
* get picture from product from picture number
*/
public ByteArrayOutputStream getPicture2(int picNo) {
String fileSpec;
FileInputStream picFileInputStream;
File picFile;
//long picLength;
byte[] picData = null;
ByteArrayOutputStream baos = null;
int b;
try {
baos = new ByteArrayOutputStream();
fileSpec = "put your directory and filename here";
picFile = new File(fileSpec);
picFileInputStream = new FileInputStream(fileSpec);
if(picFile.exists()) {
while((b=picFileInputStream.read()) != -1) {
baos.write(b);
}
picData = IOUtils.toByteArray(picFileInputStream);
picFileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return baos;
}