0

I am working with Apache POI. I am able to read data from excel, but unable to read image from the excel. How to read image from excel.

7
  • 1
  • I read that image guide and also tried executing it. I got these errors --> List lst = workbook.getAllPictures();//Type mismatch: cannot convert from List<HSSFPictureData> to List Dec 11, 2016 at 13:55
  • for (Iterator it = lst.iterator(); it.hasNext(); )//The method iterator() is undefined for the type List Dec 11, 2016 at 13:56
  • PictureData pict = (PictureData)it.next();//Cannot cast from void to PictureData Dec 11, 2016 at 13:56
  • String ext = pict.suggestFileExtension();//The method suggestFileExtension() is undefined for the type PictureData Dec 11, 2016 at 13:57

1 Answer 1

2

Instead of puzzling around let's have a complete example.

import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.PictureData;

import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.util.List;
import java.util.Iterator;

class ReadExcelImages {

 public static void main(String[] args) throws Exception{

  InputStream inp = new FileInputStream("test.xls");
  //InputStream inp = new FileInputStream("test.xlsx");

  Workbook workbook = WorkbookFactory.create(inp);

  List lst = workbook.getAllPictures();
  int i = 1;
  for (Iterator it = lst.iterator(); it.hasNext(); ) {
   PictureData pict = (PictureData)it.next();
   String ext = pict.suggestFileExtension();
   byte[] data = pict.getData();
   if (ext.equals("png")){
    FileOutputStream out = new FileOutputStream("pict" + i++ + ".png");
    out.write(data);
    out.close();
   } else if (ext.equals("jpeg")) {
    FileOutputStream out = new FileOutputStream("pict" + i++ + ".jpeg");
    out.write(data);
    out.close();
   }
  }
 }
}

Works for me with HSSF (*.xls) as well as with XSSF (*.xlsx).

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.