我的步骤是:1、复制模板excel文件为新文件new.xsl:
if (!thefile.exists()) {
//copy excel
FileInputStream fis = new FileInputStream(moulepathinfo);
FileOutputStream fos = new FileOutputStream(thepathinfo);
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
fis.close();
fos.close();
}
2、在new.xsl中更新cell值:
String outputFile = thepathinfo;
HSSFWorkbook workbook =
new HSSFWorkbook(new FileInputStream(outputFile));
HSSFSheet sheet = workbook.getSheet("Sheet1");
int rows = sheet.getPhysicalNumberOfRows();
for (int i = 1; i < rows; i++) {
HSSFRow row = sheet.getRow(i);
for (int j = 0; j < 3; j++) {
if (row == null) {
System.err.println("row is null.");
}
HSSFCell cell = row.getCell((short) j);
if (cell == null) {
System.err.println("cell is null.");
}
String CellValue = cell.getStringCellValue();
if (CellValue.equals("测试")) {
HSSFRow CountRow = sheet.getRow(i);
HSSFCell CountCell = CountRow.getCell((short) 3);
String CountValue = CountCell.getStringCellValue();
if (CountValue.equals(""))
CountValue = "0";
String Count =
Integer.toString(Integer.parseInt(CountValue) + 1);
CountCell.setCellValue(Count); //更新数据
FileOutputStream fOut = new FileOutputStream(outputFile);
workbook.write(fOut);
fOut.close();
break;
}
}
}
问题:有时候会出现getRow或者getCell出现NULL,但是excel文件打开正常,而且如果在出现NULL的那一行或者那个cell中手动输入空格,保存后再次执行就没有问题,这个究竟是什么原因,怎么解决。poi版本是jakarta-poi-1.10.0-dev-20030222.jar

解决方案 »

  1.   

    HSSFRow row = sheet.getRow(i);
    getRow() 这个函数是 0-based
      

  2.   

    因为你处理的单元格没有设置值,所以getCell返回null;
    同理,因为你处理的行,全部单元格都未设置值,所以getRow返回null。
    就是说,空格和null是不同的。poi并没有出错,是你理解的有些问题,呵呵。
      

  3.   

    单元格为NULL可以理解但是行不为null阿,打开excel时,这些行是有值的而且,这些行是在中间,加入中间某一行为null,那么下面的所有行读出来都是null这又怎么解释
      

  4.   

    0-based 是 getRow(i) 中的这个 i 是从 0 开始的
      

  5.   

    在判断为null的cell里面赋空字符串
      

  6.   

    zhkl0228(凯子魅力) ( ) 信誉:100    Blog  2006-11-15 11:31:31  得分: 0  
        
    0-based 是 getRow(i) 中的这个 i 是从 0 开始的-----------------------------------------------------
    楼主怎么视而不见?~! 
     
      

  7.   

    0-based 是 getRow(i) 中的这个 i 是从 0 开始的也就是说:excel的第1行 就是  getRow(0)
      

  8.   

    谢谢楼上的提醒,但是,我的循环是从第二行开始,然后到最后一行,程序逻辑并没有错另外,我取到NULL的这些行并不是开头也不是末尾,而是:这些行是在中间,加入中间某一行为null,那么下面的所有行读出来都是null这又怎么解释
      

  9.   

    当然会的就是你这个单元格,或者行,在编辑Excel的时候,根本就没有碰过,Excel保存的时候就会出现这个问题
      

  10.   

    是Excel的问题,循环的时候if (xxx == null) {continue;}
      

  11.   

    循环请用
    ----row----
    for (Iterator it = sheet.rowIterator(); it.hasNext();) {
    HSSFRow row = (HSSFRow) it.next();----col------
    for (Iterator cit = row.cellIterator(); cit.hasNext();) {
    HSSFCell cell = (HSSFCell) cit.next();