Re: HSSF
In article
<34adced1-4b01-4a3e-9f56-e55e46de37f1@b1g2000vbc.googlegroups.com>,
dendeezen <tsd35328@scarlet.be> wrote:
[...]
I am a novice and try to understand how HSSF works.
When I try to read an excel cell that is not empty, it works fine as
far as the content is not a date, in which case I get an number back.
When I try to read an empty cell , I get the exception: Exception in
thread "main" java.lang.NullPointerException at
com.ms.util.POIExcelReader.main(POIExcelReader.java:37)
[...]
HSSFCell cel = rij.getCell((short) 4); // this cell is empty
This method is deprecated. Empty cells are null and should not be
dereferenced. Another approach is to use the supplied iterator(), which
skips empty cells:
<code>
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
public class POIExcelReader {
public static void main(String[] args) throws IOException {
InputStream myxls = new FileInputStream("test.xls");
HSSFWorkbook book = new HSSFWorkbook(myxls);
HSSFSheet sheet = book.getSheetAt(0);
HSSFRow row = sheet.getRow(2);
for (Cell cell : row) {
printCell(cell);
}
}
private static void printCell(Cell cell) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_BLANK:
System.out.println("EMPTY");
break;
case HSSFCell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
System.out.println(cell.getDateCellValue());
} else {
System.out.println(cell.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
System.out.println(cell.getCellFormula());
break;
default:
System.out.println("DEFAULT");
}
}
}
</code>
<console>
Tue May 13 00:00:00 EDT 2009
123.0
ABCabc
true
3+3
</console>
--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>