Get text over MS Word table

This is probably a little stupid, but I really need it. I have a document with 5 tables, each table has a title. The headline is plain text without a special style, nothing. I need to extract data from these tables + plus the header. Currently, using MS interop, I was able to iterate through each cell of each table, using something like this:

app.Tables[1].Cell(2, 2).Range.Text; 

But now I'm struggling to figure out how to get the text right above the table. Here is a screenshot: enter image description here

For the first table I need to get "I need this text" and for the secnd table I need to get: "And this one too please"

So basically I need the last paragraph before each table. Any suggestions on how to do this?

+6
source share
2 answers

Mellamockb in his answer gave me a hint and a good example of how to search in paragraphs. Performing his solution, I came across the "Previous" function, which does exactly what we need. Here's how to use it:

 wd.Tables[1].Cell(1, 1).Range.Previous(WdUnits.wdParagraph, 2).Text; 

The previous one takes two parameters. First, the block that you want to find from this list: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.wdunits.aspx and the second parameter is the number of units that you want to recalculate . In my case 2 worked. It seems like it should be because it is right in front of the table, but with one I got a strange special character: ♀ that looks like a female indicator.

+9
source

You can try something in this direction. I compare the paragraphs with the first cell of the table, and when there is a match, take the previous paragraph as the table heading. Of course, this only works if the first cell of the table contains a unique paragraph that cannot be found elsewhere in the document:

 var tIndex = 1; var tCount = oDoc.Tables.Count; var tblData = oDoc.Tables[tIndex].Cell(1, 1).Range.Text; var pCount = oDoc.Paragraphs.Count; var prevPara = ""; for (var i = 1; i <= pCount; i++) { var para = oDoc.Paragraphs[i]; var paraData = para.Range.Text; if (paraData == tblData) { // this paragraph is at the beginning of the table, so grab previous paragraph Console.WriteLine("Header: " + prevPara); tIndex++; if (tIndex <= tCount) tblData = oDoc.Tables[tIndex].Cell(1, 1).Range.Text; else break; } prevPara = paraData; } 

Output Example:

 Header: I NEED THIS TEXT Header: AND THIS ONE also please 
+3
source

Source: https://habr.com/ru/post/901475/


All Articles