C#: Get index of Table after specific paragraph

835 Views Asked by At

Assume I have the following structure:-

enter image description here

I wanna get the index of second table after "1.3 The headline of paragraph3", means the next:-

The input is

1.3 The headline of paragraph3

The expected output

4

this is the forth table in the document, or you can say

The requested member of the collection equlas four.

The target of this for using the next code

Microsoft.Office.Interop.Word.Application app = new      Microsoft.Office.Interop.Word.Application();
Documents docs = app.Documents;
Document doc = docs.Open(sDocPath, ReadOnly: true);
Table t = doc.Tables[4] // 4 that what I need
1

There are 1 best solutions below

0
Jacky Choo On

You could try with the code below in VB.NET, or simply convert it to C#.

  <TestMethod()> Public Sub getDocText()
  Dim filepath As String = "C:\Test Table.docx"
  If File.Exists(filepath) AndAlso (Path.GetExtension(filepath).ToUpper.Equals(".DOCX") Or Path.GetExtension(filepath).ToUpper.Equals(".DOC")) Then
     Dim app As Word.Application = New Word.Application
     Dim doc As Word.Document = app.Documents.Open(filepath)
     Dim topic1Range As Word.Range = doc.Content
     Dim topic2Range As Word.Range = doc.Content
     Dim Find As Word.Find = topic1Range.Find()
     Find.Execute("1.2 The headline of paragraph3")

     Dim Find2 As Word.Find = topic2Range.Find()
     Find2.Execute("1.3 The headline of paragraph3")

     Dim contentRange As Word.Range = doc.Range(topic1Range.End, topic2Range.Start)
     MsgBox(contentRange.Tables.Count)
     app.Quit()
  End If
End Sub