2016-10-27 4 views
0

Ich habe ein Stück Code rechts in Excel-Blatt, es basiert auf der angegebenen Zeilennummer und Spaltenname, mein Problem ist, dass, wenn ein Spaltenname Null ist dann wird Wert im Rest nicht festgelegt der Spalten. enter image description hereDaten nicht in Excel festgelegt

in dieser Excel kein Wert nach Spalte 'D'

Unten ist mein Code

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; 
} 

Jeder kann mir helfen, noch hinzukommen. Dank im Voraus

Antwort

0

die Iteration für Schleife überspringen, wenn column null ist

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; 
    } 
} 
Verwandte Themen