You should be calling the HSSFCell.getCellType() method to determine its type. Here's a method that handles cells of type String or Numeric. (You can easily add other types.) The format used for numbers will be a valid format, but won't necessarily match that of the SpreadSheet. (That's covered below.)
public static String getCellStringValue(final HSSFCell cell) {
int cellType = cell.getCellType();
String value;
if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
// Locale is optional here
DataFormatter dataFormatter = new DataFormatter(Locale.US);
value = dataFormatter.formatCellValue(cell);
} else {
// HSSFCell.CELL_TYPE_STRING
value = cell.getStringCellValue();
} // more cell types are possible. Add whatever you need.
return value;
}
That code won't necessarily format the number as it appears in Excel.
If you need the format to exactly match the spreadsheet format, you can get a formatter from the cell itself. To do this, you can use your DataFormatter instance to create a Format instance:
public static String getCellStringValue(final HSSFCell cell) {
int cellType = cell.getCellType();
String value;
if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
// Locale is optional here
DataFormatter dataFormatter = new DataFormatter(Locale.US);
Format format = dataFormatter.createFormat(cell);
value = format.format(cell.getNumericCellValue());
} else {
// HSSFCell.CELL_TYPE_STRING
value = cell.getStringCellValue();
} // more cell types are possible. Add whatever you need.
return value;
}