Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Apache POI how to read a specific excel column

Tags:

I'm having a problem in excel while using Apache POI. I can read across rows, but sometimes I'm in a situation where I would like to read a particular column only.

So is it possible to read any particular column like only the 'A' column only or the column 'C' only.

I'm using the Java language for this.

like image 240
selva Avatar asked Oct 12 '12 10:10

selva


People also ask

How do I read a specific row in Excel using Java?

To fetch a single row, we can use the getRow(int) method: Row row = sheet. getRow(2); The method returns the Row object – the high-level representation of a single row from the Excel file, or null if the row doesn't exist.


2 Answers

heikkim is right, here is some sample code adapted from some code I have:

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
...
for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
  row = sheet.getRow(rowIndex);
  if (row != null) {
    Cell cell = row.getCell(colIndex);
    if (cell != null) {
      // Found column and there is value in the cell.
      cellValueMaybeNull = cell.getStringCellValue();
      // Do something with the cellValueMaybeNull here ...
      // break; ???
    }
  }
}

For the colCount use something like row.getPhysicalNumberOfCells()

like image 116
Christophe Roussy Avatar answered Oct 02 '22 13:10

Christophe Roussy


  Sheet sheet  = workBook.getSheetAt(0); // Get Your Sheet.

  for (Row row : sheet) { // For each Row.
      Cell cell = row.getCell(0); // Get the Cell at the Index / Column you want.
  }

My solution, a bit simpler code wise.

like image 34
Jack Avatar answered Oct 02 '22 15:10

Jack