Apache POI读取第一行,但是会抛出空指针exception

嗨,我有一个3行1列的Excel表。 每个行在Excel中都包含一个通用格式的十位数字。 这是我写的代码,

public class Tempclass { public static void main(String[] args) throws Exception { int[][] data; data = excelRead(); for (int i = 0; i < data.length; i++) { finddetails(data[i][0]); } public static int[][] excelRead() throws Exception { File excel = new File("C:\\test.xls"); FileInputStream fis = new FileInputStream(excel); HSSFWorkbook wb = new HSSFWorkbook(fis); HSSFSheet ws = wb.getSheet("xyz"); int rowNum = ws.getLastRowNum()+1; int colNum = ws.getRow(0).getLastCellNum(); int[][] data = new int[rowNum][colNum]; for (int i = 0; i < rowNum; i++) { HSSFRow row = ws.getRow(i); for (int j = 0; j < colNum; j++) { HSSFCell cell = row.getCell(i,Row.CREATE_NULL_AS_BLANK); int value = cellToString(cell); data[i][j] = value; } } return data; } public static int cellToString(HSSFCell cell) { int type; Object result; type = cell.getCellType(); switch (type) { case 0: // numeric value in excel result = cell.getNumericCellValue(); System.out.println("this is case 0" + result); break; case 1: // String value in excel result = cell.getStringCellValue(); break; default: throw new RuntimeException("There are no support for this type of cell"); } double z = (double) result; int y = (int) z; System.out.println("Value of y is" + y); return y;}} 

finddetails(data [i] [0])方法是我想要实现的实际逻辑,但问题出在excelRead方法HSSFCell cell = row.getCell(i,Row.CREATE_NULL_AS_BLANK); 抛出一个空指针exception现在在我的开关情况下处理。 我看到很多关于如何处理空单元格的post,但是我的Excel表单中没有空单元格。 我写了一些testing代码来识别上面提到的代码行,因为引起这个exception。 此外代码工作得很好,第一行,第二行getcell get返回一个空导致exception。 任何帮助表示赞赏谢谢。

HSSFCell cell = row.getCell(i,Row.CREATE_NULL_AS_BLANK);

应该 –

HSSFCell cell = row.getCell(j,Row.CREATE_NULL_AS_BLANK);

您在getCell()传递列号而不是行号。