int sheets = 0;
try {
Workbook book = WorkbookFactory.create(file);
sheets = book.getNumberOfSheets();
book.close(); //Exception occurs in this line
} catch (Exception e) {
logger.warn(e.getMessage());
throw new Exception("exception in readding number of sheets", e.getCause());
}
return sheets;
我得到这个异常:
org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException: Fail to save: an error occurs while saving the package : part.
是否有解决此异常的方法?
最佳答案
这是我在 poi 3.11 版本上测试的结果,正如您在评论中所说。
你的代码对我来说工作得很好!
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class POITest {
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("F:\\test.xlsx");
int sheets = 0;
try {
Workbook book = WorkbookFactory.create(file);
sheets = book.getNumberOfSheets();
System.out.println(sheets);
book.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
InputStream file2 = new FileInputStream("F:\\test.xlsx");
Workbook book = new XSSFWorkbook(file2);
sheets = book.getNumberOfSheets();
System.out.println(sheets);
book.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
对于上面的代码,它可以毫无异常(exception)地运行并打印出页数。我还提供了另一种新建工作簿
的方法。如果您仍然遇到异常,也许您可以尝试另一个“纯”Excel 文件(新建一个 Excel 文件并直接保存而不插入任何数据)并再次测试。
关于java - 遇到异常,发现没有。使用 Apache poi 的 xlsx 文件中的工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29738853/