在Word文档中更改或添加模板 [英] Change or add template in Word-document

查看:138
本文介绍了在Word文档中更改或添加模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一个简单的C#程序从许多Word文档中更改模板.

I'd like 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.

在Word中,可以通过单击功能区中设计器"选项卡中的文档模板"来轻松实现. 我使用本指南来做到这一点.要做:根据新模板更改标题颜色等.

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.

所以问题很简单:如何在.NET应用程序中执行完全相同的操作(附加其他模板并更改样式)?

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

我想我应该使用Microsoft.Office.Interop.Word命名空间,但是我被困在那里...

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);

这篇关于在Word文档中更改或添加模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆