【问题标题】:How to set custom properties in the currently active Word document via OpenXML如何通过 OpenXML 在当前活动的 Word 文档中设置自定义属性
【发布时间】: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


    【解决方案1】:

    您不能使用 CustomXMLParts 集合设置自定义属性。如果您的文档打开更好,请保持简单并使用 CustomDocumentProperties 集合,它非常快速和容易。只有当要插入的数据变化很大时,我才会在 open doc 中使用 open XML。

    【讨论】:

    • 谢谢,这可行,但您需要将文档标记为未保存,以确保保存自定义属性。查看我的编辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多