我的代码是使用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.
没有错误。添加了。catch。
答案 0 :(得分:0)
您似乎要为正在处理的每个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);
}
...
}