java - 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)
关于如何在没有任何错误的情况下解码文件的任何想法?
谢谢!
解决方案
这条线对我来说似乎很奇怪:
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 打开它。
推荐阅读
- amazon-web-services - eb 部署错误:TypeError - 无法连接“str”和“NoneType”对象
- python - 运行 docker-compose up 时出现 Errno 13
- php - 计算php中日期之间的百分比
- javascript - 使用 Ajax 调用修改 DOM 后 JS 函数不起作用
- ruby-on-rails - 提交表单时出错:嵌套属性不允许参数
- swift - Swift 的 Int 扩展中的 max(_:_:) 和 min(_:_:)
- r - 左对齐图但保持实际大小
- python-3.x - 有没有办法防止 scipy.stats.gamma 为这些参数生成锯齿状的 pdf?
- python - 使用 Python 中的字典理解将字典的元组键解包为单个键
- html - 解决 HTML 中的重叠元素