interop - 使用 Word 互操作设置自定义文档属性

标签 interop ms-word vsto office-2010 office-addins

我想设置我在 C# 代码中创建的 word 文档的一些自定义文档属性。为此,我关注了 this MSDN article并想出了这段代码:

using Word = Microsoft.Office.Interop.Word; // Version 12.0.0.0
word = new Word.Application();
word.Visible = false;
Word._Document doc = word.Documents.Add(ref missing, ref missing, ref missing, ref missing);
logger.Info("Setting document properties");
Core.DocumentProperties properties = (Core.DocumentProperties)doc.BuiltInDocumentProperties;
properties["Codice_documento"].Value = args[3];
properties["Versione_documento"].Value = args[4];

不幸的是,每当它到达代码时,我都会收到此错误:

HRESULT: 0x80004002 (E_NOINTERFACE)



这是为什么?我完全按照我的 MSDN 中描述的方式使用了接口(interface),为什么它不起作用?

我正在为 Office 2010 和 .net 3.5 使用 Interop

最佳答案

您需要使用 CustomDocumentProperties ,而不是 BuiltInDocumentProperties .见 MSDN reference on using Custom Document Properties in Word (和 MSDN video here )。您还需要检查属性是否存在并在尝试分配其值之前创建它。

Core.DocumentProperties properties = (Core.DocumentProperties)this.Application.ActiveDocument.CustomDocumentProperties;
if (properties.Cast<DocumentProperty>().Where(c => c.Name == "DocumentID").Count() == 0)
  properties.Add("DocumentID", false, MsoDocProperties.msoPropertyTypeString, Guid.NewGuid().ToString());
var docID = properties["DocumentID"].Value.ToString();

关于interop - 使用 Word 互操作设置自定义文档属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12690409/

相关文章:

c# - VSTO 功能区库,看起来像 Word 2010 中的样式选择器

c# - 在 C# 中以编程方式设置 dllimport

c# - EnumResourceNames 问题 - 未知错误

.net - 如果我使用 WCF w/forms auth,php 或 java 客户端将如何进行身份验证?

vba - 如何更改非英语单词的字体大小?

python - 如何以编程方式将注释插入 Microsoft Word 文档?

c# - 使用 C# 将我的光标移动到 MsWord 中文本的末尾?

c# - 是否建议在 Windows 服务中运行 Visual Studio Tools for Office?

visual-studio-2008 - 如何构建Office加载项而不在构建系统上注册它?

c# - IntPtr 不包含 native 值