apache poi 插入带图片的评论 [英] apache poi insert comment with picture

查看:24
本文介绍了apache poi 插入带图片的评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,我正在编辑一个 excel xls 文件.我想要一段代码来演示如何添加包含 png 图像的评论.我已经找到了显示如何向单元格添加注释的示例代码.我不确定如何在评论中添加图片.

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.

推荐答案

我从这个例子开始:https://poi.apache.org/spreadsheet/quick-guide.html(参见 Cell Comments - HSSF 和 XSSF)并找到了 setBackgroundImage 方法.

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;
}   

这篇关于apache poi 插入带图片的评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆