poi读取exce文件l时运行到row.getCell((short) 0)时立即抛出异常

用的是poi 3.7版本,主要 是想给一个已经存在的excel文件修改,代码如下:
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.FileInputStream;
import java.io.IOException;

public class PoiTest {
static public void main(String[] args) throws Exception {
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/test.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);

HSSFSheet sheet = wb.getSheet("sheet1");
HSSFRow row = sheet.getRow(0); //行
HSSFCell cell = row.getCell((short) 0); //列
if(cell==null){
System.out.println("null");
}
else{
System.out.println(" not null");
}

} catch (IOException e) {
e.printStackTrace();
}
}
}
调试发现,如果test文件指定的第1行第1列单元格有数据,那么运行正常.
如果test文件指定的第1行第1列单元格没有任何数据,那么程序运行完语句"HSSFCell cell = row.getCell((short) 0); "马上就发生了异常错误,根本就没有进入到下一判断语句.请问: 为什么会这样,应该如何解决??
抛出异常为: com.sun.jdi.InvocationException occurred invoking method.

是这样的,poi在获得Cell前先判断Row是否为null,获得Row前先判断Sheet是否为null,如果你的excel整个行Row都没有值,在你获得Cell时就会报错,同理,如果你的sheet不存在,在你获得Row时就会报错,这是改正后得代码:
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.FileInputStream;
import java.io.IOException;

public class PoiTest {
static public void main(String[] args) throws Exception {
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/test.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);

HSSFSheet sheet = wb.getSheet("sheet1");
if(sheet==null){//如果不存在sheet1,建立sheet1
sheet=wb.createSheet("sheet1");
}
HSSFRow row = sheet.getRow(0); //获得行
if(row==null){//如果行不存在,建立行
row=sheet.createRow(0);
}
HSSFCell cell = row.getCell((short) 0); //列
if(cell==null){
System.out.println("null");
}
else{
System.out.println(" not null");
}

} catch (IOException e) {
e.printStackTrace();
}
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-06-23
HSSFRow row = sheet.getRow(0); //行

你的这一行,如果第一行第一列为空,那个取得的row为空,就会导致下面的出错,你判断一下,就行了。
相似回答