Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.InvalidCastException Double to String

Tags:

c#

casting

excel

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.

like image 372
davidjwest Avatar asked Dec 14 '25 17:12

davidjwest


1 Answers

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);
like image 99
Mong Zhu Avatar answered Dec 16 '25 11:12

Mong Zhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!