以下单元格包含数字/字符串值的打印语句之间有什么区别?

What is the difference between below print statements where the cell holds a Numeric / String value?

下面单元格包含数字/字符串值的打印语句之间有什么区别? //尝试打印excel单元格

中的值
    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);

这会打印 cell.toString() returns。例如 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());

这仅在单元格包含文本时有效。否则它会抛出异常。参见 Cell.getStringCellValue


System.out.println(cell.getNumericCellValue());

这仅在单元格包含数字内容(数字或日期)时有效。否则它会抛出异常。参见 Cell.getNumericCellValue


更好的方法是使用 DataFormatter.

DataFormatter formatter = new DataFormatter();
...
Cell cell = row.getCell(0);
String cellContent = formatter.formatCellValue(cell);
System.out.println(cellContent);

这适用于所有类型的单元格内容,因为 DataFormatter.formatCellValue returns 无论单元格类型如何,单元格的格式化值都是 String