4

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.

5
  • What is the type and value of Value2 exactly? What is the exception message? Commented May 14, 2015 at 7:11
  • @SonerGönül Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException Can't convert double to string. Value2 is dynamic :) Commented May 14, 2015 at 7:14
  • So, range.Value2.ToString(); Commented May 14, 2015 at 7:29
  • @RezaArabQaeni yes, I just found similar answer myself, see below, Excel often returns null values also Commented May 14, 2015 at 7:31
  • FYI - That will blow up when range is more than 1 cell as .Value2 will return an object[] array Commented Mar 21, 2017 at 21:39

1 Answer 1

5

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

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

May be something better exists.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.