我使用POI HSSF API在Java我的excel操作。我在Excel单元格中的一个已经日期值“8/1/2009”,虽然我尝试阅读使用HSSF API该值,检测的细胞类型为数字,并返回我的约会的“双师型”的价值。请参见下面的示例代码:

cell = row.getCell(); // date in the cell '8/1/2009'
switch (cell.getCellType()) {

case HSSFCell.CELL_TYPE_STRING:
    cellValue = cell.getRichStringCellValue().getString();
    break;
case HSSFCell.CELL_TYPE_NUMERIC:
    cellValue = new Double(cell.getNumericCellValue()).toString();
    break;
default:
}

Cell.getCellType()返回NUMERIC_TYPE因此该代码转换成一倍的时间! :(

有什么办法来读取日期,因为它是在HSSF POI!?

有帮助吗?

解决方案

您可以看看:

HSSFDateUtil.isCellDateFormatted()

请参阅有关详细信息,POI可怕表格格式API上HSSFDateUtil:

http://poi.apache.org/ apidocs /组织/阿帕奇/ POI / HSSF /的usermodel / HSSFDateUtil.html

这也提供了返回Excel的getExcelDate()和Java日期getJavaDate()一些辅助方法。你必须要有所警惕不同的日期格式,虽然...

其他提示

如果要引用相同的格式的日期在Excel文件,你应该使用CellDateFormatter。示例代码:

CellValue cValue = formulaEv.evaluate(cell);
double dv = cValue.getNumberValue();
if (HSSFDateUtil.isCellDateFormatted(cell)) {
    Date date = HSSFDateUtil.getJavaDate(dv);

    String dateFmt = cell.getCellStyle().getDataFormatString();
    /* strValue = new SimpleDateFormat(dateFmt).format(date); - won't work as 
    Java fmt differs from Excel fmt. If Excel date format is mm/dd/yyyy, Java 
    will always be 00 for date since "m" is minutes of the hour.*/

    strValue = new CellDateFormatter(dateFmt).format(date); 
    // takes care of idiosyncrasies of Excel
}

Excel将日期和时间为数字......乔恩说,它更好的,所以我不会在这里呼应他......

但是,你已经把什么问题的示例代码是在 HTTP ://poi.apache.org/spreadsheet/quick-guide.html#CellContents

如果您使用POI 3.5可以使用以下

cell.getDateCellValue()方法。这将为2007年的Excel以及工作。

由于POI 3.15β3某些功能deprecated。 您可以检查数据格式和检索如Java Date

SimpleDateFormat format = new SimpleDateFormat("");
String cellValue;
if(cell != null && cell.getCellTypeEnum() != CellType.STRING &&
    cell.getCellTypeEnum() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)){

    cellValue = format.format(cell.getDateCellValue());
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top