簡體   English   中英

在Excel中僅打印Web元素列表中的一個元素

[英]Printing only one element from webelement list in excel

我的代碼是使用webelement列表將標題列表打印到excel中,但是僅將最后一個數據打印到excel中。 請幫忙。

            driver.get("http://www.speakingcs.com/");
                Sheet sh;
            List<WebElement> postTitles = driver.findElements(By.className("entry-header"));
        for (WebElement eachTitle:postTitles)
        {
            System.out.println(eachTitle.getText());
                File object = new File("D:/selenium/data.xlsx");
                    FileInputStream fis=new FileInputStream(object);
                     wb=WorkbookFactory.create(fis);
                     sh=wb.getSheet("Sheet1");
                    Row row=null;
                    if(sh.getRow(0) != null) {
                            row = sh.getRow(0);}
                        else {
                            row = sh.createRow(0);
                        }

                       Cell cell=row.createCell(0);
                    cell.setCellType(cell.CELL_TYPE_STRING);                   
                    cell.setCellValue(eachTitle.getText());

             for(int m=1; m<6; m++)

         sh.autoSizeColumn(m);
             }
                        FileOutputStream fos=new     FileOutputStream("D:/selenium/data.xlsx");
                        wb.write(fos);
                        fos.close();
                        System.out.println("test1");

             }catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            }

this is printing only last title whereas 5 are there.

沒有錯誤。trycatch已添加。

看起來您為要處理的每個WebElement覆蓋了excel工作表,並且始終覆蓋該工作表中的第一行,而不是創建新行。 嘗試為每個元素創建一個新行,如下所示:

wb = WorkbookFactory.create(fis);
sh = wb.getSheet("Sheet1");

List<WebElement> postTitles = driver.findElements(By.className("entry-header"));
for (int index = 0; index <= postTitles.size(); index++) {
    WebElement eachTitle = postTitles.get(index);

    Row row = null;
    if (sh.getRow(index) != null) {
        row = sh.getRow(index);
    } else {
        row = sh.createRow(index);
    }
  ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM