Reputation: 651
I have a problem with inserting a picture 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's not working(I'm using the .xls file format) and I'm not sure why.
Upvotes: 4
Views: 7362
Reputation: 6608
Main issue is Apache poi addPicture
api depends on apache common codec.Download the jar commons-codec-1.6
from this location http://commons.apache.org/codec/download_codec.cgi and place the jar in your class path.
It should work . Also try sample examples of adding Pictures to an Excel
http://poi.apache.org/spreadsheet/quick-guide.html#Images
There is also a sample working code here
http://www.codemiles.com/java/image-insert-in-excel-file-using-poi-t1340.html
Hope this helps !!
Upvotes: 4