-. Quick Ref.
http://poi.apache.org/spreadsheet/quick-guide.html

-. HOW TO
http://poi.apache.org/spreadsheet/how-to.html


Iterate over rows and cells

Sometimes, you'd like to just iterate over all the rows in a sheet, or all the cells in a row. This is possible with a simple for loop.

Luckily, this is very easy. Row defines a CellIterator inner class to handle iterating over the cells (get one with a call to row.cellIterator()), and Sheet provides a rowIterator() method to give an iterator over all the rows.

Alternately, Sheet and Row both implement java.lang.Iterable, so using Java 1.5 you can simply take advantage of the built in "foreach" support - see below.

	Sheet sheet = wb.getSheetAt(0);
	for (Iterator<Row> rit = sheet.rowIterator(); rit.hasNext(); ) {
		Row row = rit.next();
		for (Iterator<Cell> cit = row.cellIterator(); cit.hasNext(); ) {
			Cell cell = cit.next();
			// Do something here
		}
	}
				

Iterate over rows and cells using Java 1.5 foreach loops

Sometimes, you'd like to just iterate over all the rows in a sheet, or all the cells in a row. If you are using Java 5 or later, then this is especially handy, as it'll allow the new foreach loop support to work.

Luckily, this is very easy. Both Sheet and Row implement java.lang.Iterable to allow foreach loops. For Row this allows access to the CellIterator inner class to handle iterating over the cells, and for Sheet gives the rowIterator() to iterator over all the rows.

	Sheet sheet = wb.getSheetAt(0);
	for (Row row : sheet) {
		for (Cell cell : row) {
			// Do something here
		}
	}


Getting the cell contents

To get the contents of a cell, you first need to know what kind of cell it is (asking a string cell for its numeric contents will get you a NumberFormatException for example). So, you will want to switch on the cell's type, and then call the appropriate getter for that cell.

In the code below, we loop over every cell in one sheet, print out the cell's reference (eg A3), and then the cell's contents.

// import org.apache.poi.ss.usermodel.*;

Sheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
	for (Cell cell : row) {
		CellReference cellRef = new CellReference(row.getRowNum(), cell.getCellNum());
		System.out.print(cellRef.formatAsString());
		System.out.print(" - ");
		
		switch(cell.getCellType()) {
      case Cell.CELL_TYPE_STRING:
        System.out.println(cell.getRichStringCellValue().getString());
        break;
      case Cell.CELL_TYPE_NUMERIC:
        if(DateUtil.isCellDateFormatted(cell)) {
          System.out.println(cell.getDateCellValue());
        } else {
          System.out.println(cell.getNumericCellValue());
        }
        break;
      case Cell.CELL_TYPE_BOOLEAN:
        System.out.println(cell.getBooleanCellValue());
        break;
      case Cell.CELL_TYPE_FORMULA:
        System.out.println(cell.getCellFormula());
        break;
      default:
        System.out.println();
		}
	}
}
 

+ Recent posts