čtvrtek 26. března 2009

HSSF cellIterator is too clever

I caught myself with this too clever cellIterator in HSSF POI. Normally you expect that cellIterator will iterate over all the cells in row. But unfortunately it is trying to be really smart and it doesn't iterate over cells which are null.
I.e. if you have row like



first
third


The cellIterator gives you first and third cell but not the second cell which is null

Then the following two snippets gives you different behaviour :-(.


50:    StringBuffer buffer = new StringBuffer();
51: for (Iterator<HSSFCell> cit = row.cellIterator(); cit.hasNext();) {
52: String val = extractCellValue(cit.next());
53: val = val.replaceAll("\\n", " ");
54: buffer.append(val);
55: buffer.append(separator);
56: }



50:        StringBuffer buffer = new StringBuffer();
51: for (short i = 0; i < alignColumns - 1; i++) {
52: HSSFCell cell = row.getCell(i);
53: if (cell != null) {
54: String val = extractCellValue(cell);
55: val = val.replaceAll("\\n", " ");
56: buffer.append(val);
57: }
58: buffer.append(separator);
59: }



Summary: use the second one if you're data structure matters on cell order (including those nulls)