The following code opens an Excel spreadsheet and goes through it cell by cell. The Console.WriteLine call is for checking that it is working correctly.
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(@"\Extracts\Test.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
rw = range.Rows.Count;
cl = range.Columns.Count;
for (rCnt = 1; rCnt <= rw; rCnt++)
{
for (cCnt = 1; cCnt <= cl; cCnt++)
{
string str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
Console.WriteLine("Row:", str.ToString());
}
}
I get the error:
System.InvalidCastException 'Unable to cast object of type 'System.Double' to type 'System.String'.'
This refers to line:
string str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
I am aware that there is another question with the same error but that solution doesn't appear to work in this case.
Help appreciated thanks.
Excel.Range rng = (Excel.Range)xlWorkSheet.Cells[rCnt, cCnt];string cellValue = rng.Value.ToString();