首页 > 解决方案 > InputStream 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)

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

谢谢!

标签: javaexcelspringrest

解决方案


这条线对我来说似乎很奇怪:

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

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

所以二进制 blob 被编码为 Base64。您可以直接从解码器中获取字节并将它们放入 ByteArrayInputStream:

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

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


推荐阅读