Casting Range.Value2 of Excel interop to string

我们两清 提交于 2019-12-02 02:02:54

问题


I import some values from Excel sheets in C# application. One column is a text basically but can contain any values. I used the following:

Range range = ... // getting this from Excel, works fine
string myString = (string)range.Value2;

When the cell contains text, this is working. But when it contains, for example, 123, the debugger shows 123.0 for range.Value2 and conversion to string fails with exception.

I wonder, how to write the most general conversion for all kinds of cells. At least string and integer, may be float content.


回答1:


I found the solution which may be not so nice but works:

myString = range.Value2 == null ? "" : range.Value2.ToString();

May be something better exists.



来源:https://stackoverflow.com/questions/30231413/casting-range-value2-of-excel-interop-to-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!