简体   繁体   中英

not able to write all the record in excel sheet using poi jar in selenium

I have to save record fetched from the website in the excel sheet .i have 50 different records out which only last record is written in the excel 50 times. can u help me please thanks to all

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);
}

You are recreating the excel file for every WebElement in the outer for loop, and write its text over and over in the inner for loop. You need to create the file before the for and use only one loop

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM