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.Ope
using Microsoft.Office.Interop.Excel;
string path = "C:\\Projects\\ExcelSingleValue\\Test.xlsx ";
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Worksheet excelSheet = wb.ActiveSheet;
//Read the first cell
string test = excelSheet.Cells[1, 1].Value.ToString();
wb.Close();
This example used the 'Microsoft Excel 15.0 Object Library' but may be compatible with earlier versions of Interop and other libraries.
Here's a solution that may work better in the case you are referencing objWorksheet.UsedRange.
Excel.Worksheet mySheet = ...(load a workbook, etc);
Excel.Range myRange = mySheet.UsedRange;
var values = (myRange.Value as Object[,]);
int rowNumber = 3, columnNumber = 5;
string cellValue = Convert.ToString(values[rowNumber, columnNumber]);
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.
//THIS IS WORKING CODE
Microsoft.Office.Interop.Excel.Range Range_Number,r2;
Range_Number = wsheet.UsedRange.Find("smth");
string f_number="";
r2 = wsheet.Cells;
int n_c = Range_Number.Column;
int n_r = Range_Number.Row;
var number = ((Range)r2[n_r + 1, n_c]).Value;
f_number = (string)number;
The issue with reading single Excel Cell in .Net
comes from the fact, that the empty cell is evaluated to a Null
. Thus, one cannot use its .Value
or .Value2
properties, because an error shows up.
To return an empty string, when the cell is Null
the Convert.ToString(Cell)
can be used in the following way:
Excel.Workbook wkb = Open(excel, filePath);
Excel.Worksheet wk = (Excel.Worksheet)excel.Worksheets.get_Item(1);
for (int i = 1; i < 5; i++)
{
string a = Convert.ToString(wk.Cells[i, 1].Value2);
Console.WriteLine(a);
}
Please try this. Maybe this could help you. It works for me.
string sValue = (range.Cells[_row, _column] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
//_row,_column your column & row number
//eg: string sValue = (sheet.Cells[i + 9, 12] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
//sValue has your value