InvalidFormatException in Java POI

2020-04-23 04:56发布

This is the exception I am getting:

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

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.

My code:

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 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.

1条回答
够拽才男人
2楼-- · 2020-04-23 05:35

Promoting some comments to an answer

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.

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

.

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 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.

查看更多
登录 后发表回答