Home » excel » Java iterator through excel rows

Java iterator through excel rows

Posted by: admin April 23, 2020 Leave a comment


I am checking every excel row and looking for certain value. After I found that value it should print an output about that row location. But if that value is incorrect or not found I am printing match not found. So everytime I am doing this my output is always: Match not found.

P.S. barcode is my string value parsed from another class (I debugged it value is passed correctly).

Moreover if I write only if case without else if program can find that value, but in case of incorrect value I will get nothing.

My problem is that everytime I run that if cycle no mater if my barcode string is correct or not I always got match not found.

My task is to scan excel file and find a value which I need in this case barcode and print entire row, but if barcode is incorrect I need to print that match not found that user will able to know that barcode he entered is incorrect.

try {
        FileInputStream file = new FileInputStream(new File("Turto sarašas 2016.09.30.xlsx"));

        //Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(file);

        //Get first/desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);

        //Iterate through each rows one by one
        Iterator<Row> rowIterator = sheet.iterator();

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            //For each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) {

                Cell cell = cellIterator.next();
                //Check the cell type and format accordingly
                final DataFormatter df = new DataFormatter();
                String valueAsString = df.formatCellValue(cell);
                if (valueAsString.equals(barcode)) {
                    System.out.print("Hello" + row.getCell(0));
                    System.out.print("Hello" + row.getCell(3));
                } else if (!valueAsString.equals(barcode)) {
                    System.out.println(" Match not found");

    } catch (IOException e) {
How to&Answers:

Code is working as expected. If possible share that input xlsx to debug.