What is the difference between below print statements where the cell holds a Numeric / String value ? //trying the print the value from an excel cell
Cell cell = row.getCell(0);
System.out.println(cell);
System.out.println(cell.getStringCellValue());
System.out.println(cell.getNumericCellValue());
Cell cell = row.getCell(0);
System.out.println(cell);
This prints what cell.toString()
returns. For example HSSFCell.toString:
public String toString() {
switch (getCellTypeEnum()) {
case BLANK:
return "";
case BOOLEAN:
return getBooleanCellValue()?"TRUE":"FALSE";
case ERROR:
return ErrorEval.getText((( BoolErrRecord ) _record).getErrorValue());
case FORMULA:
return getCellFormula();
case NUMERIC:
//TODO apply the dataformat for this cell
if (DateUtil.isCellDateFormatted(this)) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", LocaleUtil.getUserLocale());
sdf.setTimeZone(LocaleUtil.getUserTimeZone());
return sdf.format(getDateCellValue());
}
return String.valueOf(getNumericCellValue());
case STRING:
return getStringCellValue();
default:
return "Unknown Cell Type: " + getCellType();
}
}
System.out.println(cell.getStringCellValue());
This will only work if the cell contains a text. Else it throws an exception. See Cell.getStringCellValue
System.out.println(cell.getNumericCellValue());
This will only work if the cell contains numeric content (number or date). Else it throws an exception. See Cell.getNumericCellValue
Better way is using DataFormatter.
DataFormatter formatter = new DataFormatter();
...
Cell cell = row.getCell(0);
String cellContent = formatter.formatCellValue(cell);
System.out.println(cellContent);
This works for all types of cell content since DataFormatter.formatCellValue
returns the formatted value of the cell as a String
regardless of the cell type.