创建工作簿Apache POI的一般方法

时间:2014-08-21 07:10:47

标签: java coding-style apache-poi

我有一个使用Apache POI库读取excel表的方法。为了使该方法通用,我需要在catch块中编写一些代码。这是方法:

private List<String[]> readFile(String filePath) throws IOException{
        List<String[]> sheetValues = new ArrayList<String[]>();
        //Two types of fileInputStreams for both the types of workbook i am about to use
        //
        FileInputStream fileInputStream = new FileInputStream(new File(filePath));
        FileInputStream fileInputStream2 = new FileInputStream(new File(filePath));
        LineItemFileReader fileReader = new LineItemFileReaderImpl();
        //If the file is in xls format i should use HSSFWorkbook
        //If the file is in xlsx format i should use XSSFWorkbook
        try {
        //If the file is in xlsx format then the below line will throw the
        //Exception and catch block code will be executed
            HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            sheetValues = fileReader.ParseSheet(workbook.getSheetAt(1),evaluator);
        } catch (OfficeXmlFileException exception){
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream2);
            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            sheetValues = fileReader.ParseSheet(workbook.getSheetAt(1),evaluator);
        } finally{
            fileInputStream.close();
            fileInputStream2.close();
        }
        return sheetValues;
    }

所以这里发生的是我不知道我提供的文件类型。我在上面给出的try / catch块的基础上决定。那么有没有通用的方法来决定使用哪个工作簿?由于上面的代码具有用catch块编写的流控制逻辑,因此这是一种不好的做法。

1 个答案:

答案 0 :(得分:1)

使用WorkbookFactory.create(...)打开Workbook。它将在内部创建适当的子类:

Workbook workbook = WorkbookFactory.create(new File(filePath));
// ...
workbook.close();