【问题标题】:Get text under Paragraph programmatically以编程方式获取段落下的文本
【发布时间】:2016-07-29 14:51:20
【问题描述】:

我有一个包含一些标题的大型 Word 文档。这些标题分别有一个表作为一个孩子。 (如截图所示)

因此,我使用了 Microsoft Interop.Word 库。我的代码看起来像这样。我怎样才能得到一个标题段落的孩子?也许有更好的方法来做到这一点。

Application word = new Application();
Document doc = new Document();
object missing = System.Type.Missing;
doc = word.Documents.Open(ref m_FileName,
        ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing);

foreach (Paragraph paragraph in doc.Paragraphs)
{
    Style style = paragraph.get_Style() as Style;
    string text = paragraph.Range.Text;
    paragraph.Range.Tables // does not get the table under the paragraph
}

【问题讨论】:

  • Word 文档的内部结构不是分层的,而是一系列块级元素,例如段落和表格。因此,标题段落不包含表格。在您的情况下,这意味着您需要访问标题后面的段落(或者您也可以使用 doc.Tables 简单地遍历文档中的所有表格)
  • 顺便说一句:由于 .NET 4 您可以编写更紧凑的代码,因此无需指定所有缺少的参数并使用ref。你可以简单地写:word.Document.Open(m_FileName);
  • @dirk vollmar 但我需要标题作为表格的键。需要有一种方法来做到这一点。还是我错了?
  • 你能详细说明你真正想要达到的目标吗?目前还不清楚您的要求是什么。
  • @dirkVollmar 我尝试详细说明。我的要求是表格在逻辑上属于一个标题。我用 C# 编写的解析器现在应该可以找到一些具有特定名称的标题。到目前为止,这有效。每个找到的标题在该标题下都有一个表格。现在我想将表中的信息映射到它所属的标题的名称。

标签: c# ms-word office-interop


【解决方案1】:

我会使用范围来做到这一点。查找第一个标题,查找下一个标题(或任何您可以用作章节结尾并获取中间内容的内容:

Range r1 = doc.Content; 
Range r2 = doc.Content; 
r1.Find.Execute("Heading 1"); 
r2.Find.Execute("Heading 2");

Range chapter = doc.Range(r1.Start, r2.Start); 
//Console.WriteLine(chapter.Text);

foreach (Table t in chapter.Tables)
{
    foreach(Row r in t.Rows)
    {
        foreach (Cell c in r.Cells)
        {
            //Console.WriteLine(c.Range.Text);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2017-09-28
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2016-09-16
    相关资源
    最近更新 更多