1
votes

I am writing a code in C# using Open XML SDK 2.0. I have defined some controls in Word document like TextBox, Select Option etc. I want to read their data programatically (sample given below)..

WordprocessingDocument InputWordDocument = WordprocessingDocument.Open(@"C:\Users\jayant\Desktop\Template.docx", false);
foreach (Control ctrl in InputWordDocument.MainDocumentPart.Document.Body.Descendants<Control>())
{
    Console.WriteLine(ctrl.Name.Value);
}

But it shows the name of the controls not their values.

How do I get thevalues?

2

2 Answers

2
votes

You have to use the DocumentFormat.OpenXml.Wordprocessing.Control class not the System.Windows.Forms.Control class! Change that afterwards you have to go througth the childnodes.

WordprocessingDocument InputWordDocument = WordprocessingDocument.Open(@"C:\Users\jayant\Desktop\Template.docx", false);
foreach (DocumentFormat.OpenXml.Wordprocessing.Control ctrl in InputWordDocument.MainDocumentPart.Document.Body.Descendants<Control>())
{
    ...
}

Hint: Use XmlNode it is easier to handle.

0
votes

You have to use ctrl.Id to get the relationship id instead of ctrl.Name. You need this relationship id in order to access the control contents which are stored elsewhere.

Afterwards, you may call MainDocumentPart.GetPartById(ctrl.Id) and get the control data. Before using anything, remember that you have to cast it to the correct type.