在XSSFWorkbook中使用JFileChooser获取java.lang.IllegalStateException:zip文件已关闭

时间:2015-02-06 11:04:24

标签: java

使用JFileChooser选择文件并尝试通过XSSFWorkbook读取它,但我遇到错误,因为java.lang.IllegalStateException:zip文件已关闭。

以下是我收到错误的代码。请帮我解决。

        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(  "xlsx", "xlsx");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(getParent());
        if(returnVal == JFileChooser.APPROVE_OPTION) {
           System.out.println("You chose to open this file: " +
                chooser.getSelectedFile().getName());

        //Create Workbook instance holding reference to .xlsx file
        String filename=chooser.getSelectedFile().getName();
        // getting  java.lang.IllegalStateException: zip file closed
        XSSFWorkbook workbook = new XSSFWorkbook(filename); 

        int numberOfSheets = workbook.getNumberOfSheets();
        for (int i = 0; i < numberOfSheets; i++) {
        XSSFSheet sheet = workbook.getSheetAt(i);
        System.out.println("numberOfSheets :"+numberOfSheets);
        }
     }

1 个答案:

答案 0 :(得分:0)

使用完整的文件名,包括路径:

而不是

String filename=chooser.getSelectedFile().getName();

使用

String filename = chooser.getSelectedFile().getAbsolutePath();