1
votes

Error CS0266: Cannot implicitly convert type 'object' to 'Microsoft.Office.Interop.Excel.Range'. An explicit conversion exists (are you missing a cast?)

Pls help :)

    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
    Excel.Range range;

    xlApp = new Excel.Application();
    xlWorkBook = xlApp.Workbooks.Open("C:\\Base.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(3);

    range= xlWorkSheet.UsedRange.Columns[1,Type.Missing];
4
Have you tried range= (Range) xlWorkSheet.UsedRange.Columns[1,Type.Missing]; ? - Damb

4 Answers

7
votes

The Columns indexer is typed to return object and the variable range is typed to Excel.Range. This conversion is not legal (a less specific type to a more specific type). You need to explicitly cast the result to make the conversion work

range = (Excel.Range)(xlWorkSheet.UsedRange.Columns[1,Type.Missing]);
4
votes

You get this exception only if Embed Interop types of the Microsoft.Office.Interop.Excel is set to false. If it is set to true then you will not get this exception

1
votes

I think the problem is in this line:

xlWorkSheet.UsedRange.Columns[1,Type.Missing];

it probably returns object, so you have to cast it to Excel.Range

0
votes

This will solve the problem:

Excel.Worksheet xlWorkSheet = (Excel.Worksheet)(xlWorkBook.Worksheets.get_Item(3));
Excel.Range range= (Excel.Range)(xlWorkSheet.UsedRange.Columns[1,Type.Missing]);

Just try this. Hope it works for you.