Sebastian Zeki Sebastian Zeki - 1 year ago 83
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) ();

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

XSSFCell cell = (XSSFCell) ();
if (cell.toString().contains("Ginko")) {

Answer Source

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