Category Archives: apache
Reading .xls in Java with Apache Poi
Here is my sample java code explanation for accesing an microsoft excel file with apache’s framework poi;
First initiliaze the stream definitions;
InputStream myxls = new FileInputStream(myXlsFilePath);
HSSFWorkBook workBook = new HSSFWorkBook(myxls);
Now we are nearly ready to read some data from [filename].xls but before reading we need to reach the sheet via its name or index. (Don’t forget index numbers starts from 0)
And here we go;
for (int i = 0; i < 10; i++){row = sheet0.getRow(i);
for (int j = 0; j < 10; j++)
switch (row.getCell((short) j).getCellType()){case HSSFCell.CELL_TYPE_NUMERIC:
double number = row.getCell((short) j).getNumericCellValue();
System.out.println(“["+i+","+j+"] number = ” + number);
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
boolean bool = row.getCell((short) j).getBooleanCellValue();
System.out.println(“["+i+","+j+"] bool = ” + bool);
break;
case HSSFCell.CELL_TYPE_STRING:
String string = row.getCell((short) j).getStringCellValue();
System.out.println(“["+i+","+j+"] string = ” + string);
break;/* We may increase the options */
default: System.out.println(“cant recognize the cell type.”);
}
}
PS: sorry about the indentation, i couldn’t handle it…