2016-02-26 152 views
0

我在頁面上有一個表格,而且我需要讀取表格中特定單元格的值。我想把這些值寫入excel文件。 問題在於,循環只循環一次,值只寫入excel中的第一個單元格。 我已經嘗試了許多不同的循環,並在谷歌搜索,但無法找到答案。 請幫忙。這裏是我的代碼寫入到Excel中:for循環僅在寫入excel時循環一次

public static void setExcelFile(String Path, String SheetName) throws Exception { 

     try { 

      // Open the Excel file 

      FileInputStream ExcelFile = new FileInputStream(Path); 

      // Access the required test data sheet 

      ExcelWBook = new XSSFWorkbook(ExcelFile); 

      ExcelWSheet = ExcelWBook.getSheet(SheetName); 

     } catch (Exception e) { 

      throw (e); 

     } 

    } 

這是我在哪裏寫excel文件

 public static void setCellData(String Result, int RowNum, int ColNum) throws Exception { 

     try { 

      Row = ExcelWSheet.getRow(RowNum); 

      Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL); 

      if (Cell == null) { 

       Cell = Row.createCell(ColNum); 

       Cell.setCellValue(Result); 

      } else { 

       Cell.setCellValue(Result); 

      } 

      // Constant variables Test Data path and Test Data file name 

      FileOutputStream fileOut = new FileOutputStream(Constant.Path_TestData + Constant.File_TestData); 

      ExcelWBook.write(fileOut); 

      fileOut.flush(); 

      fileOut.close(); 



     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     } 

and here is my loop 
// 
ExcelUtils.setExcelFile(Constant.Path_TestData + Constant.File_TestData, "Item_Selection"); 

List<WebElement> li = driver.findElements(By.cssSelector("#offerVersionSkuListTable>table:nth-child(2)>tbody>tr>td#regularCost")); 

for (int j = 0; j<li.size(); j++) { 

    String cellValue = li.get(j).getText(); 
    List<String> valueList = new ArrayList<String>(); 
    valueList.add(cellValue); 

      for (int m = 0; m<valueList.size(); m++) { 

         int temp = row; 

     ExcelUtils.setCellData(valueList.get(m), temp, Constant.Col_TblRegCost); 
         temp++; 

        } 
       } 

錯誤我得到的是: org.openqa.selenium.StaleElementReferenceException:元素不在緩存中找到 - 也許是頁面發生了變化,因爲它是擡頭

經過進一步調查,我發現,如果我刪除 ExcelUtils.setCellData(valueList.get(M),溫度,Constant.Col_TblRegCost);

Loop成功完成並正確輸出表中的值,但我需要將這些值寫入excel。看起來,在excel中寫入第一個值之後,再次循環循環,但不會寫入任何東西以便第二次出現。你能幫我找出原因嗎?

+0

哪裏是從頁面讀取數據的代碼? – Rehman

+0

使用列表我基本上在我想要的列下獲得2個單元格。然後,我使用for循環來從列表中獲取值並將其分配給數組,然後使用它在excel單元格中填充值。 –

回答

0

for循環爲什麼只循環一次的解釋是您試圖循環的List僅包含一個值。當for循環完成循環時,循環會中斷。同樣的事情,如果列表將有五個值,循環將遍歷這些,然後中斷。

+0

謝謝您花時間回答我的問題。當我嘗試li.size()時,它返回2,這意味着它包含2個值。 –