HOW TO: Make Microsoft Word automatically runs Microsoft Word in Visual C # .NET (from MSDN)

xiaoxiao2021-03-06  73

For Microsoft Visual Basic .NET versions of this article, see

301656. For Microsoft Visual Basic 6.0 and Microsoft Visual Basic 5.0, please refer to

220607.

SUMMARY This article describes how to use Microsoft Visual C # .NET to automatically run Word to create a merged mail.

MORE INFORMATION By the automation process, applications written in languages ​​such as Visual C # .NET can be programmed to control other applications. With Microsoft Word's automation feature, you can perform operations such as new documents, add text to documents, and formatting documents. For Word and other Microsoft Office applications, almost all operations that can be manually executed over the user interface can also be performed by using the "Automation" function.

Word opens this program function through an object model. The object model is a collection of classes and methods, these classes and methods act as a logical component of Word. For example, there is

Application object,

Document object and

Paragraph objects, each of which contains the functions of those components in Word. To access the object model from Visual C # .NET, you can set item references to the type library.

This article will explain how to set the appropriate project reference to the Word Type Library for Visual C # .NET and provide examples of code that makes Word automatically run.

Generate automation example

Start Microsoft Visual Studio .NET. On the File menu, click New, and then click Project. Select a Windows application from the Visual C # project type. FORM1 is created by default. Add a reference to the Microsoft Word object library. To do this, follow these steps:

On the project menu, click Add Reference. On the COM tab, find the Microsoft Word object library, and then click Select. Note: Microsoft Office 2003 contains the main intero set (PIA). Microsoft Office XP does not contain PIA, but you can download PIA. For additional information about Office XP PIA, click the article number below to view the article in the Microsoft Knowledge Base: 328912 Info: Microsoft Office XP PIA is available for download in the Add Reference dialog box Click OK to accept your choice . On the View menu, select the Toolbox to display the toolbox, then add a button to Form1. Double click on Button1. The code window of the form appears. In the code window, put the following code private void button1_click (Object Sender, System.EventArgs E)

{

}

Replace with: Word.Application WRDAPP;

Word._document wrddoc;

Object omissing = system.reflection.Missing.Value;

Object OFALSE = FALSE;

Private void insertlines (int Linenum)

{

Int iCount;

// INSERT "LINENUM" Blank Lines.

For (iCount = 1; ICOUNT <= linenum; ICOUNT )

{

WRDAPP.SELECTION.TYPEPARAGRAPH ();

}

}

Private Void Fillrow (Word._Document Odoc, int Row, String text1, string text2, string text3, string text4)

{

// INSERT The Data Into The Specific Cell.

Odoc.Tables [1] .cell (row, 1) .range.insertafter (text1);

Odoc.tables [1] .cell (row, 2) .range.insertafter (Text2);

Odoc.tables [1] .cell (row, 3) .range.insertafter (Text3);

Odoc.tables [1] .cell (row, 4) .range.insertafter (Text4);

}

Private void createmailmergedatafile ()

{

Word._document odatadoc;

Int iCount;

Object oname = "c: //datadoc.doc";

Object Oheader = "firstname, lastname, address, citystatezip";

Wrddoc.mailmerge.createdDataSource (Ref oname, ref omings,

Ref omissing, ref oheader, ref omissing, ref omissing,

Ref omissing, ref omissing;

// Open the file to INSERT DATA.

OdataDoc = WRDAPP.Documents.open (Ref oname, Ref Omiusing,

Ref omissing, ref omissing, ref omissing, ref omings,

Ref omissing, ref omissing, ref omissing, ref omings,

Ref omissing, ref omissing, ref omissing, ref omings,

Ref omissing / *, ref omissing * /);

For (iCount = 1; ICOUNT <= 2; ICOUNT )

{

OdataDoc.tables [1] .Rows.Add (Ref Omissing);

}

// Fill in the data.

Fillrow (OdataDoc, 2, "Steve", "Debroux",

"4567 Main Street", "Buffalo, NY 98052");

Fillrow (OdataDoc, 3, "Jan", "Miksovsky",

"1234 5th Street", "Charlotte, NC 98765");

Fillrow (OdataDoc, 4, "Brian", "Valentine",

"12348 78th Street Apt. 214",

"Lubbock, TX 25874");

// save and close the file.

OdataDoc.save ();

OdataDoc.close (Ref OFALSE, REF OMIMIMISE);

}

Private void Button1_Click (Object Sender, System.Eventargs E)

{

Word.Selection WRDSeLection;

Word.mailmerge WRDMAILMERGE; WORD.MAILMERGEFIELDS WRDMERGEFIELDS;

Word.Table Wrdtable;

String strandd;

// Create An Instance of Word and make it it visible.

WRDAPP = New Word.Application ();

WRDAPP.Visible = True;

// Add a new document.

WRDDOC = WRDAPP.Documents.Add (Ref Omissing, Ref Omissing,

Ref omissing, ref omissing;

Wrddoc.select ();

WRDSELECTION = WRDAPP.SELECTION;

WRDMAILMERGE = WRDDOC.MAILMERGE;

// CREATE A Mailmerge Data file.

CreatemailMergeDataFile ();

// CREATE A STRING AND INSERT IT INTO The Document.

Strtoadd = "State University / R / NElectrical Engineering Department";

WRDSELECTION.PARAGRAPHFORMAT.ALIGNMENT =

Word.wdparagraphalignment.wdalignparagraphCenter;

WRDSELECTION.TYPETEXT (STRTOADD);

INSERTLINES (4);

// INSERT MERGE DATA.

WRDSELECTION.PARAGRAPHFORMAT.ALIGNMENT =

Word.wdparagraphagramhalignment.wdalignparagraphleft;

Wrdmergefields = WRDMAILMERGE.FIELDS;

WRDMERGEFIELDS.ADD (WRDSELECTION.RANGE, "firstname");

WRDSELECTION.TYPETEXT ("");

WRDMERGEFIELDS.ADD (WRDSELECTION.RANGE, "Lastname");

WRDSELECTION.TYPEPARAGRAGRAGRAPH ();

Wrdmergefields.Add (WRDSELECTION.RANGE, "Address");

WRDSELECTION.TYPEPARAGRAGRAGRAPH ();

WRDMERGEFIELDS.ADD (WRDSELECTION.RANGE, "CityStatezip");

INSERTLINES (2);

// Right Justify The Line and Insert a Date Field

// with the current date.

WRDSELECTION.PARAGRAPHFORMAT.ALIGNMENT =

Word.wdparagraphalignment.wdalignparagraphright;

Object Objdate = "DDDD, MMMM DD, YYYY";

WRDSELECTION.INSERTDATETIME (Ref objdate, ref j,

Ref omissing, ref omissing;

INSERTLINES (2);

// Justify the rest of the document.

WRDSELECTION.PARAGRAPHFORMAT.ALIGNMENT =

Word.wdparagraphagramhalignment.wdalignparagraphjustify; WRDSEETETEXT ("Dear");

WRDMERGEFIELDS.ADD (WRDSELECTION.RANGE, "firstname");

WRDSELECTION.TYPETEXT (",");

INSERTLINES (2);

// CREATE A STRING AND INSERT IT INTO The Document.

STRTOADD = "Thank you for your recess requirements for next"

"Semester's Class Schedule for the Electrical"

"ENCLOSED WITH THIS"

"Letter Is A Booklet Containing All The Classes"

"Offered Next Semester At State University."

"Several New Classes Will Be Offered In The"

"Electrical Engineering Department NEXT semester."

"The Classes Are listed Below."

WRDSELECTION.TYPETEXT (STRTOADD);

INSERTLINES (2);

// INSERT A New Table with 9 rows and 4 columns.

WRDTABLE = Wrddoc.tables.add (WRDSELECTION.RANGE, 9, 4,

Ref omissing, ref omissing;

// set the colorn widths.

Wrdtable.columns [1] .SetWidth (51, Word.wdrulersty.wdadjustnone);

Wrdtable.columns [2] .SetWidth (170, Word.wdrulersty.wdadjustnone);

Wrdtable.columns [3] .SetWidth (100, Word.wdrulersTyle.wdadjustnone);

Wrdtable.columns [4] .SetWidth (111, Word.wdrulersty.wdadjustnone);

// set the shading on the first row to light gray.

WRDTable.Rows [1] .cells.Shading.BackgroundPatterncolorIndex =

Word.wdcolorindex.wdgray25;

// bold the first row.

WRDTable.ROWS [1] .range.bold = 1;

// Center The text in Cell (1, 1).

Wrdtable.cell (1, 1) .Range.Paragraphs.Alignment =

Word.wdparagraphalignment.wdalignparagraphCenter;

// Fill Each Row of The Table with data.

Fillrow (WRDDOC, 1, "Class Number", "Class Name",

"Class Time", "Instructor"); FillRow (WRDDOC, 2, "EE220", "Introduction to Electronics II,

"1: 00-2: 00 m, W, f", "dr. jensen");

Fillrow (WRDDOC, 3, "EE230", "Electromagnetic Field Theory I",

"10: 00-11: 30 T, T", "Dr. Crump");

Fillrow (WRDDOC, 4, "EE300", "Feedback Control Systems",

"9: 00-10: 00 m, W, F", "Dr. Murdy");

Fillrow (WRDDOC, 5, "EE325", "Advanced Digital Design",

"9: 00-10: 30 T, T", "Dr. Alley");

Fillrow (WRDDOC, 6, "EE350", "Advanced Communication Systems",

"9: 00-10: 30 T, T", "Dr. Taylor");

Fillrow (WRDDOC, 7, "EE400", "Advanced Microwave Theory",

"1: 00-2: 30 t, t", "tr. lee");

Fillrow (WRDDOC, 8, "EE450", "Plasma theory",

"1: 00-2: 00 m, W, f", "Dr. Davis");

Fillrow (WRDDOC, 9, "EE500", "Principles of VLSI Design",

"3: 00-4: 00 m, W, F", "Dr. Ellison");

// go to the end of the document.

Object Oconst1 = Word.WdgarToItem.wdgotoline;

Object Oconst2 = word.wdgotodirection.wdgotolast;

WRDAPP.SELECTION.GOTO (Ref Oconst1, Ref Oconst2, Ref Omissing, Ref Omissing);

INSERTLINES (2);

// CREATE A STRING AND INSERT IT INTO The Document.

STRTOADD = "for additional information regarding the"

"Department of Electrical Engineering,"

"you can visit our web site at";

WRDSELECTION.TYPETEXT (STRTOADD);

// INSERT a HYPERLINK to the Web Page.

Object Oaddress = "http://www.ee.stateu.tld";

Object Orange = WRDSELECTION.RANGE;

WRDSELECTION.HYPERLINKS.ADD (Orange, Ref OADDRESS, REF Omiissing,

Ref omissing, ref omissing, ref omissing; // Create a string and inflect it Into the document

STRTOADD = ". Thank you for your intend in the class"

"offered in the divartment of electrical"

"ENGINEERING. If you have anyi other quintions,"

"Please Feel Free to Give US A Call AT"

"555-1212./r/n/r/N"

"SINCERELY, / R / N / R / N"

"Kathryn M. Hinsch / R / N"

"Divartment of electrical engineering / r / n";

WRDSELECTION.TYPETEXT (STRTOADD);

// Perform Mail Merge.

Wrdmailmerge.destination = word.wdmailmerge ;.wdsendtonewdocument

WRDMAILMERGE.EXECUTE (REF OFALSE);

// Close the Original form document.

Wrddoc.saved = true;

Wrddoc.close (Ref OFALSE, REF OMIMIMI, REF Omiusing)

// Release References.

WRDSELECTION = NULL;

WRDMAILMERGE = NULL;

Wrdmergefields = NULL;

WRDDOC = NULL;

WRDAPP = NULL;

// Clean Up Temp file.

System.IO.File.delete ("C: //DataDoc.doc");

}

Note: Microsfot Office Word 2003 provides an additional parameter for the Open method for documents. Èç¹û¹û¹¹¹¹¹ãμçç Word 2003 PIA £ ¬çëé/23ý¶ o Open · 1/2 · ¨μÄ ¸½½4ó2îêýëù × öμä × ¢ íí¡ £ 1/2 «òôâ'úâëìí/4 μ1/2 form1.cs μĶ 2¿ £ ousing word = Microsoft.Office.Interop.Word;

Press F5 to build and run the program. Click Button1 to launch the Word Automation and perform the mail merge.

Refer to more information, visit the following Microsoft Developer Network (MSDN) Web site:

Microsoft Office Development with Visual Studio (Microsoft Office Development) http://msdn.microsoft.com/library/en-us/dnoffdev/html/vsofficeDev.asp For additional information, click the following article number, To view the article in the Microsoft Knowledge Base:

285332 HOWTO: Automate Word 2002 with Visual Basic To Create a Mail Merge

The information in this article applies to:

Microsoft Visual C # .NET (2003) Microsoft Visual C # .NET (2002) Microsoft Office Word 2003 Microsoft Word 2002 Received: 2004-2-13 (5.0) Keywords: kbpia kbautomation kbhowto KB301659

转载请注明原文地址:https://www.9cbs.com/read-109014.html

New Post(0)