Reputation: 23
I have an application where I am editing an excel xls file. I would like a snippet of code to demonstrate how to add a comment containing a png image. I already found sample code showing how to add a comment to a cell. I am unsure how to add a picture to the comment.
Upvotes: 1
Views: 1006
Reputation: 23
I started with this example: https://poi.apache.org/spreadsheet/quick-guide.html (see Cell Comments - HSSF and XSSF) and found the setBackgroundImage method.
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;
}
Upvotes: 1