3

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.

1
  • I'm posting this comment in case anyone else is trying to do something similar and coming up against problems. If you want to parse every cell and get the value for each, this works: Excel.Range rng = (Excel.Range)xlWorkSheet.Cells[rCnt, cCnt]; string cellValue = rng.Value.ToString(); Commented Sep 27, 2017 at 10:30

1 Answer 1

8

don't cast the double value. Simply call ToString to get

The string representation of the value of this instance.

string str = (range.Cells[rCnt, cCnt] as Excel.Range).Value2.ToString();

EDIT:

calling ToString on a string is not necessary, since it is already a string. You can simply write it like this:

Console.WriteLine("Row:", str);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this is now working but the value str appears to be blank, so I am obviously doing something wrong (new to c#), any idea how I can get it to output the value of each cell to the console? There is data in the sheet.
Also, with that solution, the part str.ToString() is useless: just print str to the console.
@davidjwest I don't have much knowledge about Excel interop. But it seems that you have a range of values. You should research for "get all values from excel range." May be this post can help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.