how to add images in HSSFCell in apache POI?

14,084

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.

Share:
14,084
Garudadwajan
Author by

Garudadwajan

Updated on June 14, 2022

Comments

  • Garudadwajan
    Garudadwajan almost 2 years

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

    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 :-

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