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.
-
1poi.apache.org/spreadsheet/quick-guide.html#ImagesAxel Richter– Axel Richter2016-12-11 13:35:58 +00:00Commented 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 Listmayank bisht– mayank bisht2016-12-11 13:55:13 +00:00Commented Dec 11, 2016 at 13:55
-
for (Iterator it = lst.iterator(); it.hasNext(); )//The method iterator() is undefined for the type Listmayank bisht– mayank bisht2016-12-11 13:56:45 +00:00Commented Dec 11, 2016 at 13:56
-
PictureData pict = (PictureData)it.next();//Cannot cast from void to PictureDatamayank bisht– mayank bisht2016-12-11 13:56:58 +00:00Commented Dec 11, 2016 at 13:56
-
String ext = pict.suggestFileExtension();//The method suggestFileExtension() is undefined for the type PictureDatamayank bisht– mayank bisht2016-12-11 13:57:09 +00:00Commented Dec 11, 2016 at 13:57
|
Show 2 more comments
1 Answer
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).