I have a "template" docx document which contains the desired layout, and wish to insert content using C#, but I cannot find a way to uniquely address specific sections of the document, such as paragraphs or tables. What is the best way to uniquely identify elements in the document? Thanks, Matt Sharpe.
4 Answers
How is your template built? Does it use an underlying XML Schema loaded as part of the *.docx? Or are you using content controls off of the Developer ribbon, in which case each control is uniquely identified by a given tag name? Both of these approaches would make identifying certain sections of your document easier as you could control where tables or paragraphs would be.
Also, you may want to consider using the Open XML SDK 2.0 (uses .NET 3.5). It includes a handy Document Reflector tool that allows you to open up and inspect any Open XML document and shows how to generate the code for any element you click on.
Apart from that, to learn more about content controls you can check these posts:

- 21,988
- 13
- 81
- 109

- 94,561
- 19
- 163
- 174
-
Cheers, I will take a look at those links. Thanks very much. – Matthew Sharpe Sep 09 '09 at 10:12
Can you use document variables/fields? Just go to Insert->Quick Parts->Fields->Doc Variable, enter name of variable.
example: http://www.codeproject.com/KB/office/Fill_Mergefields.aspx
You could also just use placeholder text values like "##insert_first_name##" and then do a search and replace for those variables.
example: Link

- 21,988
- 13
- 81
- 109

- 4,890
- 2
- 20
- 26
-
Thanks for your response. The DocVariable looks interesting, and we could potentially use that for bits of text. However, it does not address the issue of uniquely identifying tables. – Matthew Sharpe Sep 02 '09 at 08:23
I think you are looking for either bookmarks, or content controls (on the Ribbon's Developer tab, code example here)
I've used Named Ranges in Excel for the same purpose.

- 21,988
- 13
- 81
- 109

- 10,037
- 2
- 35
- 53
-
Thanks very much, I will take a look in the Developer tab in the Ribbon... I had forgotten it was there ;-) – Matthew Sharpe Sep 09 '09 at 10:12
There are several options to do this.
I have created a simple open-source library that will replace tags by values.
For example Hi {name}
with data={name:"John"}
will be replaced by Hi John
.
Here it is : https://github.com/edi9999/docxtemplater
Demo: http://javascript-ninja.fr/docxgenjs/examples/demo.html

- 19,701
- 13
- 88
- 127
-
1tanks @edi9999 It work very nice with .docx, but have same problem with .pptx. – Massimo212121 Sep 08 '15 at 13:07
-
1It also works with pptx (use `PptxGen = require("docxtemplater").PptxGen` instead) – edi9999 Sep 08 '15 at 13:36
-
Would you be interested if they was an http api that could be called from C# ? – edi9999 Dec 05 '15 at 11:03