2
votes

I'm upgrading a C# dotnet v1.1 application to 3.5 and encountered this error on running under 3.5 for this first time. This is an app that has run happily in production for years, and on my desktop in 1.1, so I'm assuming something's changed in the API for excel COM between 1.1 and 3.5

full exception:

InvalidClassCastException was unhandled
Unable to cast COM object of type 'System.__ComObject' to interface type 'Excel._Workbook'. 

This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208DA-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

code:

Excel.ApplicationClass excel = new Excel.ApplicationClass();
excel.Application.Workbooks.Add(true);
((Excel.Range)excel.Cells[1,1]).EntireRow.Font.Bold = true;     

excel.Cells[1,1] = "col a";
excel.Cells[1,2] = "col b";
excel.Cells[1,3] = "col c";

// here loop and populate rows, nothing special just as above, all strings

excel.Visible = true;

Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet;
((Excel._Workbook)worksheet).Activate();

How do I resolve this? I tried renaming from Excel.ApplicationClass to Excel.Application as this post on MSDN Social suggested, but no luck :(

1
A book is a collection of sheets. Casting a WorkSheet to a WorkBook should produce a loud bang. It is quite mysterious to me how that could work before.Hans Passant
Generally ... do NOT use the classes (and a few interfaces?) prefixed with _ in the PIA. These should be considered "internal" -- the PIA hierarchy may very well have changed.user166390

1 Answers

1
votes

turns out the answer is to call activate on the WorkSheet, not the WorkBook, oops ;-)

((Excel._Worksheet)worksheet).Activate();