以编程方式获取段落下的文本
Get text under Paragraph programmatically
我有一个包含一些标题的大型 word 文档。这些标题分别有一个table一个child。 (如屏幕截图所示)
因此我使用了 Microsoft Interop.Word 库。我的代码看起来像这样。如何获得标题段落的 children?也许有更好的方法。
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
}
我会使用范围来做到这一点。查找第一个标题,查找下一个标题(或任何您可以用作本章结尾并获取中间内容的内容:
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);
}
}
}
我有一个包含一些标题的大型 word 文档。这些标题分别有一个table一个child。 (如屏幕截图所示)
因此我使用了 Microsoft Interop.Word 库。我的代码看起来像这样。如何获得标题段落的 children?也许有更好的方法。
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
}
我会使用范围来做到这一点。查找第一个标题,查找下一个标题(或任何您可以用作本章结尾并获取中间内容的内容:
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);
}
}
}