我正在使用 Apache POI 来读取 xsl 文件。我的pom文件更新:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.0</version>
</dependency>
我的代码:
public List<String> getSheetNames(String fileLocation) throws Exception {
FileInputStream file = new FileInputStream(new File(fileLocation));
Workbook workbook = null;
try {
workbook = new XSSFWorkbook(file);
} catch (Exception e) {
e.printStackTrace();
}
//do something with read lines
}
这对于某些文件来说效果很好。但是,对于其他人来说,它会抛出此错误:
org.apache.commons.compress.archivers.zip.UnsupportedZipFeatureException: Unsupported feature compression method used in entry ...
...
at org.apache.commons.compress.archivers.zip.ZipUtil.checkRequestedFeatures(ZipUtil.java:353)
at org.apache.commons.compress.archivers.zip.ZipArchiveInputStream.read(ZipArchiveInputStream.java:514)
at java.io.FilterInputStream.read(FilterInputStream.java:133)
at org.apache.poi.openxml4j.util.ZipArchiveThresholdInputStream.read(ZipArchiveThresholdInputStream.java:80)
at org.apache.poi.util.IOUtils.toByteArray(IOUtils.java:185)
at org.apache.poi.util.IOUtils.toByteArray(IOUtils.java:153)
at org.apache.poi.util.IOUtils.toByteArray(IOUtils.java:140)
at org.apache.poi.openxml4j.util.ZipArchiveFakeEntry.<init>(ZipArchiveFakeEntry.java:72)
at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource.<init>(ZipInputStreamZipEntrySource.java:98)
at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:132)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:312)
at org.apache.poi.ooxml.util.PackageHelper.open(PackageHelper.java:59)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:304)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:300)
此错误的修复方法是什么?我在网上找不到太多帮助。
更新:这现在不适用于任何文件。
像这样进行更改。如果文件是 xls 类型,则必须使用 HSSFWorkbook obj 来读取它
public List<String> getSheetNames(String fileLocation) throws Exception{
File inputFile = new File(fileLocation);
FileInputStream fis = new FileInputStream(inputFile);
Workbook workbook = null;
try {
if (inputFile.getName().endsWith(".xlsx")) {
workbook = new XSSFWorkbook(fis);
} else if (inputFile.getName().endsWith(".xls")) {
workbook = new HSSFWorkbook(fis);
} else{
fis.close();
throw new IOException("This file extension type is not supported!");
}
} catch (Exception e) {
e.printStackTrace();
}
//do something with read lines
}