syy*_*syy 5 java excel apache-poi
我正在尝试读取 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?为什么程序永远不会移动到下一行?
我不明白为什么程序一直停止,所以我降级到 3.9 版本并让代码正常工作。感谢Gagravarr,我能够通过摆脱整个getWorkbook()方法和FileInputStream类来减少内存的使用。
改成workbook = getWorkbook()这样:
workbook = WorkbookFactory.create(new File(excelFilePath));
Run Code Online (Sandbox Code Playgroud)
它将创建适当的XSSFWorkbook或HSSFWorkbook.
来源:WorkbookFactory.create(...)