gpt4 book ai didi

c# - 如何通过 OpenXML 在当前事件的 Word 文档中设置自定义属性

转载 作者:太空宇宙 更新时间:2023-11-03 16:16:58 24 4
gpt4 key购买 nike

到目前为止,我已经能够通过使用 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 .

问题是我的自定义属性被插入到 OpenXML 文件格式的 document.zip\customXml 文件夹中的 xml 文件(例如 item1.xml)中。稍后,当我想读取我的自定义属性时,我使用了空的 WordProcessingDocument.CustomFilePropertiesPart。事实上,我发现 CustomFilePropertiesPart 引用了 document.zip\docProps\custom.xml 文件。

因此,除了使用 doc.CustomXMLParts.Add(openxml);,我应该使用什么来填充正确的 xml 文件,即 document.zip\docProps\custom.xml?

编辑我已经尝试了 Mishra 提出的解决方案但没有成功,即自定义属性并不总是被保存。然而,由于他发布了这个解决方案,我再次尝试并找到了 here您首先需要将文档标记为未保存:

doc.CustomDocumentProperties.Add("MyProp", False, MsoDocProperties.msoPropertyTypeNumber, 123);
doc.Saved = false;
doc.Save();

最佳答案

您不能使用 CustomXMLParts 集合设置客户属性。如果您打开了文档,最好保持简单并使用 CustomDocumentProperties 集合,它非常快速和简单。仅当要插入的数据变化很大时,我才会在 open doc 中使用 open XML。

关于c# - 如何通过 OpenXML 在当前事件的 Word 文档中设置自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15526800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com