我正在尝试读取 Excel 工作簿 (.xlsx
),但程序在初始化 Workbook
时停止。我不确定发生了什么,因为它没有给出任何错误。
当我说停止时,我的意思是程序只是暂停。它仍在运行,但我感觉它卡住了,不确定。
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader
{
private String excelFilePath;
private FileInputStream inputStream;
private Workbook workbook;
private Sheet sheet;
// Constructors
public ExcelReader() {
try {
// Get path to excel workbook and put in stream
excelFilePath = "/home/flow/project/mydata.xlsx";
inputStream = new FileInputStream(new File(excelFilePath));
// Get type of workbook (Excel 2003 or Excel 2007+)
workbook = getWorkbook();
} catch (Exception e) {
e.printStackTrace();
}
}
// Get type of workbook (Excel 2003 or Excel 2007+)
private Workbook getWorkbook() {
Workbook work = null;
try {
if(excelFilePath.endsWith("xlsx")) {
System.out.println("In firstIf"); // Prints this
work = new XSSFWorkbook(inputStream); // Gets stuck here
System.out.println("After XSSF"); // Never prints this
}
else if(excelFilePath.endsWith("xls")) {
work = new HSSFWorkbook(inputStream);
}
else
throw new IllegalArgumentException("The specified file is not an Excel file");
} catch (Exception e) {
e.printStackTrace();
}
return work;
}
}
我做错了什么?为什么程序永远不会移动到下一行?
最佳答案
我还注意到暂停,我的意思是程序只是在 XSSFWorkbook 正在初始化的那一行暂停。我发现类路径中缺少几个 jar 文件。在我的例子中,以下 jars 不在类路径中:
curvesapi-1.03.jar
xmlbeans-2.6.0.jar
奇怪的是,Java 运行时没有抛出类未找到异常。相反,Java 运行时卡在 XSSFWorkbook 构造函数上。
POI 分发中的所有 jar 都应该添加到类路径中
poi-3.14-20160307.jar
poi-excelant-3.14-20160307.jar
poi-ooxml-3.14-20160307.jar
poi-ooxml-schemas-3.14-20160307.jar
poi-scratchpad-3.14-20160307.jar
commons-codec-1.10.jar
commons-logging-1.2.jar
junit-4.12.jar
log4j-1.2.17.jar
curvesapi-1.03.jar
xmlbeans-2.6.0.jar
关于java - 程序停止尝试读取 Excel 工作簿 (Apache POI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37949857/