Apache POI插入图像

我正在插入一个图片在excel表im正在制作的麻烦。 关于这个问题有很多问题,但我根本搞不清楚我做错了什么。 我的代码运行,显示没有错误,但我没有看到一个图像插入:(

这里是代码:

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

问题是你的锚是不正确的。 你需要设置所有的4个值,因为默认值是0–但是你的第一列不能比第二个更好;)你会得到负的范围。 当你打开它损坏的excel文件时,你应该得到一个警告。

所以试试

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

从我写的一些代码的一个工作示例:

 // 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();