views:

217

answers:

2

I have a .NET C# windows app that I need to read some excel data into. I have started by writing some unit tests .. one of the first just trys to instantiate a Workbook, and it is throwing this error ...

System.Runtime.InteropServices.COMException: System.Runtime.InteropService.COMException: Retrieving the COM class factory for component with CLSID {GUID} failed due to the following error: 80040154 Class not registered {Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

This piece of the app is really simple, the one method, public Workbook RetrieveWorkbook() { return new Workbook(); }

and one unit test that calls this function.

Code is using Microsoft.Office.Interop.Excel.

I went into the dcom config utility and verified that access seem to be correct. What am I missing? Any thoughts?

+3  A: 

The MSDN Library article for the Workbook class constructor is quite explicit:

Microsoft.Office.Tools.Excel.Workbook host items cannot be created programmatically.

Use the Application.Workbooks.Add() method, sample code is here.

Hans Passant
Thanks!! I was trying to use the Add() first, but could not get past a 'Null reference error' and could not find any useful info on the expected paramaters. The sample code you provided shows that I don't need any those extra params I was trying to send though .. I will give this way a try. Thanks!1
Chris
Since I am starting the Excel.Application just a few lines before I try to .Add()the workbook, the workbook collection is always null. Not sure how the sample code works because I can't get that code to run without a null reference exception. Not sure what I am missing.
Chris
I dunno, works fine on my machine!
Hans Passant
Let me make sure I understand .. on your machine, when you create a new Application, the Workbooks collection has been initialized?
Chris
I got it ... Thanks you nobugz and Gary!!!!!!
Chris
A: 

Like the answer above, the code below works fine:

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
object o = Type.Missing;
Workbook wkb = xlApp.Workbooks.Add(o);
Gary Joynes