gpt4 book ai didi

java - 是什么导致这段代码中的 'NullPointerException',读取 Excel 单元格?

转载 作者:行者123 更新时间:2023-11-29 04:01:34 24 4
gpt4 key购买 nike

我正在使用 Apache POI 阅读 Excel。我被要求将单元格存储到 MySQL 5.1 中。当我读取 Excel 单元格时,我被抛出 NullPointerException。这是我的代码片段:

  int rows = sheet.getPhysicalNumberOfRows();

for(int r = 1; r<rows; r++) {
HSSFRow row = sheet.getRow(r);
int cols = row.getLastCellNum();

for(int c=0; c < cols; c++) {
HSSFCell cell = row.getCell(c, Row.CREATE_NULL_AS_BLANK);

switch(cell.getColumnIndex()) {

case 0:
....
....

case 1:
....
....


case ...:
....
....

}
}
}

// Here comes the code to insert into DB

如果有人能确定它出现的位置,请尽快发布。如果我留下了一些逻辑你只需要问我...

最佳答案

您的数组偏移量是否有可能偏离一个(对于行循环)?

for(int r = 1; r<rows; r++) {
HSSFRow row = sheet.getRow(r);

不是从偏移量 1 开始,而是从 0 开始。这更有意义(并且匹配您的列循环)。

在这种情况下,HSSFRow row = sheet.getRow(r); 的结果可能为空(顺便说一句,您应该检查一下)。

编辑#1:例如:

  if (sheet == null) {
return;
}

int rows = sheet.getPhysicalNumberOfRows();
for(int r = 1; r<rows; r++) {
HSSFRow row = sheet.getRow(r);
if (row != null) {
int cols = row.getLastCellNum();

for(int c=0; c < cols; c++) {
HSSFCell cell = row.getCell(c, Row.CREATE_NULL_AS_BLANK);

if (cell != null) {
switch(cell.getColumnIndex()) {
case 0:
case 1:
case ...:

}
}
}
}
}

如果你看the JavaDoc这很重要

public int getPhysicalNumberOfRows()  {
return _rows.size();
}

返回物理定义的行数(不是工作表中的行数)

编辑#2:为了进一步调试,请在您的 for 循环周围放置以下 try/catch。

try {
// Your for loop code here
} catch (Exception x) {
x.printStackTrace();
}

请将评论粘贴到此答案或使用此输出结果更新您的原始答案。

关于java - 是什么导致这段代码中的 'NullPointerException',读取 Excel 单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3192906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com