我正在使用apache POI来通过Java读取和写入Excel的文件,但是我无法在源中找到WorkbookFactory或XSSFWorkbook来读取xlsx文件。
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>
我在apache poi的变更日志中找不到任何可能导致此行为的信息。
编辑:这是我的实现(目前只是一种简单的方法)
public static HSSFSheet getXLSSheet(String fileName, int sheetIndex) throws IOException {
InputStream inputStream = new FileInputStream(fileName);
HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
return workbook.getSheetAt(sheetIndex);
}
我试图打开XLSX文件,但是由于找不到其他两个类(WorkbookFactory或XSSFWorkbook),所以我会遇到类似以下的错误:
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)
提前致谢。
首先,我可以向您保证POI网站上记录的WorkbookFactory
和XSSFWorkbook
类包含在POI-OOXML 3.13 jar中
$ 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
但是,正如您发布的例外所明确指出的那样,您的代码将永远无法用于XLSX
文件,需要对其进行更改。好吧,对于这个以及其他一些问题……例如,如果您有文件,请不要使用InputStream
您的代码应该更像是:
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);
}
这将同时适用于xls
和xlsx
文件,并且比使用输入流的内存要少。只要您告诉maven依赖poi-ooxml
jar,就会自动获得所有其他需要的依赖
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句