Sebastian Zeki Sebastian Zeki - 1 month ago 14
Java Question

Check if row contains word

I have a spreadsheet and I only want to select rows that have a specific word in one column and another word in another column. At the moment I am only able to check for the word in any cell in the row. How can I check for the presence of the word in a cell in a specific column?

Here is my code

FileInputStream fis = new FileInputStream(new File(filepath));
XSSFWorkbook workBook = new XSSFWorkbook (fis);
XSSFSheet sheet = workBook.getSheetAt (0);

List<XSSFRow> filteredRows = new ArrayList<XSSFRow>();
Iterator<Row> rows= sheet.rowIterator();
while (rows.hasNext ()){
XSSFRow row = (XSSFRow) rows.next ();

Iterator<Cell> cells = row.cellIterator ();
while (cells.hasNext ()){

XSSFCell cell = (XSSFCell) cells.next ();
if (cell.toString().contains("Ginko")) {
filteredRows.add(row);
break;
}
}
}

Answer

You can check if a cell is in a specific column by calling cell.getColumnIndex() == columnNumber. For example:

for(Cell cell : row) {
  if(cell.getColumnIndex() == 1) {
    // process a cell in column 1
  }
}

Source: https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#getColumnIndex()

Comments