到目前爲止,我已經能夠通過使用VSTO並通過添加一個包流活動文檔設置爲一個Word文檔的自定義屬性,因爲它遵循如何將當前活動的Word文檔中通過的OpenXML
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();
謝謝,這可行,但您需要將文檔標記爲未保存,以確保保存自定義屬性。查看我的編輯 – 2013-03-25 10:25:58