2016-10-27 28 views
0

我有一段代码直接进入excel工作表,它基于指定的行号和列名,我的问题是如果列名为null,那么值将不会设置在其余的列。 enter image description hereexcel中没有设置数据

在这个

练成没有价值得到后列“d”

下面是我的代码

public boolean setExcelData(String sheetName, String colName, int rowNum, String data) throws AutoException { 
    dataFile(); 
    try { 
     if (rowNum <= 0) 
      throw new AutoException(EXCEPTIION); 

     int index = wb.getSheetIndex(sheetName); 
     int colNum = -1; 
     if (index == -1) 
      throw new AutoException(EXCEPTIION); 

     XSSFSheet sheet = wb.getSheetAt(index); 
     Row row = sheet.getRow(0); 
     for (int i = 0; i < row.getLastCellNum(); i++) { 
      System.out.println(row.getCell(i)); 
      if (row.getCell(i) == null) { 
       throw new AutoException(EXCEPTIION); 
      } else if (row.getCell(i).getStringCellValue().trim().equals(colName)) { 
       colNum = i; 
       break; 
      } 
     } 
     if (colNum == -1) 
      throw new AutoException(EXCEPTIION); 

     sheet.autoSizeColumn(colNum); 
     row = sheet.getRow(rowNum - 1); 
     if (row == null) 
      row = sheet.createRow(rowNum - 1); 
     Cell cell = row.getCell(colNum); 
     if (cell == null) 
      cell = row.createCell(colNum); 
     cell.setCellValue(data); 

     FileOutputStream fileOut = new FileOutputStream(excelFilePath); 
     wb.write(fileOut); 
     fileOut.close(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
     return false; 
    } finally { 
     try { 
      wb.close(); 
      in.close(); 
     } catch (Exception e) { 
     } 
    } 
    return true; 
} 

任何一个可以帮我补充道。 由于事先

回答

0

跳过for循环迭代,如果列名是空

for (int i = 0; i < row.getLastCellNum(); i++) { 
    System.out.println(row.getCell(i)); 
    if (String.IsNullOrEmpty(colName)) 
     continue; 
    if (row.getCell(i) == null) { 
     throw new AutoException(EXCEPTIION); 
    } else if (row.getCell(i).getStringCellValue().trim().equals(colName)) { 
     colNum = i; 
     break; 
    } 
}