【问题标题】:Get full date and time value from a cell in Excel with NPOI使用 NPOI 从 Excel 中的单元格获取完整的日期和时间值
【发布时间】:2020-04-29 11:51:49
【问题描述】:

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

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

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

例如,在 Excel 中,单元格的“公式值”为:

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“公式值”?

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

【问题讨论】:

    标签: c# excel npoi


    【解决方案1】:

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

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

    【讨论】:

    • 这给了我相同的价值:它在内部使用 NumericCellValue。我在调试中检查了所有单元格的属性和私有成员,但找不到任何能给我原始价值的东西。我猜它根本没有加载到单元格对象中,我需要以另一种方式从工作表或工作簿中查询它。
    • 好的,它对我有用,但是我没有你相同的工作簿。抱歉,我无法提供更多帮助。
    • 你说得对……我看错了单元格,我觉得自己很笨!
    • 别出汗;它有时会发生在我们所有人身上。我很高兴你能够让它工作。
    猜你喜欢
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多