Unit test with Microsoft.Office.Interop dll fails

2019-01-27 00:41发布

I've written a unit test. The code under test references Microsoft.Office.Interop.Excel.dll.

The test runs fine on my machine but fails on the build server. It fails on the line where the Excel application is instantiated:

var application = new Application { Visible = Visible };

The error is:

System.Runtime.InteropServices.COMException: 
Retrieving the COM class factory for component with CLSID 
{00024500-0000-0000-C000-000000000046} failed due to the following error:
80040154 Class not registered

Does this mean I have to install the Redistributable Primary Interop Assemblies on my build server? And if so, do I also need to install Excel on the build server?

Edit: Microsoft.Office.Interop.Excel.dll is included in my solution and it is referenced from there.

3条回答
对你真心纯属浪费
2楼-- · 2019-01-27 00:59

Yes, it looks like you need to install the PIA:

The primary interop assemblies for Microsoft Office products are also available in a redistributable Microsoft Windows Installer package:

The package for Microsoft Office 2003 is available for download from the Microsoft Download Center (http://go.microsoft.com/fwlink/?LinkId=50479).

The package for the 2007 Microsoft Office system is available for download from the Microsoft Download Center (http://go.microsoft.com/fwlink/?LinkId=72637).

And, for completeness, the Office 2010 package is here: (http://www.microsoft.com/download/en/details.aspx?id=3508)

查看更多
Juvenile、少年°
3楼-- · 2019-01-27 01:01

You'll need to install Office and the Primary Interop Assemblies for that version, or Visual Studio to get this to work. You might run into COM issues with running in a CI environment, and if you can restructure your tests to avoid using Office Interop, I'd highly recommend it.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-27 01:21

If you add Microsoft.Office.Interop.Excel.dll to the solution in a library folder and reference the assembly there the build machine should get the required assembly when you promote. Otherwise, you're referencing an assembly that comes with the installation of Excel. Also, if you try to distribute your application without putting it in the solution anyone who tries to run your application that doesn't have Excel installed will get run time errors.

Or course, you're other option if you do not want to redistribute the assembly is to put a try/catch around the code that calls the Excel assembly and then display a message to the user saying an installation of Excel is required.

Finally, each version of Excel (2010, 2007, etc) has different version numbers. Meaning, if you're using the 2010 assembly and someone has 2007 Excel installed they will get run time errors. The answer I ended up using for that was reflection to pick which assembly is used in their environment.

查看更多
登录 后发表回答