Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting Range.Value2 of Excel interop to string

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.

like image 283
demonplus Avatar asked Nov 03 '25 01:11

demonplus


1 Answers

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

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

May be something better exists.

like image 147
demonplus Avatar answered Nov 04 '25 13:11

demonplus