DhanushD DhanushD - 1 year ago 147
Java Question

Apache POI All Image Insert to Excel failing due to one corrupt image

I have prepared a code which fetches bytes from the database field storing image as BLOB and inserting the same into an excel file using apache poi version 3.9

This code works fine and the images are being pulled and anchored to the column and row specified in most cases.

Here is the code :

Blob img = ads.getPhoto();
byte[] imageByte = ads.getPhoto().getBytes(1, (int) img.length());
if (imageByte.length > 10) {
try {
int picId = workbook.addPicture(imageByte, workbook.PICTURE_TYPE_JPEG);
CreationHelper helper = workbook.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setRow2(rowId + 1);
Picture pict = drawing.createPicture(anchor, picId);
System.out.println("TEST PRINT");
} catch (Exception ex) {

Now I have narrowed down to one image that is causing an issue. The blob looks ok to me. But when all the images along with this particular image is inserted all the images are removed and the excel opens with the error message: "File Error: Data May have been lost"

None of the images in the Drawing Patriarch are displayed in the excel.
If I skip this particular row the images are displayed fine in the excel. Its just with this particular image.

Can any one help me out with a way to check if there is an error in one of the drawings and skip it if found so that rest of the images stay and only this image is removed.

Any suggestions with this would help a lot.
Thanks in advance.

Answer Source

Switching to XSSF worked for this scenario. Corrupt image is displayed with and invalid image icon. And all others still populate properly.

But the performance of XSSF is very poor using poi.3.15..

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download