I use an endpoint in order to upload a .xlsx
or .xls
file. After that I am storing the encoded excel file (base64) to a String. In order to parse and handle the values of excel I need to decode that file.
Upload service class:
public BulkUploadResponse validateFile(BulkUploadRequest request) {
final String pfx = String.format("validateFile: ");
BulkUploadResponse response = new BulkUploadResponse();
String delimiters = "\\s |,";
String[] tokensVal = request.getContent().split(delimiters);
String fileContentEncoded = tokensVal[tokensVal.length-1];
InputStream fileContent = new ByteArrayInputStream(new String(Base64.getDecoder().decode(fileContentEncoded), UTF_8).getBytes(UTF_8));
Then I call a class where I convert the data included in excel file parsing as a parameter the fileContent
which is supposed to be decoded.
BulkVignetteCustomer customerVignettes = bulkVignetteCustomerConverter.convert(fileContent);
Finally I use the Workbook
package in order to parse that file
Example:
@Override
public BulkVignetteCustomer convert(InputStream fileContent) {
try {
Workbook wb = WorkbookFactory.create(fileContent);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Sheet sheet = wb.getSheetAt(0);
Iterator rows = sheet.iterator();
(...)
Error that I get:
java.lang.IllegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXML stream at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:89)
Any thoughts on how to decode the file without any errors?
Thank you!
CodePudding user response:
This line seems very strange to me:
InputStream fileContent = new ByteArrayInputStream(new String(Base64.getDecoder().decode(fileContentEncoded), UTF_8).getBytes(UTF_8));
You have an Excel file which isn't plain text but a big binary blob at this stage. Why do you use a String here?
So the binary blob is encoded as Base64. You can directly get the bytes out of the decoder and put them into the ByteArrayInputStream:
InputStream fileContent = new ByteArrayInputStream(Base64.getDecoder().decode(fileContentEncoded));
To verify this part of your application you can store the bytes to a file and try to open it with Excel.