What is the difference between .text, .value, and .value2?

后端 未结 6 2002
孤独总比滥情好
孤独总比滥情好 2020-11-22 00:07

What is the difference between .text, .value, and .value2? Such as when should target.text, target.value, and target.value2 be used?

6条回答
  •  孤街浪徒
    2020-11-22 00:39

    Regarding conventions in C#. Let's say you're reading a cell that contains a date, e.g. 2014-10-22.

    When using:

    .Text, you'll get the formatted representation of the date, as seen in the workbook on-screen:
    2014-10-22. This property's type is always string but may not always return a satisfactory result.

    .Value, the compiler attempts to convert the date into a DateTime object: {2014-10-22 00:00:00} Most probably only useful when reading dates.

    .Value2, gives you the real, underlying value of the cell. In the case for dates, it's a date serial: 41934. This property can have a different type depending on the contents of the cell. For date serials though, the type is double.

    So you can retrieve and store the value of a cell in either dynamic, var or object but note that the value will always have some sort of innate type that you will have to act upon.

    dynamic x = ws.get_Range("A1").Value2;
    object  y = ws.get_Range("A1").Value2;
    var     z = ws.get_Range("A1").Value2;
    double  d = ws.get_Range("A1").Value2;      // Value of a serial is always a double
    

提交回复
热议问题