使用POI HSSF API从Excel单元格读取date值
我正在使用POI HSSF API来处理Java中的Excel操作。 我在我的excel单元格中有一个date值“8/1/2009”,当我尝试使用HSSF API读取这个值时,它将单元格types检测为Numeric并返回我的date的“Double”值。 请参阅下面的示例代码:
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,因此这段代码将date转换为double! 🙁
有什么方法可以读取HSSF POI中的date吗?
你可以看看:
HSSFDateUtil.isCellDateFormatted()
有关HSSFDateUtil的更多详细信息,请参阅POI Horrible Spreadsheet Format API:
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDateUtil.html
这也为返回Excel getExcelDate()
和JavadategetJavaDate()
提供了一些帮助方法。 你需要有点警惕不同的date格式,虽然…
如果您想以与Excel文件中相同的格式引用date,则应该使用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将date和时间视为数字… Jon说得好,所以我不会在这里回应他。
但是,您在问题中提供的示例代码是http://poi.apache.org/spreadsheet/quick-guide.html#CellContents
如果您使用POI 3.5,则可以使用以下内容
cell.getDateCellValue()方法。 这也适用于Excel 2007。
自POI 3.15 beta3以来,一些function已被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()); }