c# - 在 Visual Studio C# 中通过代码打开 Word 文档

标签 c# .net vsto

我正在使用 Visual Studio 进行 Office 开发。并收到以下错误

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 )

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 的许可。无法注册“Microsoft.Office.Interop.Word.dll”dll。我花了几乎整整一周的时间才弄清楚这一点。注意:亲自查看;下载-安装-运行“RegDllView”。您可以看到“WINWORD.EXE”的所有已注册 DLL。请注意,不会显示 {000209FF-0000-0000-C000-000000000046}。即使尝试使用该程序手动注册“Microsoft.Office.Interop.Word.dll”也会失败,并显示错误代码 127。我相信解决方法实际上是使用 Microsoft.Office 中提供的“文档”界面。 Interop.Word.dll。它只是 WINWORD.EXE 的包装器。

关于c# - 在 Visual Studio C# 中通过代码打开 Word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6539192/

相关文章:

c# - 字符串未被识别为有效的日期时间,当它出现时?

c# - Binder.GetMember 方法不打算使用?为什么?

.net - WPF DataGrid 验证/绑定(bind)模式错误

c# - 如何在 VSTO 中自动调整功能区控件的大小?

c# - 基于 Excel 工作表更改启用/禁用功能区按钮 - VSTO

c# - Blazor 是否有与 WinForms 的 KeyboardEventArgs 键等效的枚举类型?

C# 集合继承

.net - 如何使用 vb 6 中制作的 dll 到 c#.net 3.5 应用程序?

c# - TransformToAncestor 给我错误的转换

deployment - 如何为我的其他版本的Office Addin制作单一安装程序