【问题标题】:DateTime is rounded up to the next day using ExcelLibrary使用 ExcelLibrary 将 DateTime 向上舍入到第二天
【发布时间】:2016-09-14 14:17:02
【问题描述】:

我写入 Excel 的日期时间总是四舍五入到第二天:

workSheet.Cells[0, 0] = new Cell(DateTime.Now, new CellFormat(CellFormatType.DateTime, @"HH:mm:ss"));

在输出 Excel 文件中,单元格获取以下值:29/09/2013 00:00:00

此示例中的 DateTime.Now 是 28/09/2013 19:42:23

【问题讨论】:

  • @pnuts 是的。我刚试过。

标签: excel datetime excellibrary


【解决方案1】:

我最终将单元格值作为字符串而不是 DateTime 传递:

 workSheet.Cells[0, 0] = new Cell(DateTime.Now.ToString(@"HH:mm:ss:ff"),
                                  new CellFormat(CellFormatType.DateTime, @"HH:mm:ss"));

【讨论】:

    【解决方案2】:

    如果您使用 ExcelLibrary 项目源代码,您可以通过以下方式解决此问题:

    1. 转到此位置的 SharedResource 类:[项目源代码文件夹]\Office\BinaryFileFormat 文件夹

    2. 如下更改EncodeDateTime函数:

      public double EncodeDateTime(DateTime value)
      {
          double days = (value - BaseDate).Days;
          //if (days > 365) days++;
          return days;
      }
      
    3. 将 DataTime 对象传递给具有首选格式的 Cell:

      worksheet.Cells[iIndex, j] = new Cell(((DateTime)cellValue), new CellFormat(CellFormatType.DateTime, @"dd/MM/yyyy"));
      

    【讨论】:

      【解决方案3】:

      您需要使用 DateTime.FromOADate 将日期格式从 OLE 自动化转换为 .net 格式。

      If oCell.Format.FormatType = CellFormatType.Date OrElse oCell.Format.FormatType = CellFormatType.DateTime Then
       Dim d As Double = Double.Parse(oCell.Value)
      
       Debug.print(DateTime.FromOADate(d))
      
      End If
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 2013-11-17
        • 2016-01-17
        相关资源
        最近更新 更多