Home » excel » c# – How do I get the value of a cell by row index and column index

c# – How do I get the value of a cell by row index and column index

Posted by: admin March 9, 2020 Leave a comment

Questions:

currently i’m doing this:

string cellValue = sheet.get_Range("A12", _missing).Value2.ToString();

this works but i really need to select a cell by row and column index.

i get a null exception when i try

string cellValue = ((Range)sheet.Cells[row, column]).Value2.ToString();

any ideas?

How to&Answers:

Where does the ArgumentNullException occur? Try separating out your code like this and step through it:

object rangeObject = sheet.Cells[row, column];
Range range = (Range)rangeObject;
object rangeValue = range.Value2;
string cellValue = rangeValue.ToString();

This will show you where the null object is.

Answer:

I had the same issue. The nullref would happen when the cell I was reading was empty.

string foo = (((Range) ActiveWorksheet.Cells[row, column]).Value2 != null
            ? ((Range) ActiveWorksheet.Cells[row, column]).Value2.ToString()
            : "Coalesce some false string here..."); 

Notice that you have to check for null before you attempt to transform or cast the value.