日期:2014-05-20  浏览次数:20773 次

小弟有一个关于POI 问题,,有请大哥们赐教,最好能写出代码!!
小弟刚接触poi不久,想用poi 做一个 能够添加 指定的单元格位置 内容 的程序,但是问题就出现了, 我用getrow()的方法,

如果 这行的第一个单元格为空,程序就会有异常抛出,, 但是 如果 我要是用 creatrow(), 就会把 这行 其他单元格里的内

容 覆盖了,变成了空值。。 能不能 帮小弟 解决下??
我的代码 如下:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;


public class test {

/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
try{

FileOutputStream fileOut = null;


File myxls = new File("1.xls");
FileInputStream fis = new FileInputStream(myxls);
HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(fis));

HSSFSheet sheet = wb.getSheetAt(0);


HSSFRow row = sheet.getRow(6);

HSSFCell cell=row.getCell(1);

if(null != sheet.getRow((short)6) )
{
System.out.println("ok");
}

else{
System.out.println("111");
}


fileOut = new FileOutputStream("1.xls");

fis.close();

wb.write(fileOut);

fileOut.close();


}catch(Exception e){
String s=e.toString();
System.out.println(s);

}

}

}
 

------解决方案--------------------
get之后需要测试是否是null然后再操作
Java code
HSSFRow row = sheet.getRow(6);    
    if (row == null){
        row = sheet.createRow(6);
    }
    HSSFCell cell=row.getCell(1);
    if (cell == null){
        cell = row.createCell(1);
    }

------解决方案--------------------
探讨

不知道 您遇到过这样的情况不,,如果这样的首个单元格为空的话,, poi就认为这个整行为空吧,是不是我的poi有问题呀

------解决方案--------------------
另外,可能你已经知道,只是提醒下
首单元是cell(0)不是cell(1)
row(6)是第七行
------解决方案--------------------
我的poi是3.7版的, 
HSSFRow row = sheet.getRow(6); 只有整行都是空白时,才返回null,该行任意一个单元格有数据时,不会返回null. 
HSSFRow row = sheet.getRow(6); 
if (row == null){
row = sheet.createRow(6);
}
HSSFCell cell=row.getCell(1);
if (cell == null){
使用前要判断一下.
sheet.createRow(6);只有整行为空白时,才要创建row,因为是null行,所以不会覆盖原数据.