如何获取文档中所有内容控件的列表? [英] How to get the list of all content controls in the document?

查看:586
本文介绍了如何获取文档中所有内容控件的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用互操作,我想获取Word文档中包含的所有内容控件的列表(主体,形状,页眉,页脚..).这是正确的最佳方法吗?

I am using interop and I want to get the list of all content controls contained in word document (in the body, shapes, header, footer..). Is this the correct and the best way to do this :

public static List<ContentControl> GetAllContentControls(Document wordDocument)
{
  if (null == wordDocument)
    throw new ArgumentNullException("wordDocument");

  List<ContentControl> ccList = new List<ContentControl>(); ;
  // Body cc
  var inBodyCc = (from r in wordDocument.ContentControls.Cast<ContentControl>()
          select r);
  ccList.AddRange(inBodyCc);

  // cc within shapes
  foreach (Shape shape in wordDocument.Shapes)
  {
    if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoTextBox)
    {
      ccList.AddRange(WordDocumentHelper.GetContentControlsInRange(shape.TextFrame.TextRange));
    }
  }

  // Get the list of cc in the story ranges : wdFirstPageHeaderStory, wdFirstPageFooterStory, wdTextFrameStory (textbox)... 
  foreach (Range range in wordDocument.StoryRanges)
  {
    ccList.AddRange(WordDocumentHelper.GetContentControlsInRange(range));
  }
  return ccList;
}

public static List<ContentControl> GetContentControlsInRange(Range range)
{
  if (null == range)
    throw new ArgumentNullException("range");

  List<ContentControl> returnValue = new List<ContentControl>();

  foreach (ContentControl cc in range.ContentControls)
  {
    returnValue.Add(cc);
  }

  return returnValue;
}

致谢.

推荐答案

这是解决该问题的更短方法(VBA,但可以移植到C#中):

Here's a much shorter way of going about it (VBA, but can be ported to C#):

Sub GetCCs()
    Dim d As Document
    Set d = ActiveDocument
    Dim cc As ContentControl
    Dim sr As Range
    Dim srs As StoryRanges
    For Each sr In d.StoryRanges
        For Each cc In sr.ContentControls
            ''# do your thing
        Next
    Next
End Sub

这篇关于如何获取文档中所有内容控件的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆