Get code-Practical tips for Microsoft Word documents from asp.net

Source: Internet
Author: User
Tags reflection
Background
Automation (Automation) is a process that allows applications written by a programming language such as Visual Basic.NET or C # to programmatically control other applications. Automation to Word allows you to do things like create new documents, add text to documents, mail merge, and control document formatting. With Word and other Microsoft Office applications, almost all of the actions you can manually implement on the user panel can be achieved by automating programming. Word implements this programmatic functionality (programmatically functionality) through an object model. The object model is a series of classes and methods that provide services similar to the logical components of Word. For example, an Application object, a Document object, and a paragraph object, each containing the functionality of the corresponding component of Word.

Project
The first step in working with word in. NET, you need to add a COM reference to your project by right-clicking the reference-> in the solution window. Click the COM tag to find the Microsoft Word 10.0 Object Library. Click Select to add, and click OK to return.
This automatically places an assembly (assembly) in your application folder to state the COM interface to Word.
Now you can generate an instance of a word application.

Word.applicationclass oWordApp = new Word.applicationclass ();
You can invoke the very interesting methods and properties that Microsoft Word provides to you to manipulate documents in Word format. The best way to learn how to manipulate the Word,excel and PowerPoint object models is to use the macro recorder in these Office applications:
1, select "Record new Macros" in the Macros option on the Tools menu, and then perform the tasks you are interested in.
2, select Stop Recording in the Macros option on the Tools menu.
3. Once you have finished recording, select macros under the Macros option on the Tools menu, select the macro you recorded, and click Edit.
This brings you into the generated VBA code, which completes the task you are recording. Note that the macro that is logged is not the best code in most cases, but it provides a quick and usable example.
For example, to open an existing file to add some text:
Copy Code code as follows:

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 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 you want to open a new document and then save it:
Copy Code code as follows:

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 Open method of a Word document class 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. This means that the Open method of C # accepts 15 necessary parameters, each of which must be prefixed with the REF keyword and each parameter must be of type object. Because the first parameter is a file name, usually a string value in Visual Basic.NET, we must declare a variable of type object to hold the string value of C #, as follows:

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 supply the remaining 14 parameters in the form of variables of type object, which hold the value of the System.Reflection.Missing.Value.

Working with templates
If you use automation to create documents that are all in a consistent format, it will be convenient to use predefined templates to process new documents. There are two notable advantages to using templates in your Word Automation client, compared with templates:
• You can have more control over the format and object position of your document
• You can use less code to build your document
By using templates, you can adjust the location of tables, paragraphs, and other objects in your document, and you can also adjust the formatting of those objects. By using automation, you can create a document based on your template and use only 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 your template, you can define bookmarks so that your Automation client can fill in a variable text in a specific location in the document, as follows:

Object oBookMark = "MyBookmark";
OWordDoc.Bookmarks.Item (ref oBookMark). Range.Text = "Some Text here";
Another advantage of using templates is that you can create a style of storage format that you want to apply at run time, as follows:

Object ostylename = "MyStyle";
OWordDoc.Bookmarks.Item (ref oBookMark). Range.set_style (ref oStyleName);
Using the Ccwordapp class
This project contains a file: CCWordAPP.cs. I do not want to write code every time to insert text, open a file, and so on ... So I decided to write a Ccwordapp class to include most important methods. The following is a brief description of the class and its methods.
Copy Code code as follows:

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

In this way, the operation of opening an existing file is:
Ccwordapp test;
Test = new Ccwordapp ();
Test. Open ("C:\\database\\test.doc");
Test. InsertText ("This is the text");
Test. Insertlinebreak;
Test. Save ();
Test. Quit ();
Details
Sample projects include:
Ccwordapp.cs-the class
Createdocmodel.aspx: Create a template-based document and use a bookmark example.
Createnewdoc.aspx: An example of creating a document and inserting some text.
Modifydocument.aspx: An example of opening an existing document and then adding some text later.
Template\template1.dot: An example of a template (used in createdocmodel.aspx).
Remember that the directory in which you save your files must be writable. Please review the Web.config file to modify the path.
Reference
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.