问题
My code is to print a list of title in to excel using webelement list, but it is only printing one that is last data in to excel. please help.
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.
no error is there.try catch is added.
回答1:
Looks like you overwrite your excel sheet for every WebElement
that you are processing and always overwriting the first row in that sheet instead of creating a new row. Try creating a new row for each element, like this:
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);
}
...
}
来源:https://stackoverflow.com/questions/41819888/printing-only-one-element-from-webelement-list-in-excel