How to create word docs programmatically from a template

Jesper Kihlberg picture Jesper Kihlberg · Nov 29, 2010 · Viewed 62.9k times · Source

I am trying to create about 600 reports in Microsoft office Word. The documents are populated with data from a database, and images found on a local drive. I have figured out, that I might create a Word Template project in visual studio 2010, and program the template, so that when you enter a single value (id-number), it automatically fills out the entire document.

I am quite confident that this is possible. the only problem is. How do I loop through all entries in the database, open a new document based on the template and set the id-value?

for(int i = 0; i < idnumbers.Count(); i++)
{
     Word.Application app = new Word.Application();
     Word.Document doc = app.Documents.Add(@"C:\..\WordGenerator\bin\Debug\WordTemplate.dotx");
     //input the id-number below: HOW??

     doc.SaveAs(FileName: @"c:\temp\test.docx"); 
}

The application is supposed to run only once, generating the reports, and it doesn´t have to be fast. It just has to be easy to develop.

The problem here is, that it seems that the DocumentBase object is not accessible outside the Word project. The substitute Microsoft.Office.Interop.Word.Document does not have functionality like SelectContentControlsByTitle that allows me to find and set my ContentControls. And that is exactly what I need to do..


EDIT: This is what my code looks like now to insert the text into my field:

Word.Application app = new Word.Application();

Word.Document doc = app.Documents.Add(@"C:\..\test.dotx");

foreach (Word.ContentControl cc in doc.SelectContentControlsByTitle("MyCCTitle"))
{
    cc.Range.Text += "1234";
}

doc.SaveAs(FileName: @"c:\temp\test.docx");

Then an eventhandler on my template on BeforeSave fills out the document based on the text in MyCCTitle-titled object.

Answer

Jens picture Jens · Nov 29, 2010

Don't use Office Automation. Office automation opens up an instance of office in the background and performs the actions on it. Opening up an office instance 600 times doesn't seem like a very interesting thing to do. (and it would never run serverside)

Take a look at Open XML. You can find loads about it below:

http://openxmldeveloper.org/

edit: Openxmldeveloper is shutting down. Find all the sources mentioned above at http://www.ericwhite.com/ instead.