【发布时间】:2013-03-25 18:24:38
【问题描述】:
到目前为止,我已经能够通过使用 VSTO 并将包流添加到活动文档中来为 Word 文档设置自定义属性,如下所示
public static void SetCustomProperty(Microsoft.Office.Interop.Word.Document doc, string propertyName, object propertyValue)
{
using (MemoryStream stream = new MemoryStream())
using ((WordprocessingDocument wordDoc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true))
{
SetProperty(wordDoc, propertyName, propertyValue);
// Flush the contents of the package.
wordDoc.Package.Flush();
// Convert back to flat OPC by using this in-memory package.
XDocument xDoc = OpcHelper.OpcToFlatOpc(wordDoc.Package);
// Return the xml string.
string openxml = xDoc.ToString();
// Add to Word doc
doc.CustomXMLParts.Add(openxml);
}
}
SetProperty 方法的工作原理与here 的说明相同,OpcHelper 可以在here 找到,并在here 进行说明。
问题是我的自定义属性被插入到一个 xml 文件(例如 item1.xml)中,该文件位于 OpenXML 文件格式的文件夹 document.zip\customXml 中。稍后当我想阅读我的自定义属性时,我使用了空的WordProcessingDocument.CustomFilePropertiesPart。事实上,我发现CustomFilePropertiesPart 引用了 document.zip\docProps\custom.xml 文件。
所以我应该使用什么来填充正确的 xml 文件,即 document.zip\docProps\custom.xml,而不是使用 doc.CustomXMLParts.Add(openxml);?
编辑 我已经尝试过 Mishra 提出的解决方案但没有成功,即并不总是保存自定义属性。然而,自从他发布了这个解决方案后,我再次尝试,我发现 here 你首先需要将文档标记为未保存:
doc.CustomDocumentProperties.Add("MyProp", False, MsoDocProperties.msoPropertyTypeNumber, 123);
doc.Saved = false;
doc.Save();
【问题讨论】:
标签: c# vsto openxml office-interop