Using Microsoft Word documents in asp.net

Source: Internet
Author: User
Tags format contains insert interface object model range version touch
Asp.net|microsoft|word

This article is written to create a Microsoft Word document in asp.net. This article demonstrates how to create and modify Microsoft Word documents in asp.net.

Background

Automation is an application that can be written in a variety of languages (such as Visual Basic.NET or C #) to control other applications at the program level.

Automation of Word allows you to perform actions such as creating new documents, adding text to documents, mail merging, and formatting documents. In Word and other Microsoft Office programs, visual operations through the user interface can also be implemented through program-level automation.

Word uses an object model to provide an external interface to the functionality that this program can manipulate.

An object model is a collection of classes and methods that correspond to the logical components of Word. For example, he may be an Application object, a Document object, a paragraph object, and each object contains the functionality of the word component.

[Set up Project]

The first step in working with word in. NET is to add COM references to your project, right-click on Solution Explorer's Reference,add Reference. Select the COM tab to find the Microsoft Word 10.0 Object Library. Click Select, OK.

This automatically adds an assembly of COM that is packaged with Word to the application directory.

Now you can create an instance of Word:

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

You can manipulate Word documents by calling methods and properties that Word provides to you.

The best way to learn how to use the Word,excel,powerpoint object model is to use Macro recorder in these Office applications:

1. Select the record New Macro in the Macro option of the Tools menu and perform the tasks you are interested in.

2. Select Stop Recording in the macro option of the Tools menu.

3. If you make a record, select the macros in the macro option of the Tools menu and find the macro you recorded, you can edit it.

The above operation generated the VBA code to complete the task you recorded. It should be noted that macros are not the best code in most cases, but it provides a convenient and usable method.

The following example opens and adds a written 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);

If you create a new document and save it in this way:

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 method of opening a Word document class is defined in this way: open (Ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref OBJEC T, ref object, ref object, ref object, ref object, ref object, ref object, ref object. The Open method in C # requires 15 parameters, and each parameter must be described by the REF keyword and is of type object.

The first parameter is the file, the name, which is usually a string in Visual Basic.NET, but in C # it must be an object that contains a string, which is the code:

Object fileName = "C:\\database\\test.doc";

Although we only need to use the first argument of the Open method, C # does not allow the default parameters, so we give it 14 object-type values: System.Reflection.Missing.Value

[Use stencil]

If you need to automatically create a document in a common format, you can use a preformatted version to create a new document, which can be a lot easier.

There are two obvious advantages to using a touch version in Word instead of creating an empty document:

1. You can format documents and control the objects in the document to a greater degree.

2. You can build documents with fewer code.
  
By using the touch version, you can adjust the position of the tables, paragraphs, and other objects in the document, including formatting them. By using automated processing, you can create a document based on the touch version of the following code:

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

Object otemplate = "C:\\mytemplate.dot";

oWordDoc = OWORDAPP.DOCUMENTS.ADD (ref otemplate, ref missing,ref Missing, ref Missing);

In the touch version you use, you can define some notation, and automated processing will populate these locations with text, as follows:

Object oBookMark = "MyBookmark";

OWordDoc.Bookmarks.Item (ref oBookMark). Range.Text = "Some Text here";
  

Another advantage of using the touch version is that you can create and save the formatting styles you want in the runtime, as follows:

Object ostylename = "MyStyle";

OWordDoc.Bookmarks.Item (ref oBookMark). Range.set_style (ref oStyleName);

[Use Ccwordapp class]

Included in the project CCWordApp.cs this file, I do not want to always write like insert text, open the document such code.

So, I decided to encapsulate some of the most important features into the Ccwordapp class.

The following code briefly describes this class and his 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 a 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 ();

The code that opens a file that exists will be like this:

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 used above

Createdocmodel.aspx-Create an example of a new document that is based on a touch version that uses bookmarks.

Createnewdoc.aspx-Creates a new document and adds a write text to it.

Modifydocument.aspx-Open a document that exists and append some text at the end.

Template\template1.dot-an example of a touch version (used in createdocmodel.aspx)

Note that the directory you use to save the document should be overridable.

You can modify this path in web.config.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.