I have excel file with sheet1 that has a value I need to read on row 2 and column 10. Here is my code.
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "Sheet1";
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
var cell = (Excel.Range)excelWorksheet.Cells[10, 2];
After getting cell object which is Excel.Range, I do not know how to read the content of that cell. I tried converting it into array and looping over it and I tried converting to string array etc. I am sure it is very simple. Is there a direct way to get just one cell value that is string?
It is better to use .Value2() instead of .Value(). This is faster and gives the exact value in the cell. For certain type of data, truncation can be observed when .Value() is used.
You need to cast it to a string (not an array of string) since it's a single value.
Please try this. Maybe this could help you. It works for me.
The issue with reading single Excel Cell in
.Net
comes from the fact, that the empty cell is evaluated to aNull
. Thus, one cannot use its.Value
or.Value2
properties, because an error shows up.To return an empty string, when the cell is
Null
theConvert.ToString(Cell)
can be used in the following way:This example used the 'Microsoft Excel 15.0 Object Library' but may be compatible with earlier versions of Interop and other libraries.