2017-02-24 76 views
0

我想讀取每一行中的第一個單元格中的數據到對象的ArrayList中。我的問題是,我的代碼似乎沒有增加我的櫃檯超過第一行。我錯過了一些簡單的東西嗎如何在我的while循環中增加我的行計數器變量?

代碼

 try 
      { 
       wb = new XSSFWorkbook(new FileInputStream(fileName)); 
      } 
     catch (FileNotFoundException e) 
      { 
       e.printStackTrace(); 
      } 
     catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 

     XSSFSheet sheet = wb.getSheetAt(2); 
     ArrayList<Object> obj = new ArrayList<Object>(); 
     int rowIndex = 0; 
     int cellIndex = 0; 
     XSSFRow row = sheet.getRow(rowIndex); 
     Iterator<Cell> rowItr = row.iterator(); 

     while(rowIndex <= sheet.getLastRowNum()) 
      { 
       if(row.getCell(0) == null) 
        { 
         continue; 
        } 
       else 
        { 
         while(rowItr.hasNext() && rowItr.next() != null) 
            { 
             XSSFCell cell = row.getCell(cellIndex); 

             if(cell == null) 
              { 
               continue; 
              } 
             else 
              {  
               obj.add(row.getCell(cellIndex).toString()); 
              } 
             cellIndex++; 
            } 

           rowIndex++; 
           cellIndex = 0; 

          } 

         System.out.println(obj.toString()); 
        } 
       rowIndex++; 
      } 
    } 

輸出

[ValuSmart Series 1120 Double Hung] 

... 我得到這個輸出72倍,因爲有72列在表

隔離迴路

ArrayList<Object> obj = new ArrayList<Object>(); 
int rowCounter = 16; 
     int x = 0; 

     while(rowCounter <= 21) 
      { 

       XSSFRow row = sheet.getRow(rowCounter); 
       Iterator<Cell> rowItr = row.iterator(); 

       while(rowItr.hasNext() && rowItr.next() != null) 
        { 

           XSSFCell cell = row.getCell(x); 


           if(cell == null) 
            { 
             continue; 
            } 
           else 
            { 

             obj.add(row.getCell(x).toString()); 
            } 
         x++; 

        } 

       rowCounter++; 
       x = 0; 
      } 
     System.out.println(obj.toString()); 
+0

使用調試器和執行由行代碼行會幫助你找到問題,並會爲您節省在今後的調試時間無數個小時。爲什麼不現在就開始做? –

+0

你的迭代器的目的是什麼? – shmosel

+0

int rowIndex = 0; XSSFRow row = sheet.getRow(rowIndex);事實上,你的「行」對象已經在循環之外初始化了,你只是在循環中使用同一個對象。 –

回答

1

您不會在任何地方選擇下一行,並且您的循環很混亂,並在基於索引和基於迭代器的查找之間切換。嘗試一個簡單的增強爲循環:

for (Row row : sheet) { 
    for (Cell cell : row) { 
     if (cell != null) { 
      obj.add(row.getCell(x).toString()); 
     } 
    } 
} 
System.out.println(obj.toString()); 
+0

最後一件事。一旦一個單元格爲空,我不想再讀取該行。我努力想出邏輯的@shmosel –

+0

@KyleHarbour將'if'改爲'if(cell == null){break; }'並移出下一行。 – shmosel

+0

使用增強的循環,你只會得到存在的單元格,所以你不會得到一個空單元格。打破空單元格的目的是什麼?電子表格中的行是否在行中間缺少單元格? – jmarkmurphy

相關問題