Unable to cast COM object of type 'System.__ComObject' to interface type 'Excel._Workbook'
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:
Invali开发者_如何学PythondClassCastException 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 :(
turns out the answer is to call activate on the WorkSheet, not the WorkBook, oops ;-)
((Excel._Worksheet)worksheet).Activate();
精彩评论