Modify or add a template in a Word document

I want to change a template from a large number of Word documents using a simple C # program.

All of these documents are based on a standard template for heading styles, font, etc. We would like to change this template (more precisely, title colors and other little things) and change the current documents to use this new template.

In Word, this is easily achieved by clicking on the “Document Template” in the “Design” tab of the ribbon. I used this guide for this. This works great and does exactly what it should do: change the colors of the headers, etc. according to the new template.

So the question is simple: how can I do the same thing (attach other templates and change styles) from a .NET application?

I assume that I should use the Microsoft.Office.Interop.Word namespace, but I am stuck there ...

+3
source share
1 answer

I managed to solve it myself, not so difficult. This is the code I used:

        object missing = System.Reflection.Missing.Value;
        Word.Application wordApp = new Word.ApplicationClass();
        Word.Document aDoc = null;
        object readOnly = false;
        object isVisible = false;

        wordApp.Visible = false;
        object filename = "d:\\Testdocs\\testfile.doc";
        object saveAs = "d:\\Testdocs\\output.doc";
        object oTemplate = "d:\\Testdocs\\Template.dotx";

        aDoc = wordApp.Documents.Add(ref oTemplate, ref missing,
                                     ref missing, ref missing);

        aDoc = wordApp.Documents.Open(ref filename, ref missing,
                                      ref readOnly, ref missing, ref missing,
                                      ref missing, ref missing, ref missing,
                                      ref missing, ref missing, ref missing,
                                      ref isVisible, ref missing, ref missing,
                                      ref missing, ref missing);

        aDoc.Activate();
        aDoc.set_AttachedTemplate(oTemplate);
        aDoc.UpdateStyles();

        aDoc.SaveAs(ref saveAs, ref missing, ref missing,
                    ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing);

        aDoc.Close(ref missing, ref missing, ref missing);
+2
source

All Articles