Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all merge fields of word document using open xml sdk

I am beginner to open xml sdk. I am trying to find out all merge fields of document.

But I am not getting the headers and footers merge fields.

Can any one suggest a working solution?

I am trying some thing like this -

foreach (FieldCode field in docGenerated.MainDocumentPart.RootElement.Descendants<FieldCode>())
                    {

                        String fieldText = field.Text;
                        if (fieldText.StartsWith(" MERGEFIELD"))
                        {
                            Int32 endMerge = fieldText.IndexOf("\\");

                            Int32 fieldNameLength = fieldText.Length - endMerge;

                            String fieldName = fieldText.Substring(11, endMerge - 11);

                            fieldName = fieldName.Trim();
                         }
}
like image 677
Ramashanker Tripathi Avatar asked Sep 30 '22 11:09

Ramashanker Tripathi


1 Answers

You have to loop through header and footer separately, see the following code:

foreach (var header in doc.MainDocumentPart.HeaderParts)
            foreach (var cc in header.RootElement.Descendants<FieldCode>())
                //DO CODE
foreach (var footer in doc.MainDocumentPart.FooterParts)
           foreach (var cc in footer.RootElement.Descendants<FieldCode>())
                //DO CODE
like image 145
st mnmn Avatar answered Oct 05 '22 07:10

st mnmn