How to fetch single row from excel sheet and pass into testng data provider using java

158 views Asked by At

I have a scenario to fetch entire 3rd row data from excel sheet and pass to data provider. I can fetch all the row available in excel sheet (Please find the code below). But, I want to fetch nth row of data and pass to data provider annotation. Thanks in advance

Utility class:

public static Object[][] getTestData(String sheetName) {
        Object[][] data = null;
        DataFormatter fmt = new DataFormatter();
        try (Workbook workbook = new XSSFWorkbook(
                new FileInputStream("path"))) {
            Sheet sheet = workbook.getSheet(sheetName);
            data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
            for (int i = 0; i < sheet.getLastRowNum(); i++) {
                for (int k = 0; k < sheet.getRow(0).getLastCellNum(); k++) {
                    data[i][k] = fmt.formatCellValue(sheet.getRow(i + 1).getCell(k));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

I am preparing utlity class for fetching single row of data and passing into data provider annotation in testng

1

There are 1 answers

2
mazi On

Just return the 3rd row after reading the data

for (int i = 0; i < sheet.getLastRowNum(); i++) {
                for (int k = 0; k < sheet.getRow(0).getLastCellNum(); k++) {
                    data[i][k] = fmt.formatCellValue(sheet.getRow(i + 1).getCell(k));
                }
            }
if (i>2) 
  for k...
  return data[2,k]

or break your loop after the 3rd row has been read if you don't need to fetch all rows.