Java POI 中的 InvalidFormatException [英] InvalidFormatException in Java POI

查看:42
本文介绍了Java POI 中的 InvalidFormatException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我得到的例外:

org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]

我试图打开的文件是一个 .xls 文件,我搜索了可能的解决方案,我找到了 this这个,但我我已经正确地做到了这一点,所以这不是问题.

The file I am trying to open is an .xls file, I searched for possible solutions, I found this and this, but I am already doing this correctly, so this is not the problem.

我的代码:

InputStream file = new FileInputStream(new File(path));
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(sheetNumber);

sheetNumber 是一个整数(在我的软件中它总是 0)并且路径是正确的,我在发布之前测试了这两次,以确保我没有失败.抛出异常的行是:

sheetNumber is an int (It´s always 0 in my software) and the path is correct, I tested these two many times before posting this, to make sure I am not failing there. The line that is throwing the exception is:

org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);

(如果你想了解更多关于代码的细节,你可以找到整个类这里)

(If you want more details on the code, you can find the whole class Here)

有谁知道我哪里会失败?谢谢大家.

Does anyone know where can I be failing? Thank you all.

推荐答案

将一些评论提升为答案

您的第一个问题是您使用的 Apache POI 版本.如果您要使用 POI 3.15 beta 1 或更新版本,在这种情况下您会得到一个更有帮助的异常.

Your first issue is the version of Apache POI you're using. If you were to use POI 3.15 beta 1 or newer, you'd get a much more helpful Exception in this situation.

在 POI 3.15 beta 1 和更新版本中,您将获得 ODFNotOfficeXmlFileException 带有如下消息:

In POI 3.15 beta 1 and newer, you'll get a ODFNotOfficeXmlFileException with a message like:

ODFNotOfficeXmlFileException: The supplied data appears to be in ODF (Open Document) Format. Formats like these (eg ODS, ODP) are not supported, try Apache ODFToolkit

.

实际上,您可以通过使用 --detect 模式下的 Apache Tika CLI 应用程序.如您所见,这给出了 application/vnd.oasis.opendocument.spreadsheet,它是一个 OpenDocument 格式电子表格,通常带有 .ods 扩展名.所以,有人将 .ods 文件重命名为 .xlsx,虽然它可能会让 Excel 打开它,但不会神奇地改变格式!

As it is, you can find (and have found, thanks!) out what your file really is by using the Apache Tika CLI App in --detect mode. As you found, that gave application/vnd.oasis.opendocument.spreadsheet which is an OpenDocument Format Spreadsheet, normally with the .ods extension. So, someone has renamed the .ods file to .xlsx, which while it may make Excel open it, doesn't magically change the format!

Apache POI 不支持 ODF 格式,因此您需要将文件转换为真正的 Excel 格式,或者使用类似 Apache ODF Toolkit 来处理它.

Apache POI doesn't support the ODF formats, so you'll either need to convert the file to a true Excel format, or use something like Apache ODF Toolkit to process it.

这篇关于Java POI 中的 InvalidFormatException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆