将自定义文档属性添加到单词用c#

问题描述:

我尝试使用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

你可以做这样的事情

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

我有同样的奇怪的东西,它原来那个字不保存,如果你只改变CustomDocumentProperties!您需要告诉单词,通过将doc.saved设置为false来保存它。

希望这会有所帮助。 最好的问候 弗兰克