无法解码输入流 xls 文件



我使用端点上传.xlsx.xls文件。之后,我将编码的excel文件(base64(存储到一个字符串中。为了解析和处理excel的值,我需要解码该文件。

上传服务类别:

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));

然后,我调用一个类,在该类中,我将excel文件解析中包含的数据转换为参数fileContent,该参数应该被解码。

BulkVignetteCustomer customerVignettes = bulkVignetteCustomerConverter.convert(fileContent);

最后,我使用Workbook包来解析文件

示例:

@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();
(...)

我得到的错误

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)

关于如何在没有任何错误的情况下解码文件,有什么想法吗?

谢谢!

这行对我来说很奇怪:

InputStream fileContent = new ByteArrayInputStream(new String(Base64.getDecoder().decode(fileContentEncoded), UTF_8).getBytes(UTF_8));

在这个阶段,您有一个Excel文件,它不是纯文本,而是一个大的二进制blob。为什么在这里使用字符串?

因此二进制blob被编码为Base64。您可以直接从解码器中取出字节,并将其放入ByteArrayInputStream:

InputStream fileContent = new ByteArrayInputStream(Base64.getDecoder().decode(fileContentEncoded));

若要验证应用程序的这一部分,可以将字节存储到文件中,然后尝试用Excel打开它。

最新更新