maruf sayyed
maruf sayyed

Reputation: 41

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

Upvotes: 0

Views: 33

Answers (1)

Guy
Guy

Reputation: 50809

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

Upvotes: 1

Related Questions