加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何获取文档中所有内容控件的列表?

发布时间:2020-12-15 23:57:01 所属栏目:百科 来源:网络整理
导读:我正在使用互操作,我想得到word文档中包含的所有内容控件的列表(在正文,形状,页眉,页脚..).这是正确的,也是最好的方法: public static ListContentControl GetAllContentControls(Document wordDocument){ if (null == wordDocument) throw new ArgumentNul
我正在使用互操作,我想得到word文档中包含的所有内容控件的列表(在正文,形状,页眉,页脚..).这是正确的,也是最好的方法:

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#):

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读