How can I read a mergefield content in table cell on a docx file using C# and OpenXml

246 Views Asked by At

I have to automatically verify the content of tables in multiple docx filled by another software, some cells contains mergefield text type and because of that I can not access to the text in these cells. the code I am attaching here is a code that works in the case of a text type cell :

Table table =  wordprocessingDocument .MainDocumentPart.Document.Body.Elements<Table>().First(); 
TableRow row = table.Elements<TableRow>().ElementAt(i);
TableCell cell = row.Elements<TableCell>().ElementAt(j);
Paragraph parag = cell.Elements<Paragraph>().First();
Run run = parag.Elements<Run>().First();
Text text = run.Elements<Text>().First();

please can anyone tell me if there's a way to recuperate the content of a mergefield from a table cell.

1

There are 1 best solutions below

0
On BEST ANSWER

I finally found a solution to this, displaying the xml structure of my document has helped me enormously. By using cell.InnerXml I noticed that the run tag exists in a SimpleField tag, so I adjusted my code by adding one single line.

Table table =  wordprocessingDocument.MainDocumentPart.Document.Body.Elements<Table>().First(); 
TableRow row = table.Elements<TableRow>().ElementAt(i);
TableCell cell = row.Elements<TableCell>().ElementAt(j);
Paragraph parag = cell.Elements<Paragraph>().First();
SimpleField cellfield = parag.Elements<SimpleField>().First();
Run run = cellfield .Elements<Run>().First();
Text text = run.Elements<Text>().First();