Nikhil Kumar
Nikhil Kumar

Reputation: 89

How to print the whole row of an excel sheet after finding a specific string from that row?

This is the code I am using to find the specific string in an excel sheet.

FileInputStream fis = new FileInputStream(new File("D:\\excel_file.xlsx"));
workbook = new XSSFWorkbook(fis);

for(int i = 0; i < workbook.getNumberOfSheets(); i++) {
    XSSFSheet spreadsheet = workbook.getSheetAt(i);
    Iterator<Row> rowIterator = spreadsheet.iterator();
    while (rowIterator.hasNext()) {
        row = (XSSFRow) rowIterator.next();
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();

            String test_string = "search_phrase";
            if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                if (test_string.trim().equalsIgnoreCase(cell.getStringCellValue().trim())) {
                    flag = 1;
                    rowNum = row.getRowNum();
                    System.out.println("found");
                }
            }
        }
        fis.close();
        workbook.close();
    }
}

if(flag==0) {
    System.out.println("not found");
}

I can also get the row number easily.

But using that row number I am not able to figure out how to get all the cells in that row.

Upvotes: 0

Views: 7120

Answers (1)

Sankumarsingh
Sankumarsingh

Reputation: 10079

No need to find row number. If the condition met and, you have row then you can use the following in place of Flag=1;

Iterator<Cell> cellItr = row.iterator();
    while(cellItr.hasNext()){
        System.out.println(cellItr.next().toString());
    }

However I am assuming the datatype in the cell are String. If not, you need to manage the cell data type and missingCellPolicy for perfection.

Upvotes: 3

Related Questions