是这样的,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();
}
}
}