无法使用硒中的poi jar将所有记录写到excel工作表中

时间:2019-06-03 04:50:52

标签: java selenium-webdriver

我必须将从网站获取的记录保存在excel工作表中。我有50条不同的记录,其中只有最后一条记录在excel中被写入了50次。你能帮我吗 感谢所有人

List<WebElement> xpath11 = m.findElements(By.xpath(".//tr[contains(@id, 'rcmrow')]"));
int count = xpath11.size();
System.out.println(count);
for (WebElement link : xpath11) {
    String sd = link.getText();
    System.out.println(sd);
    File source = new File("/home/dev2/Desktop/readexcell.xlsx");
    FileOutputStream input = new FileOutputStream(source);
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet("data");

    int i;

    for (i = 0; i < count; i++) {
        XSSFRow excelRow = sheet.createRow(i);
        XSSFCell excelCell = excelRow.createCell(0);
        excelCell.setCellType(CellType.STRING);
        excelCell.setCellValue(sd);
    }

    wb.write(input);
}

1 个答案:

答案 0 :(得分:1)

您要为外部WebElement循环中的每个for重新创建excel文件,并在内部for循环中反复写入其文本。您需要在for之前创建文件,并且仅使用一个循环

File source = new File("/home/dev2/Desktop/readexcell.xlsx");
FileOutputStream input = new FileOutputStream(source);
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("data");

List<WebElement> xpath11 = m.findElements(By.xpath(".//tr[contains(@id, 'rcmrow')]"));
int count = xpath11.size();
for (int i = 0; i < count; i++) {
    String sd = xpath11.get(i).getText();
    System.out.println(sd);
    XSSFRow excelRow = sheet.createRow(i);
    XSSFCell excelCell = excelRow.createCell(0);
    excelCell.setCellType(CellType.STRING);
    excelCell.setCellValue(sd);
}

wb.write(input);