From 6649d4e4f7415b6a1a532707b13f5c9c268b7086 Mon Sep 17 00:00:00 2001 From: Nick Burch Date: Tue, 5 Feb 2008 16:21:21 +0000 Subject: [PATCH] Tweaks to the iterator use guides for hssf git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@618690 13f79535-47bb-0310-9956-ffa450edef68 --- .../content/xdocs/hssf/quick-guide.xml | 44 +++++++++++++++++-- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/src/documentation/content/xdocs/hssf/quick-guide.xml b/src/documentation/content/xdocs/hssf/quick-guide.xml index b2f729fedc..69850afe88 100644 --- a/src/documentation/content/xdocs/hssf/quick-guide.xml +++ b/src/documentation/content/xdocs/hssf/quick-guide.xml @@ -236,16 +236,51 @@ -
Iterate over rows and cells (including Java 5 foreach loops) +
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. If you are using Java - 5 or later, then this is especially handy, as it'll allow the - new foreach loop support to work.

+ a sheet, or all the cells in a row. This is possible with + a simple for loop.

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

+

(Unfortunately, due to the broken and + backwards-incompatible way that Java 5 foreach loops were + implemented, it isn't possible to use them on a codebase + that supports Java 1.4, as POI does)

+ + HSSFSheet sheet = wb.getSheetAt(0); + for (Iterator rit = sheet.rowIterator(); rit.hasNext(); ) { + HSSFRow row = (HSSFRow)rit.next(); + for (Iterator cit = row.cellIterator(); cit.hasNext(); ) { + HSSFCell cell = (HSSFCell)cit.next(); + // Do something here + } + } + + + HSSFSheet sheet = wb.getSheetAt(0); + for (Iterator<HSSFRow> rit = (Iterator<HSSFRow>)sheet.rowIterator(); rit.hasNext(); ) { + HSSFRow row = rit.next(); + for (Iterator<HSSFCell> cit = (Iterator<HSSFCell>)row.cellIterator(); cit.hasNext(); ) { + HSSFCell cell = cit.next(); + // Do something here + } + } + +
+
Iterate over rows and cells using Java 1.5 foreach loops - OOXML Branch Only +

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 HSSFSheet and HSSFRow + implement java.lang.Iterable to allow foreach + loops. For HSSFRow this allows access to the + CellIterator inner class to handle iterating over + the cells, and for HSSFSheet gives the + rowIterator() to iterator over all the rows.

HSSFSheet sheet = wb.getSheetAt(0); for (HSSFRow row : sheet.rowIterator()) { @@ -254,6 +289,7 @@ } } + This only works on the OOXML branch of POI
Text Extraction -- 2.39.5