如何在 Apache POI 的 HSSFCell 中添加图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1125488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 17:54:21  来源:igfitidea点击:

how to add images in HSSFCell in apache POI?

javaapacheexcelspreadsheet

提问by Garudadwajan

How to add Image in different different HSSFCell object in poi ?

如何在 poi 的不同不同 HSSFCell 对象中添加图像?

I have written some code which is adding image but problem is, the cell were I added last image, That cell only showing image other than that no other cells are showing images ...

我已经编写了一些添加图像的代码,但问题是,我添加了最后一张图像的单元格,该单元格仅显示图像,而没有其他单元格显示图像...

appreciate your help ...

感谢你的帮助 ...

My Code is

我的代码是

while(rs.next()){

    HSSFCell cell = getHSSFCell(sheet, rowNo, cellNo);

    cell.setCellValue(new HSSFRichTextString(rs.getString("TEST_STEP_DETAILS")) );
    cell.setCellStyle(style);

    String annotate = rs.getString("ANNOTATE");

    if(annotate != null){                       
        int index = getPicIndex(wb);
        HSSFPatriarch patriarch=sheet.createDrawingPatriarch();
        HSSFClientAnchor anchor = new HSSFClientAnchor(400,10,655,200,(short)cellNo,(rowNo+1),(short)cellNo,(rowNo+1));
        anchor.setAnchorType(1);
        patriarch.createPicture(anchor, index);                                         
    }
    cellNo++;
}

getPicIndex METHOD :-

getPicIndex 方法:-

public static int getPicIndex(HSSFWorkbook wb){
    int index = -1;
    try {
        byte[] picData = null;
        File pic = new File( "C:\pdf\logo.jpg" );
        long length = pic.length(  );
        picData = new byte[ ( int ) length ];
        FileInputStream picIn = new FileInputStream( pic );
        picIn.read( picData );
        index = wb.addPicture( picData, HSSFWorkbook.PICTURE_TYPE_JPEG );
    } catch (IOException e) {
        e.printStackTrace();
    }  catch (Exception e) {
        e.printStackTrace();
    } 
    return index;
}

采纳答案by Christian

i hope you found the solution yourself. if not:
the problem is that you create for every image a new partiarch. HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
you should create only one patriarch instance and use its createPicture method for all images.

我希望你自己找到了解决方案。如果不是:
问题在于您为每个图像创建了一个新的成员。 HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
您应该只创建一个族长实例,并为所有图像使用其 createPicture 方法。