从ASP.NET得到Microsoft Word文档

引言


        这篇文章是应在一个ASP.NET项目中建立Microsoft Word文档的需要而写的。本文描述了怎样使用ASP.NET来创建和修改Microsoft Word文档。

背景


        自动化(Automation)是一个过程,它允许编程语言譬如Visual Basic.NET或C#写的应用程序可以编程控制其它应用程序。自动化到Word允许你执行像创建新文档,向文档中添加文本,邮件合并,还有控制文档格式这样的操作。使用Word和其它Microsoft Office应用程序,几乎所有你能在用户面板上手动实现的操作都可以通过自动化编程实现。Word通过一个对象模型来实现这个编程功能性(programmatically functionality)。对象模型是一系列类和方法,它们提供和Word的逻辑组成部分相似的服务。例如,一个应用程序对象,一个文档对象,和一个段落对象,这些每个都包含着Word的相应组成部分的功能性。

项目


        在.NET中操作Word的第一步,你需要在你的项目中添加一个COM引用,这通过右击解决方案窗口中的引用->添加引用。单击COM标签寻找Microsoft Word 10.0 Object Library。单击“选择”添加,单击“确定”返回。

        这会自动在你的应用程序文件夹中放置一个程序集(assembly)将COM接口邦定到Word。
        现在,你可以生成一个Word应用程序的实例了。

Word.ApplicationClass oWordApp = new Word.ApplicationClass();


        你可以调用Microsoft Word提供给你的很有趣的方法和属性来操作Word格式的文档。学习怎样操纵Word,Excel和PowerPoint对象模型最好的方法就是,在这些Office应用程序中使用宏录制器:
        1、在“工具”菜单中的“宏”选项中选择“录制新宏”,然后执行你感兴趣的任务。
        2、在“工具”菜单中的“宏”选项中选择“停止录制”。
        3、一旦你完成了录制,选择“工具”菜单中的“宏”选项下的“宏”,选择你录制的宏,单击“编辑”。
        这将将你带入生成的VBA代码,这些代码完成了你记录的任务。注意记录下的宏在多数情况下不是最好的代码,但它提供了一个快速和可用的例子。
        例如要打开一个存在的文件加入一些文本:

object fileName = "c:\\database\\test.doc";
object readOnly = false;
object isVisible = true;
object missing = System.Reflection.Missing.Value;
Word.ApplicationClass oWordApp 
= new Word.ApplicationClass();

Word.Document oWordDoc 
= oWordApp.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);

oWordDoc.Activate();

oWordApp.Selection.TypeText(
"This is the text");
oWordApp.Selection.TypeParagraph();
oWordDoc.Save();

oWordApp.Application.Quit(
ref missing, ref missing, ref missing);


        或者要打开一个新的文档然后保存它:

Word.ApplicationClass oWordApp = new Word.ApplicationClass();

Word.Document oWordDoc 
= oWordApp.Documents.Add(ref missing, 
                           
ref missing,ref missing, ref missing);

oWordDoc.Activate();

oWordApp.Selection.TypeText(
"This is the text");
oWordApp.Selection.TypeParagraph();
oWordDoc.SaveAs(
"c:\\myfile.doc");

oWordApp.Application.Quit(
ref missing, ref missing, ref missing);


        在C#中,Word文档类的open方法定义为:Open(ref object, ref object, ref object, ref object, ref object, ref object,ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object)。这说明C#的Open方法接受15个必要参数,每个参数都必须以ref关键字为前缀而且每个参数都必须是Object类型的。因为第一个参数是一个文件名,通常在Visual Basic.NET中的一个String值,我们必须声明一个Object类型的变量来保存C#的string值,代码如下:

object fileName = "c:\\database\\test.doc";


        尽管我们在Open方法中只需要使用第一个参数,但是记住C#不允许可选参数,所以我们以Object类型的变量的形式提供余下的14个参数,它们保存System.Reflection.Missing.Value的值。

使用模板


        如果你使用自动化来创建都是一致格式的文档,使用预定义模板来处理新的文档将会很方便。在你的Word自动化客户程序中使用模板与不用模板相比,有两个显著的优点:
    ·对于你文档的格式和对象位置上你可以拥有更多的控制权
    ·你可以使用更少的代码来建立你的文档
        通过使用模板,你可以调整文档中表格、段落还有其它对象的位置,还有也可以调整这些对象的格式。通过使用自动化,你可以创建一个基于你的模板的文档,而只用如下的代码:

Word.ApplicationClass oWordApp = new Word.ApplicationClass();
object oTemplate = "c:\\MyTemplate.dot";
oWordDoc 
= oWordApp.Documents.Add(ref oTemplate, 
              
ref Missing,ref Missing, ref Missing);


        在你的模版中,你可以定义书签,这样你的自动化客户程序可以在文档中的特定位置填入可变的文本,如下:

object oBookMark = "MyBookmark";
oWordDoc.Bookmarks.Item(
ref oBookMark).Range.Text = "Some Text Here";


        使用模板的另一个优点是你可以创建你希望在运行时应用的存储格式风格,如下:

object oStyleName = "MyStyle";
oWordDoc.Bookmarks.Item(
ref oBookMark).Range.set_Style(ref oStyleName);

 

使用CCWordApp类


        这个项目包含一个文件:CCWordAPP.cs。我不想每次都写代码来插入文本,打开一个文件,等等……所以我决定写一个CCWordApp类来包括多数重要的方法。下面是对这个类和它的方法的简要描述。

public class CCWordApp 
{
    
//it's a reference to the COM object of Microsoft Word Application 
    private Word.ApplicationClass oWordApplic;    
    
// it's a reference to the document in use 
    private Word.Document oWordDoc;                    
    
    
// Activate the interface with the COM object of Microsoft Word 
    public CCWordApp();
    
    
// Open an existing file or open a new file based on a template 
    public void Open( string strFileName);

    
// Open a new document
    public void Open( );

    
// Deactivate the interface with the COM object of Microsoft Word 
    public void Quit( );

    
// Save the document
    public void Save( );
    
    
//Save the document with a new name as HTML document 
    public void SaveAs(string strFileName );

    
// Save the document in HTML format
    public void SaveAsHtml(string strFileName );

    
// Insert Text
    public void InsertText( string strText);

    
// Insert Line Break
    public void InsertLineBreak( );
    
    
// Insert multiple Line Break
    public void InsertLineBreak( int nline);

    
// Set the paragraph alignment
    
// Possible values of strType :"Centre", "Right", "Left", "Justify"
    public void SetAlignment(string strType );

    
// Set the font style
    
// Possible values of strType :"Bold","Italic,"Underlined"
    public void SetFont( string strType );
    
    
// Disable all the style 
    public void SetFont( );

    
// Set the font name
    public void SetFontName( string strType );

    
// Set the font dimension
    public void SetFontSize( int nSize );

    
// Insert a page break
    public void InsertPagebreak();

    
// Go to a predefined bookmark
    public void GotoBookMark( string strBookMarkName);

    
// Go to the end of document
    public void GoToTheEnd( );

    
// Go to the beginning of document
    public void GoToTheBeginning( );


        这样,打开一个已有的文件的操作就是:

CCWordApp test ;
test 
= new CCWordApp();
test.Open (
"c:\\database\\test.doc");
test.InsertText(
"This is the text");
test.InsertLineBreak;
test.Save ();
test.Quit();

 

细节


示例项目包括:
CCWordApp.cs - the class
CreateDocModel.aspx: 创建一个基于模板的文档和使用书签的例子。
CreateNewDoc.aspx: 创建一个文档和插入一些文本的例子。
ModifyDocument.aspx: 打开一个已有文档然后在后面添加一些文本的例子。
template\template1.dot: 一个模板的例子(在CreateDocModel.aspx中使用)。
记住一点,你保存文件的目录必须是可写的。请查看Web.config文件来修改路径。

引用


Microsoft Word Objects
Converting Microsoft Office VBA Macros to Visual Basic .NET and C#
HOWTO: Automate Microsoft Word to Perform a Mail Merge from Visual Basic .NET
A Primer to the Office XP Primary Interop Assemblies
HOWTO: Find and Use Office Object Model Documentation
Creating and Opening Microsoft Word Documents from .NET using C#

译注:本文译自The Code Project网站上的一篇文章,原文作者Michela,译者寒带鱼。仅供参考,如有翻译或理解上的错误,欢迎批评指正。查看原文请点击这里,点击这里下载源代码。

        另外,读完这篇文章之后,推荐阅读《.NET1.1下,使用C#自动生成Word2003文档(通过操作COM组件实现)》,加深理解。

 

posted @ 2005-11-09 11:08  寒带鱼  阅读(9055)  评论(8编辑  收藏  举报