开发者

Change or add template in Word-document

开发者 https://www.devze.com 2023-03-11 08:34 出处:网络
I\'d like开发者_Go百科 to change the template from a lot of Word-documents using a simple C#-program.

I'd like开发者_Go百科 to change the template from a lot of Word-documents using a simple C#-program.

This documents are all based on a standard template for title styles, font, etc... We would like to change this template (more specifically: the title colors and other small things) and modify the current documents to use this new template.

In Word, this is easily achieved by clicking "Document Template" in the Designer tab in the ribbon. I used this guide to do this. This works beautifully and does exactly what it should do: change the title colors etc according to the new template.

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

I guess I should use the Microsoft.Office.Interop.Word namespace, but I'm stuck there...


I managed to solve it by myself, wasn't that difficult apparantly. 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消