使用 NPOI 从 Excel 中的单元格获取完整的日期和时间值

Get full date and time value from a cell in Excel with NPOI

我正在尝试从 Excel 文件(旧的 xls 文件)中获取数据,特别是,一列被格式化为日期,尽管它应该被格式化为时间。

当我用NPOI读取文件时,我只得到单元格的日期部分;时间部分固定为中午12点。

当我打开 Excel 中的文件并单击单元格时,我可以看到时间已填充。

例如,在Excel中,单元格的"formula value"是:

4/23/2020  3:00:00 PM

单元格格式为:

4/23/2020

当我读取带有 NPOI 的单元格时,我得到:

var value = cell.NumericCellValue;// value = 43944.5
var dateValue = DateUtil.GetJavaDate(cell.NumericCellValue);// dateValue = {4/23/2020 12:00:00 PM}
var formattedValue = _formatter.FormatCellValue(cell);// formattedValue = "4/23/20"
var formula = cell.CellFormula;// throws exception "Cannot get a formula value from a numeric formula cell"

我阅读了 DateUtil.GetJavaDate 的代码,43944.5 确实转换为 4/23/2020 12:00:00 PM,这意味着 NumericCellValue 是已经应用格式的值。

所以我的问题是:如何使用 NPOI 获取该单元格的 4/23/2020 3:00:00 PM "formula value"?

如果您对其他库有建议,我也很乐意尝试。

尝试使用单元格的 DateCellValue 属性:

if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
{
    DateTime date = cell.DateCellValue;
    Debug.WriteLine(date.ToString("MM/dd/yyyy h:mm:ss tt"));
}