Home » excel » Can't read Excel cell value in Visual C#

Can't read Excel cell value in Visual C#

Posted by: admin May 14, 2020 Leave a comment

Questions:

I read How to read single Excel cell value and tried it myself. But when I gets to

string s = (myExcelWorkSheet.Cells[3, "E"] as Excel.Range).Value2.ToString();

Everything was terminated and the form was shown.

//Everything worked fine here.
string s = (myExcelWorkSheet.Cells[3, "E"] as Excel.Range).Value2.ToString();
//Everything after this was all skipped!

Why is this, and how can I fix it?

How to&Answers:

The problem with reading excel cell is that if there is nothing in it, the cell object is Null. Thus, it does not have .Value2 neither .Value.

To find a way how to avoid the check for Null, you may use Convert.ToString() which evaluates the Null to an empty string and thus does not return an error:

for (int i = 1; i < 5; i++)
{
    string a = Convert.ToString(wk.Cells[i, 1].Value2);
    Console.WriteLine(a);
}

Answer:

When the cell has a value, you need the ToString().

And when the cell doesn’t has a value, then you don’t need the ToString()!

Otherwise the whole program will skip out and everything after that was NEVER executed!!!

So I guess it’s just a problem of if the system was trying to cast a null value into a string or not!!!