I want to read Excel files which I get passed over REST as InputStream
. For this I have the class ExcelImport
:
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
public class ExcelImport {
public boolean readStream(InputStream stream) {
boolean success;
try {
byte[] bytes = getBytes(stream);
InputStream wrappedStream = new ByteArrayInputStream(bytes);
Workbook workbook = WorkbookFactory.create(wrappedStream);
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
Sheet sheet = workbook.getSheetAt(i);
for (Row row : sheet) {
IterateThroughRow(row);
}
}
success = true;
} catch (FileNotFoundException e) {
success = false;
e.printStackTrace();
} catch (IOException e) {
success = false;
e.printStackTrace();
} catch (InvalidFormatException e) {
success = false;
e.printStackTrace();
}
return success;
}
private void IterateThroughRow(Row row) {
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
//do something with the content...
case Cell.CELL_TYPE_STRING:
cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
cell.getBooleanCellValue();
break;
default:
}
}
}
public static byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int len;
byte[] data = new byte[100000];
while ((len = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, len);
}
buffer.flush();
return buffer.toByteArray();
}
}
If I run this with this:
ExcelImport excelImport = new ExcelImport();
InputStream is = new FileInputStream("/path/to/file.xlsx");
excelImport.readStream(is);
It works fine. But if I use this class with a InputStream
from a PUT
over REST I get this Exception:
java.lang.IllegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXML stream
I wrap the stream because if I don't do it, I get this Exception: Package should contain a content type part
. I got this from here.
Isn't it possible to read Excel files using Apache POI with a Stream from REST? Or am I doing something else wrong?