Using Cucumber+Maven+Apache POI how to select the second row values in an Excel data sheet when the test scenario runs for the second time

76 views
Skip to first unread message

Dinesha Nagahapitiya

unread,
Apr 7, 2020, 6:37:09 AM4/7/20
to Cukes

i'm automating a web application using cucumber java. And i have a test data sheet (excel sheet) which include some applicant details.This excel file will have multiple sheets and those sheets will include different number of records (eg: One sheet may have only one record but the 2nd sheet may have 5 records). I'm using apache.poi dependency and i was able to fetch the row values. But the scenario i need to automate is, when i run the same test scenario for the second time i need to fetch the data from second row of the excel sheet. And if a run the test for the 3rd time i need to fetch 3rd row... Below i have attached a sample data table i'm using,

Image of test data sheet

Below is the code i used to fetch data,


public String readExcelToFetchCaseIDValue(String fileName, String sheetName) throws IOException {

    String caseId = null;
    String filePath = FileReaderManager.getInstance().getConfigReader().gettestDataResourcePath() + fileName;
    File file = new File(filePath);

    // Create an object of FileInputStream class to read excel file

    FileInputStream inputStream = new FileInputStream(file);

    Workbook pegaTestData = null;

    // Find the file extension by splitting file name in substring and getting only
    // extension name

    String fileExtensionName = fileName.substring(fileName.indexOf("."));

    // Check condition if the file is xlsx file

    if (fileExtensionName.equals(".xlsx")) {

        // If it is xlsx file then create object of XSSFWorkbook class

        pegaTestData = new XSSFWorkbook(inputStream);

    }

    // Check condition if the file is xls file

    else if (fileExtensionName.equals(".xls")) {

        // If it is xls file then create object of HSSFWorkbook class

        pegaTestData = new HSSFWorkbook(inputStream);

    }

    // Read sheet inside the workbook by its name

    Sheet pegaDataSheet = pegaTestData.getSheet(sheetName);

    // Find number of rows in excel file

    int rowCount = pegaDataSheet.getLastRowNum() - pegaDataSheet.getFirstRowNum();

    // Create a loop over all the rows of excel file to read it

    for (int i = 0; i < rowCount + 1; i++) {

        Row row = pegaDataSheet.getRow(i);

        // Create a loop to print cell values in a row

        for (int j = 0; j < row.getLastCellNum(); j++) {

            // Print Excel data in console

            caseId = row.getCell(0).getStringCellValue();

        }

    }
    return caseId;

}
Reply all
Reply to author
Forward
0 new messages