Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerating a .docx from a .dotx using merge (SimpleField) fields
    text
    copied!<p>So, first off here's my code to open the dotx and create a new docx copy (of which the copy is then modified). Cut for brevity, but essentially takes 3 params a data table (to make it usable by legacy systems), the UNC path as a string to a template and a UNC path as a string to the output document:</p> <pre><code>using (WordprocessingDocument docGenerated = WordprocessingDocument.Open(outputPath, true)) { docGenerated.ChangeDocumentType(WordprocessingDocumentType.Document); foreach (SimpleField field in docGenerated.MainDocumentPart.Document.Descendants&lt;SimpleField&gt;()) { string mergeFieldName = GetFieldName(field).Trim(); DataRow[] dr = dtSchema.Select("FieldName = '" + mergeFieldName + "'"); if (dr.Length &gt; 0) { string runProperties = string.Empty; foreach (RunProperties property in field.Descendants&lt;RunProperties&gt;()) { runProperties = property.OuterXml; break; } Run run = new Run(); run.Append(new RunProperties(runProperties)); run.Append(new Text(dr[0]["FieldDataValue"].ToString())); field.Parent.ReplaceChild&lt;SimpleField&gt;(run, field); } } docGenerated.MainDocumentPart.Document.Save(); } </code></pre> <p>What I did initially was take a .dot template and re-save it as a .dotx and crossed my fingers, didn't work. So instead I tried deleting all merge fields in the .dotx and adding them again. This worked - but it would only find one merge field (as a SimpleField), specifically the last one added before saving the .dotx. Looking further at the template using the open XML productivity tool I can see that all other merge fields are of type w:instrText which is why they're being ignored.</p> <p>I'm literally just starting out with OpenXML as we're looking to replace our current office automation with it so I know very little at this point. Could someone please instruct me a bit further or point me to a good resource? I've Google'd around a bit but I can't find my specific problem. I am trying to put off reading through the whole SDK documentation (I know, I know!) as I need to get a solution put together quickly so am focusing on a single task which is to take our existing .dot templates, convert them to .dotx and just replace merge fields with data to derive a .docx.</p> <p>Thanks in advance!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload