日期:2011-05-04  浏览次数:20413 次

说明:这篇文章是很早以前写的了,原本是用自动化模型在C# 中开发Word程序,现在自然可以用插件或智能文档的形式开发,但是Word的一些编程模型大体是一样的。所以也就不怕写得简单,拿出来供大家作个参考了。

在C#中利用自动化模型操纵Word

一.     引入程序集

在工程中加入引用Interop.Word

二.     生成Word对象

定义Word对象

Word.ApplicationClass app=null; 
 

 

打开Word对象

if(app==null)

app=new Word.ApplicationClass(); 
 

显示Word应用程序

if(app!=null)

app.Visible=ture; 
 

关闭并保存Word对象

object SaveOption,OriginalFormat,RouteDocument;

SaveOption=Word.WdSaveOptions.wdPromptToSaveChanges;

OriginalFormat=Word.WdOriginalFormat.wdPromptUser;

RouteDocument=Missing.Value;

if(app!=null)

{

app.Quit(ref SaveOption,ref OriginalFormat,ref RouteDocument);

app=null;


 

关闭并保存Word对象的资料如下:

Application.Quit

退出 Microsoft Word,并可选择保存或传送打开的文档。

expression.Quit(SaveChanges, Format, RouteDocument)

expression      必需。该表达式返回一个 Application 对象。

 

SaveChanges      Variant 类型,可选。指定退出 Word 前是否保存修改过的文档。可以是下列 WdSaveOptions 常量之一。

 

WdSaveOptions 可以是下列 WdSaveOptions 常量之一:

wdDoNotSaveChanges

wdPromptToSaveChanges

wdSaveChanges

 

 

OriginalFormat      Variant 类型,可选。指定 Word 对文档的保存方式(该文档的原始格式并非是 Word 文档格式)。可以是下列 WdOriginalFormat 常量之一。

 

WdOriginalFormat 可以是下列 WdOriginalFormat 常量之一:

wdOriginalDocumentFormat

wdPromptUser

wdWordDocument

 

 

RouteDocument      Variant 类型,可选。如果为 True,则将文档传送给下一个收件人。如果文档没有附加的传送名单,则忽略该参数。

 

  
 

 

新增文档

if(app!=null)

{

     object template,newTemplate,docType,visible;

     template=newTemplate=docType=visible=Missing.Value;

     Word.Document document=app.Documents.Add(

ref template,ref newTemplate,ref docType,ref visible);


 

 

Documents.Add

返回一个 Document 对象,该对象表示添加至打开的文档集合中的新建空文档。

expression.Add(Template, NewTemplate, DocumentType, Visible)