Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Poi 3.13 can't find classes to open XLSX files

I am using apache POI to read and write Excels' files with Java, but I am not able to find WorkbookFactory nor XSSFWorkbook in the sources to read xlsx files.

pom.xml :

<poi.version>3.13</poi.version>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>${poi.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>${poi.version}</version>
</dependency>

I can't find neither any information in the changelog of apache poi that could lead to this behaviour.

Edit: Here my implementation (just a simple method for the moment)

public static HSSFSheet getXLSSheet(String fileName, int sheetIndex) throws IOException {
    InputStream inputStream = new FileInputStream(fileName);
    HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
    return workbook.getSheetAt(sheetIndex);
}

I tried to open an XLSX file but since I can't find the two other classes (WorkbookFactory or XSSFWorkbook) I was expected to have an error like this one:

org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)

Thanks in advance.

like image 852
Maurice Avatar asked Nov 13 '15 12:11

Maurice


1 Answers

First up, I can assure you that the WorkbookFactory and XSSFWorkbook classes are contained in the POI-OOXML 3.13 jars, as documented on the POI site

$ unzip -l .m2/repository/org/apache/poi/poi-ooxml/3.13/poi-ooxml-3.13.jar | grep WorkbookFactory
  6041  2015-09-22 00:22   org/apache/poi/ss/usermodel/WorkbookFactory.class

However, as the exception you have posted makes clear, your code will never work for XLSX files, it needs changing. Well, for that and some other issues too... eg Don't use an InputStream if you have a File

Your code should instead be more like:

import java.io.File;
import org.apache.poi.ss.usermodel.*;

public static Sheet getExcelSheet(String fileName, int sheetIndex) throws IOException {
   File file = new File(fileName);
   Workbook workbook = WorkbookFactory.create(file);
   return workbook.getSheetAt(sheetIndex);
}

That will work for both xls and xlsx files, and will be lower memory than using an input stream. As long as you tell maven to depend on the poi-ooxml jar, you'll get all the other dependencies you need automatically

like image 115
Gagravarr Avatar answered Nov 03 '22 11:11

Gagravarr