2013-03-20 79 views
2
設置自定義屬性

到目前爲止,我已經能夠通過使用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(); 

回答

0

你不能使用CustomXMLParts集合設置custome屬性。如果你打開文檔更好,保持簡單並使用CustomDocumentProperties集合,它非常快速和簡單。只有在插入的數據變化很大的情況下,我纔會在open doc中使用open XML。

+0

謝謝,這可行,但您需要將文檔標記爲未保存,以確保保存自定義屬性。查看我的編輯 – 2013-03-25 10:25:58

0

檢查this post - 它解釋瞭如何給自定義屬性到Word。

相關問題