2012-07-27 41 views
0

我正在嘗試以單詞.doc(word 97 - 2003)編程方式更新現有的自定義屬性。我最初使用Aspose解決問題,但由於許可證有限,我無法將其用於此項目。正在更新現有的自定義屬性word doc

此代碼是批量從這裏進行小修改字而不是excel Accessing Excel Custom Document Properties programatically

第一種方法用於添加自定義屬性(如果它不存在),第二種方法可以拉取自定義屬性。我還沒有想出如何更新已經存在的屬性。我認爲它可能與InvokeMember()中的動詞有關,但我找不到多少文檔。

public void SetDocumentProperty(string propertyName, string propertyValue) 
    { 
     object oDocCustomProps = oWordDoc.CustomDocumentProperties; 
     Type typeDocCustomProps = oDocCustomProps.GetType(); 

     object[] oArgs = {propertyName,false, 
          MsoDocProperties.msoPropertyTypeString, 
          propertyValue}; 

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

    } 

    public object GetDocumentProperty(string propertyName, MsoDocProperties type) 
    { 
     object returnVal = null; 

     object oDocCustomProps = oWordDoc.CustomDocumentProperties; 
     Type typeDocCustomProps = oDocCustomProps.GetType(); 

     object returned = typeDocCustomProps.InvokeMember("Item", 
                  BindingFlags.Default | 
                  BindingFlags.GetProperty, null, 
                  oDocCustomProps, new object[] { propertyName }); 

     Type typeDocAuthorProp = returned.GetType(); 
     returnVal = typeDocAuthorProp.InvokeMember("Value", 
                BindingFlags.Default | 
                BindingFlags.GetProperty, 
                null, returned, 
                new object[] { }).ToString(); 

     return returnVal; 
    } 
+0

http://docx.codeplex.com/ – 2012-07-27 19:08:57

+0

這個庫看起來不錯,但我必須.doc文件 – Curtis 2012-07-27 20:34:55

回答

0

我們通常將所有道具檢索到列表並從文檔中刪除,更改值並再次插入。我們使用DSOFile.dll方法

+0

你如何刪除所有的自定義屬性的要求? – baru 2016-03-02 11:27:15

1

不知道您是否找到了正確的答案,但對於訪問此頁面的任何人來說都是爲了設置現有的自定義文檔屬性。看起來您需要先使用BindingFlags.GetProperty然後使用BindingFlags.SetProperty設置檢索的特定項目的值來檢索文檔屬性。

您還可以添加一些自定義檢查以確定您嘗試設置的對象是否有效。

public void SetDocumentProperty(string propertyName, object value) 
    { 
     // Get all the custom properties 
     object customProperties = wordDocument.CustomDocumentProperties; 
     Type customPropertiesType = customProperties.GetType(); 

     // Retrieve the specific custom property item 
     object customPropertyItem = customPropertiesType.InvokeMember("Item", 
      BindingFlags.Default | BindingFlags.GetProperty, null, customProperties, 
      new object[] { propertyName }); 
     Type propertyNameType = customPropertyItem.GetType(); 

     // Set the value of the specific custom property item 
     propertyNameType.InvokeMember("Value", BindingFlags.Default | BindingFlags.SetProperty, null, 
      customPropertyItem, new object[] { value }); 
    }