2014-02-27 30 views
2

我正在編寫一個應用程序,它從Word文檔中讀出內容控件。它工作正常,但我無法獲取文檔的頁眉和頁腳中的控件。在辦公室互操作程序集中獲取Word標題/頁腳中的內容控件

這裏是我的代碼:

public static List<string> GetContentControlsList(word.Document currentWordDocument) 
{ 
    List<string> contentControlsList = new List<string>(); 

    try 
    { 
     ContentControls contentControlsCollection = currentWordDocument.ContentControls; 

     if (contentControlsCollection != null) 
     { 
      if (contentControlsCollection.Count > 0) 
      { 
       foreach (ContentControl contentControl in contentControlsCollection) 
       { 
        if (!String.IsNullOrEmpty(contentControl.Title) && !contentControlsList.Contains(contentControl.Title)) 
        { 
         contentControlsList.Add(contentControl.Title); 
        } 
       } 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     // TODO do error handling here 
    } 

    return contentControlsList; 
} 

我能夠得到正文內容控制這個代碼,但我還需要頁眉和頁腳。

+2

你需要添加額外的循環來檢查'document.storyranges'頁眉和頁腳屬於哪裏。請記住,有幾種類型的頁眉和頁腳,因此我建議使用額外的循環。在每個'storyrange'內,你會發現額外的'ContentControls'來處理。 –

+0

謝謝,我通過故事範圍循環,現在它工作 –

回答

0

此作品(代碼必須進行重構,一點點,但我認爲,原則很清楚):

public static List<string> GetContentControlsList(word.Document currentWordDocument) 
    { 
     List<string> contentControlsList = new List<string>(); 

     try 
     { 
      ContentControls contentControlsCollection = currentWordDocument.ContentControls; 

      if (contentControlsCollection != null) 
      { 
       if (contentControlsCollection.Count > 0) 
       { 
        foreach (ContentControl contentControl in contentControlsCollection) 
        { 
         if (!String.IsNullOrEmpty(contentControl.Title) && !contentControlsList.Contains(contentControl.Title)) 
         { 
          contentControlsList.Add(contentControl.Title); 
         } 
        } 
       } 
      } 

      //Get storyRanges from document for header and footer properties 
      StoryRanges storyRanges = currentWordDocument.StoryRanges; 

      foreach (Range storyRange in storyRanges) 
      { 
       ContentControls storyRangeControls = storyRange.ContentControls; 

       if (storyRangeControls != null) 
       { 
        if (storyRangeControls.Count > 0) 
        { 
         foreach (ContentControl control in storyRangeControls) 
         { 
          if (!String.IsNullOrEmpty(control.Title) && !contentControlsList.Contains(control.Title)) 
          { 
           contentControlsList.Add(control.Title); 
          } 
         } 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      //TODO do error handling here 
     } 

     return contentControlsList; 
    } 

感謝KazJaw爲他的評論。