关于.net:在Visual Studio C#中通过代码打开Word文档

Opening Word Document through code in Visual Studio C#

我正在使用Visual Studio开发Office开发。并收到

下面的错误

1
2
3
4
5
Error:
**
Unable to cast COM object of type 'Microsoft.Office.Interop.Word.ApplicationClass' to interface type 'Microsoft.Office.Interop.Word._Application'.
This operation failed because the QueryInterface call on the COM component for the interface with IID '{00020970-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
**

代码:(也在https://gist.github.com/1056809上)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
if (File.Exists((string)strDocPath))
{
    Word.Application wdApp = new Word.Application();
    wdApp.Visible = true; //Error thrown here

    object readOnly = false;
    object isVisible = true;
    object oMissing = System.Reflection.Missing.Value;

    //Open the word document
    //Error thrown on line below.
    Word.Document aDoc = wdApp.Documents.Open(ref strDocPath, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing,
                                              ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref isVisible,
                                              ref oMissing, ref oMissing, ref oMissing, ref oMissing);


    // Activate the document
    aDoc.Activate();
}

这是什么错误?如何避免呢?


问题是HKEY_LOCAL_MACHINE \\\\ SOFTWARE \\\\ Classes \\\\ CLSID {000209FF-0000-0000-C000-000000000046}无法注册。
尽管该类在您的注册表中存在(Microsoft.Office.Interop.Word.ApplicationClass),但这并不意味着它已被注册。由于某些无法解释的原因,Microsoft不允许注册Microsoft.Office.Interop.Word.dll,因此,如果您在代码中引用" ApplicationClass"类,则不允许这样做。部署到实际服务器时,您会遇到此问题。您不会在本地/构建计算机上收到错误消息/警告。
这里是一般错误的样子:

Retrieving the COM class factory for component with CLSID
{000209FF-0000-0000-C000-000000000046} failed due to the following
error: 80040154 Class not registered (Exception from HRESULT:
0x80040154 (REGDB_E_CLASSNOTREG)).

结论:
即使您已安装/激活了Microsoft Office 2007/2010


尝试将if语句后的第一行替换为以下内容:

1
Microsoft.Office.Interop.Word.Application wdApp = new Microsoft.Office.Interop.Word.Application();

然后确保您添加对" Microsoft Word 12.0对象库" COM对象的引用,该引用在解决方案资源管理器中看起来像" Microsoft.Office.Interop.Word"。

我对此进行了测试,然后出现了一个空白的MS Word应用程序。因此,让我们看看我们能否达到目标。


n