Microsoft Word Documents from ASP.NET

原创 2004年09月15日 17:47:00

Microsoft Word Documents from ASP.NET
By
Michela

Creating and opening Microsoft Word documents from ASP.NET?

Download demo project - 313 Kb

Introduction

This article is being written in response of the need of building Microsoft Word document in an ASP.NET project. This article demonstrates how to create and modify document using Microsoft Word with ASP.NET.

Background

Automation is a process that allows applications that are written in languages such as Visual Basic .NET or C# to programmatically control other applications. Automation to Word allows you to perform actions such as creating new documents, adding text to documents, mail merge, and formatting documents. With Word and other Microsoft Office applications, virtually all of the actions that you can perform manually through the user interface can also be performed programmatically by using automation. Word exposes this programmatic functionality through an object model. The object model is a collection of classes and methods that serve as counterparts to the logical components of Word. For example, there is an Application object, a Document object, and a Paragraph object, each of which contain the functionality of those components in Word.

The project

The first step in manipulating Word in .NET is that you'll need to add a COM reference to your project by right clicking in the solution explorer on References->Add Reference. Click on the COM tab and look for the Microsoft Word 10.0 Object Library. Click Select and OK.

Add Com Reference

This will automatically place an assembly in your application directory that wraps COM access to Word.

Now you can instantiate an instance of a Word application:

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

You can call the interesting methods and properties that Microsoft Word provides to you to manipulate documents in Word. The best way to learn how to navigate the object models of Word, Excel, and PowerPoint is to use the Macro Recorder in these Office applications:

  1. Choose Record New Macro from the Macro option on the Tools menu and execute the task you're interested in.
  2. Choose Stop Recording from the Macro option on the Tools menu.
  3. Once you are done recording, choose Macros from the Macro option on the Tools menu, select the macro you recorded, then click Edit.

This takes you to the generated VBA code that accomplishes the task you recorded. Keep in mind that the recorded macro will not be the best possible code in most cases, but it provides a quick and usable example.

For example to open an existing file and append some text:

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

Or to open a new document and save it:

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

In C#, the Word Document class's Open method signature is defined as 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). What this means is that in C# the Open method takes 15 required arguments, and each argument must be preceded with the ref keyword and each argument must be of type object. Since the first argument is a file name, normally a String value in Visual Basic. NET, we must declare a variable of type object that holds the C# string value, hence the code:

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

Although we only need to use the first argument in the Open method, remember that C# does not allow optional arguments, so we provide the final 14 arguments as variables of type object that hold values of System.Reflection.Missing.Value

Use a template

If you are using automation to build documents that are all in a common format, you can benefit from starting the process with a new document that is based on a preformatted template. Using a template with your Word automation client has two significant advantages over building a document from nothing:

  • You can have greater control over the formatting and placement of objects throughout your documents.
  • You can build your documents with less code.

By using a template, you can fine-tune the placement of tables, paragraphs, and other objects within the document, as well as include formatting on those objects. By using automation, you can create a new document based on your template with code such as the following:

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

In your template, you can define bookmarks so that your automation client can fill in variable text at a specific location in the document, as follows:

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

Another advantage to using a template is that you can create and store formatting styles that you wish to apply at run time, as follows:

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

Using the class CCWordApp

The project contains a file: CCWordApp.cs. I didn't want to write every time all the code necessary to insert text, open a file, etc...So I decided to write a class CCWordApp that wraps the most important function. This is a brief description of the class and its functions.

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

So the code to open an existing file will be:

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

Details

The demo project contains:

  • CCWordApp.cs - the class
  • CreateDocModel.aspx: an example of building a new document based on a template and the use of bookmarks
  • CreateNewDoc.aspx: an example of building a new document and inserting some text
  • ModifyDocument.aspx: an example of opening an existing document and appending some text at the end
  • template/template1.dot: an example of a template (used in CreateDocModel.aspx)

Keep in mind that the directory ,in which you save the files, must be writeable. Please check the Web.config to change the path.

References

Michela


Click here to view Michela's online profile.

?

原文:http://www.codeproject.com/aspnet/wordapplication.asp?msg=916345

Beginning Microsoft Word Business Documents

版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章原始出版、作者信息和本声明。否则将追究法律责任。http://blog.csdn.net/topmvp - topmvpBeginning...
  • topmvp
  • topmvp
  • 2008年12月02日 21:06
  • 210

Microsoft Office Excel cannot open or save any more documents because there is not enough available

Microsoft Office Excel (0x800A03EC) .NET导出Excel遇到的80070005错误的解决方法: 检索 COM 类工厂中 CLSID 为 {00024500-...
  • zouxistudent
  • zouxistudent
  • 2011年12月21日 15:00
  • 2716

python学习笔记--代码

texts=[[word for word in document.lower().split() if word not in stoplist] for document in documents...
  • u012328476
  • u012328476
  • 2014年04月28日 10:46
  • 465

Microsoft JET Database Engine 错误 '80040e14' FROM 子句语法错误

今天用asp做一个网站计数器,查询数据库记录的页面老是出现下列信息Microsoft JET Database Engine 错误 80040e14 FROM 子句语法错误**************...
  • fsclc
  • fsclc
  • 2007年04月17日 13:18
  • 7172

Windows Server® 2008 Enterprise 组件服务 找不到 ”Microsoft Word 97 - 2003 文档“组件

Windows Server® 2008 Enterprise 组件服务 找不到 ”Microsoft Word 97 - 2003 文档“
  • chang_chao_123
  • chang_chao_123
  • 2016年05月04日 10:43
  • 2536

ASP.NET操作Word文档

操作WORD配置说明引入:Word的对象库文件“MSWORD.OLB”(word 2000为MSWORD9.OLB)(这是针对老版本的情况,在用vs.net2005的时候,直接在引用对话框中,在com...
  • kaigood
  • kaigood
  • 2007年01月18日 13:22
  • 3170

Microsoft.Office.Interop.Word.Application.Documents.Open参数说明

打开指定的文档并将其添加至 Documents 集合。返回一个 Document 对象。 expression.Open(FileName, ConfirmConversions, ReadOn...
  • scys1217
  • scys1217
  • 2015年11月18日 15:51
  • 808

ASP.NET实现将网页内容输出到WORD并下载到本地

个人觉得要实现这个功能如果没有类库提供的几个关键函数,还是比较繁琐的。所以首先介绍几个将要在代码中使用的关键函数和参数,然后再说函数实现、注意问题等。关键函数:1.函数原型:Response.Appe...
  • SunMoonJP
  • SunMoonJP
  • 2017年03月20日 15:21
  • 2361

asp.net中打开word(2)

如果要求把word文件存储在sql server中时,就是存的时候先把文件转成byte[],然后赋值给定义的image参数,最后运行SQL命令进行提交。取的时候把image列转成byte[]类型的,然...
  • czsd82
  • czsd82
  • 2006年09月11日 11:30
  • 942

在"DCOM配置"中找到"Microsoft Office Word 97 - 2003 文档"

如果环境是 Windows 2008 R2可能找不到"Microsoft Office Word 97 - 2003 文档"。你可以 运行mmc -32 ,然后会弹出一个程序,在菜单中选择 添加/删除...
  • YangangwuWuyangang
  • YangangwuWuyangang
  • 2014年06月20日 14:57
  • 2074
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Microsoft Word Documents from ASP.NET
举报原因:
原因补充:

(最多只允许输入30个字)