我想设置我在 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/