Search code examples
c#.netexcelcom-interop

Milliseconds missing when getting a DateTime value from Excel using .Net Interop


If I put a DateTime value into an Excel cell using Range.set_value through .Net COM Interop, and then retrieve the value of that same cell using Range.get_value, the Millisecond part of the value is not returned, though everything else is correct.

Is this a bug?

What is the workaround? I'm guessing that using the Value2 property instead might help. Has anybody else tried this?


Solution

  • As Jon suggested, converting the DateTime to a double using DateTime.ToOADate (then back again using DateTime.FromOADate) works if you set the value using the Range.Value2 property.

    The only trouble with this property is that, if you don't already know, it doesn't tell you that the cell is supposed to be treated as a DateTime. I guess to solve this, you'd need to use a two-pass approach: get cell values using Range.get_Value to determine their type, then, for any DateTime cells, get their values again using Range.Value2, then convert using DateTime.FromOADate.