2015-09-04 92 views
1

我嘗試使用c#工具將自定義文檔屬性添加到單詞。 我可以像編輯等編輯內置屬性的值。將自定義文檔屬性添加到單詞用c#

但是,使用該代碼,我沒有得到任何例外,但在word文檔中沒有自定義屬性。

object oDocCustomProps; 
string strIndex = String.Empty; 
string strValue; 
Microsoft.Office.Interop.Word.Application wordApp = 
    new Microsoft.Office.Interop.Word.Application { Visible = false }; 
Microsoft.Office.Interop.Word.Document doc = 
    wordApp.Documents.Open("C:\\test.docx", ReadOnly: false, Visible: false); 
oDocCustomProps = document.CustomDocumentProperties; 
Type typeDocCustomProps = oDocCustomProps.GetType(); 
strIndex = "Testindex"; 
strValue = "Testvalue"; 
object[] oArgs = {strIndex, false, MsoDocProperties.msoPropertyTypeString, strValue}; 
typeDocCustomProps.InvokeMember("Add", BindingFlags.Default | BindingFlags.InvokeMethod, 
    null, oDocCustomProps, oArgs); 
document.save(); 
document.close(); 

編輯

public void addCustomDocumentPropertys() 
    { 

     object oMissing = Missing.Value; 
     object oDocBuiltInProps; 
     object oDocCustomProps; 


     oDocBuiltInProps = oDoc.BuiltInDocumentProperties; 
     Type typeDocBuiltInProps = oDocBuiltInProps.GetType(); 

     //Get the Author property and display it. 
     string strIndex = String.Empty; 
     string strValue; 

     oDocCustomProps = oDoc.CustomDocumentProperties; 
     Type typeDocCustomProps = oDocCustomProps.GetType(); 

     foreach (DataRow row in dt_customAttributes.Rows) 
     { 
      strIndex = row[0].ToString(); 
      strValue = row[1].ToString(); 
      object[] oArgs = {strIndex,false, 
       MsoDocProperties.msoPropertyTypeString, 
       strValue}; 

      typeDocCustomProps.InvokeMember("Add", BindingFlags.Default | 
             BindingFlags.InvokeMethod, null, 
             oDocCustomProps, oArgs); 
     } 
    } 
+0

我的編輯適合我......但我現在不爲什麼:D – Ezak

回答

0

你可以做這樣的事情

Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application { Visible = false }; 
Microsoft.Office.Interop.Word.Document Doc = wordApp.Documents.Open("C:\\test.docx", ReadOnly: false, Visible: false); 

Doc.BuiltInDocumentProperties["Title"].Value = this.Title.Text; 
Doc.BuiltInDocumentProperties["Subject"].Value = this.Subject.Text; 
Doc.BuiltInDocumentProperties["Category"].Value = this.Category.Text; 
Doc.BuiltInDocumentProperties["Keywords"].Value = this.Keywords.Text; 
Doc.BuiltInDocumentProperties["Author"].Value = this.Author.Text; 
Doc.BuiltInDocumentProperties["Comments"].Value = this.Comments.Text; 
+0

我可以編輯內置屬性的值,如作者等,但我的問題是添加customDocumentProperties – Ezak

0

我有同樣的奇怪的東西,它原來那個字不保存,如果你只改變CustomDocumentProperties!您需要告訴單詞,通過將doc.saved設置爲false來保存它。

希望這會有所幫助。 最好的問候 弗蘭克

相關問題