Apache POI method "addPicture" doesn't work for me
I am having a problem inserting an image into an Excel workbook with Apache POI (version 3.7). Here's my code:
private static void createAndFillWorkbook() {
FileOutputStream out = null;
FileInputStream in = null;
try {
HSSFWorkbook workbook = new HSSFWorkbook();
File picture = new File("D:\\pngPict.png");
byte[] buf = new byte[(int) picture.length()];
in = new FileInputStream(picture);
in.read(buf);
workbook.addPicture(buf, Workbook.PICTURE_TYPE_PNG);
out = new FileOutputStream("D:\\Book3.xls");
workbook.write(out);
} catch (Exception e) {
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
It doesn't work (I'm using the .xls file format) and I'm not sure why.
The main problem is Apache poi addPicture
api depends on the general apache codec. Download the jar commons-codec-1.6
from this location http://commons.apache.org/codec/download_codec.cgi and put the jar in your class.
It should work. Also try examples of examples of adding images to Excel
http://poi.apache.org/spreadsheet/quick-guide.html#Images
There is also a working code example here
http://www.codemiles.com/java/image-insert-in-excel-file-using-poi-t1340.html
Hope this helps!