【发布时间】:2015-12-08 13:11:41
【问题描述】:
您好,我有一张 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); 抛出一个空指针异常,现在在我的 switch 案例中处理。我看到很多关于如何处理空单元格的帖子,但我的 excel 表中没有空单元格。我编写了一些测试代码来确定上述代码行是导致异常的原因。此外,第一行的代码工作得很好,从第二行开始,getcell 返回一个导致异常的空值。感谢您提供任何帮助。
【问题讨论】:
-
别忘了行也可以为空!
标签: java excel nullpointerexception apache-poi