Use Microsoft Word documents in ASP. NET

Source: Internet
Author: User
[Source]Http://www.codeproject.com/useritems/wordapplication.asp

[Download the demo project used in this article]Project file size: 309 KB

[Introduction]

This document is required to create Microsoft Word documents in ASP. NET. This articleArticleDemonstrate 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 #).ProgramControl other applications at the program level.
Word automation allows you to perform operations such as creating new documents, adding text to documents, merging emails, and formatting documents. In word and other Microsoft Office programs, visual operations performed through user interfaces can also be achieved through Program-level automation.
Word provides the interface for using the operable functions of this program through the object model.
An object model is a set of classes and methods. These classes and Methods correspond to the logical components of word. For example, it may be an application object, a document object, and a paragraph object. Each object contains the function of the word component.

[Create a project]

In. net, the first step to operate word is to add com reference to your project, right-click the reference of Solution Explorer, and add reference. Select the com tab to find the Microsoft Word 10.0 Object Library. Click Select, OK.
This will automatically add the com Assembly encapsulated with word to the application directory.
Now, you can create a word instance:

Word. applicationclass owordapp = new word. applicationclass ();

You can call the methods and Attributes provided by word to manipulate Word documents.
The best way to learn how to use Word, Excel, and PowerPoint object models is to use macro recorder in these office applications:

1. Select record new macro in the macro option in the Tools menu and execute the tasks you are interested in.
2. In the macro option of the Tools menu, select stop recording.
3. if you set a record, select Macros in the macro option of the Tools menu, find the macro you recorded, and you can edit it.

The preceding operations generate VBACodeTo complete the tasks you recorded. It should be noted that a macro is not the best code in most cases, but it provides a convenient and available method.
The following example shows how to open and add a write text:

Object filename = "C: \ database \ test.doc";
object;
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 isvisible, 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 as follows:

Word. applicationclass owordapp = new word. applicationclass ();

Word. Document oworddoc = owordapp. Documents. Add (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 open method of the Word document class is defined as follows: open (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 the object type.
The first parameter is the file name, which is usually a string in Visual Basic. net, but in C #, it must be an object containing a string. The Code is as follows:

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

Although we only need to use the first parameter of the open method, C # does not allow the use of default parameters, So we assign it 14 object-type values: system. reflection. Missing. Value

[Touch version]

If you need to automatically create a document with a common format, you can use a pre-formatted touch version to create a new document, which is much easier.
Using a touch version in word instead of creating an empty document has two obvious advantages:

1. You can Format documents and control objects to a greater extent.
2. You can use less code to create a document.

By using the touch version, you can adjust the positions of tables, paragraphs, and other objects in the document, including formatting these objects. By using automated processing, you can create a touch version-based document with the following code:

Word. applicationclass owordapp = new word. applicationclass ();
Object otemplate = "C :\\ mytemplate. Dot ";
Oworddoc = owordapp. Documents. Add (ref otemplate, ref missing );

In your touch version, you can define some marks. Automatic processing will fill the text with these locations, as shown below:

Object obookmark = "mybookmark ";
Oworddoc. bookmarks. Item (ref obookmark). range. Text = "some text here ";

Another advantage of touch edition is that you can create and save the formatting styles you want during running as follows:

Object ostylename = "mystyle ";
Oworddoc. bookmarks. Item (ref obookmark). range. set_style (ref ostylename );

[Use the ccwordapp class]

The project contains the ccwordapp. CS file. I don't want to always write code like inserting text and opening a document.
Therefore, I decided to encapsulate some of the most important functions into the ccwordapp class.
The following code briefly describes 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 ();

The code for opening an existing file is as follows:

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 includes:
Ccwordapp. CS-class used above
Createdocmodel. aspx-an example of creating a new document based on the touch version using bookmarks.
Createnewdoc. aspx-create a new document and add a write text to it.
Modifydocument. aspx-open an existing document and append some text at the end.
Template \ template1.dot-touch version example (used in createdocmodel. aspx)

Note that the directory you used to save the document should be rewritable.
You can modify this path in Web. config.

[References]

    • 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 #

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.