0

I have excel sheet with two columns, first column has 50 first names and second column has 50 last names. I want to read random first name and random last name everytime I call excel sheet. Here is my generic method for accessing both the columns

public void getCellData(String sheetName) {
        int index = workbook.getSheetIndex(sheetName);
        sheet = workbook.getSheetAt(index);
        Iterator iterator = sheet.iterator();
        while(iterator.hasNext()) {
            XSSFRow row = (XSSFRow) iterator.next();
            Iterator cellIterator = row.cellIterator();
            while(cellIterator.hasNext()) {
                XSSFCell cell = (XSSFCell) cellIterator.next();
                String cellData = cell.getStringCellValue();
                System.out.println(cellData);
            }   }   }

Above code will display all first and last names. Now that I have access to the names how do I randomly select the first and last name ?

I tried this thread, but it was more about intergers.

Any help please on how to randomly select cell data using java ?

GSN
  • 123
  • 2
  • 13

1 Answers1

1

You could do by following

    public void getCellData(String sheetName) {
        int index = workbook.getSheetIndex(sheetName);
        sheet = workbook.getSheetAt(index);
        int randomRowIndex = new SecureRandom().nextInt(sheet.getLastRowNum()) % sheet.getPhysicalNumberOfRows();
        XSSFRow row = sheet.getRow(randomRowIndex);
        Iterator cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {
            XSSFCell cell = (XSSFCell) cellIterator.next();
            String cellData = cell.getStringCellValue();
            System.out.println(cellData);
       }
}
mystery
  • 875
  • 6
  • 16