从具有空白单元格的excel文件读取到2d数组

时间:2015-06-04 15:05:27

标签: java excel apache-poi

我有一个以下代码,从第二行开始从xls文件读取登录名和密码(它跳过列名)并将其写入二维数组。但它只有在工作表中没有任何行中的空白单元格时才有效。我该怎么做才能让它与空单元一起工作?



private static Object[][] getUsersFromXls(String sheetName) {
        final File excelFile = new File("src//resources//TestData.xls");
        FileInputStream fileInputStream;

        try {
            fileInputStream = new FileInputStream(excelFile);
            workbook = new HSSFWorkbook(fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        sheet = workbook.getSheet(sheetName);

        final int numberOfRows = sheet.getLastRowNum();
        final int numberOfColumns = sheet.getRow(0).getLastCellNum();

        final String[][] xlsData = new String[numberOfRows][numberOfColumns];
        String cellValue;

        for (int i = 1; i <= numberOfRows; i++) {
            final HSSFRow row = sheet.getRow(i);

            for (int j = 0; j < numberOfColumns; j++) {
                final HSSFCell cell = row.getCell(j);
                final int cellType = cell.getCellType();

                if (cellType == HSSFCell.CELL_TYPE_FORMULA) {
                    throw new RuntimeException("Cannot process a formula. Please change field to result of formula.");
                } else {
                    cellValue = String.valueOf(cell);
                    xlsData[i - 1][j] = cellValue;
                }
            }
        }
        return xlsData;
    }
&#13;
&#13;
&#13;

0 个答案:

没有答案