18

I am having troubles with inserting a picture in an excel sheet im making. There are a lot of question about this subject, but I simply cannot figure out what am I doing wrong. My code runs, shows no errors but I do not see an image inserted :(

here is the code:

    InputStream is = new FileInputStream("nasuto_tlo.png");
    byte [] bytes = IOUtils.toByteArray(is); 
    int pictureIndex = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
    is.close();

    CreationHelper helper = wb.getCreationHelper();
    Drawing drawingPatriarch = sheet.createDrawingPatriarch();
    ClientAnchor anchor = helper.createClientAnchor();

    anchor.setCol1(2);
    anchor.setRow1(3);
    Picture pict = drawingPatriarch.createPicture(anchor, pictureIndex);
    pict.resize();

    try {
        FileOutputStream out = new FileOutputStream(root+"/Busotina/Busotina1.xls");
        wb.write(out);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
SteBra
  • 4,188
  • 6
  • 37
  • 68
  • POI has had problems inserting pictures in Word documents so I would think that this is related. – dkatzel Feb 24 '14 at 15:09
  • 1
    Does it work on a new sheet? POI can only add images to a sheet without any existing ones, it won't work if you try to add them to a sheet which already has some on it – Gagravarr Feb 24 '14 at 15:50

1 Answers1

27

the problem is that your anchor is not correct. You need to set all 4 values, because the default ones are 0 - but your first column can not be more right than your second one ;) You'll get negative extent. You should get a warning when you open the excel file that it is corrupt.

So try

anchor.setCol1(2);
anchor.setCol2(3);
anchor.setRow1(3);
anchor.setRow2(4);

A working example from some code I wrote:

// read the image to the stream
final FileInputStream stream =
        new FileInputStream( imagePath );
final CreationHelper helper = workbook.getCreationHelper();
final Drawing drawing = sheet.createDrawingPatriarch();

final ClientAnchor anchor = helper.createClientAnchor();
anchor.setAnchorType( ClientAnchor.MOVE_AND_RESIZE );


final int pictureIndex =
        workbook.addPicture(IOUtils.toByteArray(stream), Workbook.PICTURE_TYPE_PNG);


anchor.setCol1( 0 );
anchor.setRow1( LOGO_ROW ); // same row is okay
anchor.setRow2( LOGO_ROW );
anchor.setCol2( 1 );
final Picture pict = drawing.createPicture( anchor, pictureIndex );
pict.resize();
Mirco
  • 2,940
  • 5
  • 34
  • 57
  • 1
    Hi! I need to insert image not from disk. My image stored in memory in Bitmap array and i dont want to save it on harddrive. Can I insert data from Bitmap array directly to .docx file? – Art B Mar 04 '18 at 12:07
  • Sorry, never worked with docx. But why not? AFAIK poi wants inputstreams and you could use a bytearrayinputstrean – Mirco Mar 09 '18 at 08:09