Search code examples
javaapache-poi

How to get the whole row for a if specific column has a certain text with POI


I need to filter my Excel spreadsheet for the word "GHH" anywhere in the text of a cell in a specific column. I have managed to do this by I then need to have returned the whole row that this text is found in. This I can't do as there doesn't seem to be a way of using the getRowIndex method to then display the whole row.

Here is my code:

public static void main(String[] args) throws IOException {
    FileInputStream fis = new FileInputStream(new File("myfile.xls"));
    HSSFWorkbook workBook = new HSSFWorkbook(fis);
    HSSFSheet sheet = workBook.getSheetAt(0);
    Iterator < Row > rows = sheet.rowIterator();
    while (rows.hasNext()) {
        HSSFRow row = (HSSFRow) rows.next();
        Iterator < Cell > cells = row.cellIterator();
        while (cells.hasNext()) {
            HSSFCell cell = (HSSFCell) cells.next();
            if (cell.toString().contains("GHH")) {
                String key = cell.getStringCellValue();
                int RI = cell.getRowIndex();
            }
        }
    }
    workBook.close();
}

Solution

  • You could try to use a List<HSSFRow> to save filtered rows as bellow:

    List<HSSFRow> filteredRows = new ArrayList<HSSFRow>();
    Iterator<Row> rows= sheet.rowIterator(); 
    while (rows.hasNext ()){
    HSSFRow row = (HSSFRow) rows.next ();  
     Iterator<Cell> cells = row.cellIterator (); 
     while (cells.hasNext ()){
        HSSFCell cell = (HSSFCell) cells.next (); 
        if (cell.toString().contains("GHH")) {
            String key = cell.getStringCellValue();
            int RI=cell.getRowIndex();
            filteredRows.add(row);
            break;
        }
    }
    // then use filteredRows