[英]Trying to parse Excel file
I'm trying to parse excel file in such a way that when I find an empty cell I add to the value of string. 我正在尝试以一种方式解析excel文件,以便当我找到一个空单元格时将其添加到字符串的值中。 Sample code:
样例代码:
for (int e = 0; e < wb.getNumberOfSheets(); e++) {
sheet = wb.getSheetAt(e);
for (int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum(); i++) {
System.out.println(sheet.getSheetName());
row = sheet.getRow(i);
if(row != null) {
cell = row.getCell(0, Row.RETURN_BLANK_AS_NULL);
if(cell.getCellType() != Cell.CELL_TYPE_BLANK) {
cell = row.createCell(i);
cell.setCellValue("foo");
}
cell = row.getCell(1, Row.RETURN_BLANK_AS_NULL);
if(cell == null) {
cell = row.createCell(i);
cell.setCellValue("bar");
}
cell = row.getCell(2, Row.RETURN_BLANK_AS_NULL);
if(cell == null) {
cell = row.createCell(i);
cell.setCellValue(0.0);
}
}
}
I tried many solutions, and I always get an exception NullPointerException. 我尝试了许多解决方案,并且总是收到NullPointerException异常。
Could be useful to know which line gives you the exception, but I bet it's this one: 知道哪一行为您提供了异常可能会很有用,但是我敢打赌这就是这一行:
cell = row.getCell(0, Row.RETURN_BLANK_AS_NULL);
if(cell.getCellType() != Cell.CELL_TYPE_BLANK) {
As far as I know, the policy RETURN_BLANK_AS_NULL returns a null value if the cell is empty. 据我所知,如果单元格为空,则策略RETURN_BLANK_AS_NULL 返回空值 。 So, if you get a blank cell there, the
cell.getCellType()
in the if statement raises a NullPointerException. 因此,如果在那里有一个空白单元格,则if语句中的
cell.getCellType()
会引发NullPointerException。
You have NPE in first check, the cell is null: 您首先检查了NPE,单元格为空:
cell = row.getCell(0, Row.RETURN_BLANK_AS_NULL);
if(cell.getCellType() != Cell.CELL_TYPE_BLANK) {
later you check correctly: 稍后您正确检查:
cell = row.getCell(2, Row.RETURN_BLANK_AS_NULL);
if(cell == null) {
to create new cell use 创建新的单元格使用
Row.CREATE_NULL_AS_BLANK
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.