Geeting异常发现没有。使用 Apache poi 的 xlsx 文件中的工作表

Geeting exception finding no. of sheets in xlsx files using Apache poi

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();
        }
    }

}

对于上面的代码,它可以运行并无一例外地打印出sheet的数字。我还提供了另一种方法来新建一个Workbook。如果仍然遇到异常,或许你可以尝试另一个 'pure' excel 文件(新建一个 excel 文件并直接保存,不插入任何数据)并再次测试。