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
    poi.apache.org/spreadsheet/quick-guide.html#Images Commented Dec 11, 2016 at 13:35
  • 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 Commented Dec 11, 2016 at 13:55
  • for (Iterator it = lst.iterator(); it.hasNext(); )//The method iterator() is undefined for the type List Commented Dec 11, 2016 at 13:56
  • PictureData pict = (PictureData)it.next();//Cannot cast from void to PictureData Commented Dec 11, 2016 at 13:56
  • String ext = pict.suggestFileExtension();//The method suggestFileExtension() is undefined for the type PictureData Commented 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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.