【发布时间】:2019-02-12 00:46:34
【问题描述】:
使用 apache-POI 打开一个 Excel 工作簿,如果它不存在则创建一个。 由于某种原因,正在打开的工作簿已损坏,导致在带有错误注释的行上发生错误。
不知何故,围绕这部分代码的 try/catch 似乎没有激活。任何想法为什么,以及如何正确处理这些错误?
另外,有没有办法在我的if(file.exists() && file.length() != 0) {有条件的时候检查文件的完整性?
public XSSFWorkbook OpenWB(String directory, String name) {
File file = new File(directory + "\\" + name + ".xlsx");
FileInputStream fIP;
if(file.exists() && file.length() != 0) {
try {
fIP = new FileInputStream(file);
//Get the workbook instance for XLSX file
workbook = new XSSFWorkbook(fIP); //*********error occurs here**********
fIP.close();
System.out.println(name + ".xlsx file open successfully.");
return workbook;
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error to open " + name + ".xlsx file, creating blank");
//Create Blank workbook
workbook = new XSSFWorkbook();
Integer i = 0;
while (file.isFile() && file.exists()) {
name = name.concat(i.toString());
file = new File(directory + "\\" + name + ".xlsx");
i++;
}
return workbook;
}
} else {
System.out.println("Error to open " + name + ".xlsx file, creating blank");
//Create Blank workbook
workbook = new XSSFWorkbook();
return workbook;
}
}
【问题讨论】:
-
你得到了什么异常?
标签: java excel error-handling apache-poi