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#Images– Axel RichterDec 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– mayank bishtDec 11, 2016 at 13:55
-
for (Iterator it = lst.iterator(); it.hasNext(); )//The method iterator() is undefined for the type List– mayank bishtDec 11, 2016 at 13:56
-
PictureData pict = (PictureData)it.next();//Cannot cast from void to PictureData– mayank bishtDec 11, 2016 at 13:56
-
String ext = pict.suggestFileExtension();//The method suggestFileExtension() is undefined for the type PictureData– mayank bishtDec 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
).