2016-02-26 136 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个值。 –