Instance development: Use Visual C #. Net to enable word to automatically create a document?

Source: Internet
Author: User
Tags 3x5 table
In this article Code The example shows how to complete the following tasks:

Insert paragraphs that contain text and format.
Browse and modify different scopes in the document.
Insert a table, set the table format, and fill in data in the table.
Add a chart.

To use the automation function of Visual C #. Net to create a new word document, perform the following steps:

1. Start Microsoft Visual Studio. NET. InFileClickNewAnd then clickProject. InProject Type, ClickVisual C # projectAnd then clickTemplateUnderWindows ApplicationsProgram. By default, form1 is created.
2. AddMicrosoft Word Object Library. To do this, follow these steps:

A. InProjectClickAdd reference.
B. InComTab, findMicrosoft Word Object LibraryAnd then clickSelect.
C. InAdd referenceIn the dialog box, clickOKTo accept your selection. If the system prompts you to generate a package for the selected library, clickYes.
3. InViewChooseToolboxTo display the toolbox, and then add a button to form1.
4. Double-clickButton1. The code window for this form is displayed.
5. In the code window

Private void button#click (Object sender, system. eventargs e ){}

Replace:

Private void button#click (Object sender, system. eventargs e) {object omissing = system. reflection. missing. value; object oendofdoc = "\ endofdoc";/* \ endofdoc is a predefined bookmark * // start WORD and create a new document. word. _ application oword; word. _ document odoc; oword = new word. application (); oword. visible = true; odoc = oword. documents. add (ref omissing, ref omissing); // insert a paragraph at the beginning of the document. word. paragraph opara1; opara1 = odoc. content. paragraphs. add (ref omissing); opara1.range. TEXT = "Heading 1"; opara1.range. font. bold = 1; opara1.format. spaceafter = 24; // 24 PT spacing after paragraph. opara1.range. insertparagraphafter (); // insert a paragraph at the end of the document. word. paragraph opara2; object orng = odoc. bookmarks. get_item (ref oendofdoc ). range; opara2 = odoc. content. paragraphs. add (ref orng); opara2.range. TEXT = "Heading 2"; opara2.format. spaceafter = 6; opara2.range. insertparagraphafter (); // insert another paragraph. word. paragraph opara3; orng = odoc. bookmarks. get_item (ref oendofdoc ). range; opara3 = odoc. content. paragraphs. add (ref orng); opara3.range. TEXT = "this is a sentence of normal text. now here is a table: "; opara3.range. font. bold = 0; opara3.format. spaceafter = 24; opara3.range. insertparagraphafter (); // insert a 3x5 Table, fill it with data, and make the first row // bold and italic. word. table otable; word. range wrdrng = odoc. bookmarks. get_item (ref oendofdoc ). range; otable = odoc. tables. add (wrdrng, 3, 5, ref omissing, ref omissing); otable. range. paragraphformat. spaceafter = 6; int R, C; string strtext; For (r = 1; r <= 3; r ++) for (C = 1; C <= 5; c ++) {strtext = "R" + R + "C" + C; otable. cell (R, c ). range. TEXT = strtext;} otable. rows [1]. range. font. bold = 1; otable. rows [1]. range. font. italic = 1; // Add some text after the table. word. paragraph opara4; orng = odoc. bookmarks. get_item (ref oendofdoc ). range; opara4 = odoc. content. paragraphs. add (ref orng); opara4.range. insertparagrapappsfore (); opara4.range. TEXT = "and here's another table:"; opara4.format. spaceafter = 24; opara4.range. insertparagraphafter (); // insert a 5x2 table, fill it with data, and change the column widths. wrdrng = odoc. bookmarks. get_item (ref oendofdoc ). range; otable = odoc. tables. add (wrdrng, 5, 2, ref omissing, ref omissing); otable. range. paragraphformat. spaceafter = 6; For (r = 1; r <= 5; r ++) for (C = 1; C <= 2; C ++) {strtext = "R" + R + "C" + C; otable. cell (R, c ). range. TEXT = strtext;} otable. columns [1]. width = oword. inchestopoints (2); // change width of Columns 1 & 2 otable. columns [2]. width = oword. inchestopoints (3); // keep inserting text. when you get to 7 inches from top of the // document, insert a hard page break. object opos; double DPOs = oword. inchestopoints (7); odoc. bookmarks. get_item (ref oendofdoc ). range. insertparagraphafter (); do {wrdrng = odoc. bookmarks. get_item (ref oendofdoc ). range; wrdrng. paragraphformat. spaceafter = 6; wrdrng. insertafter ("a line of text"); wrdrng. insertparagraphafter (); opos = wrdrng. get_information (word. wdinformation. wdverticalpositionrelativetopage);} while (DPOs> = convert. todouble (opos); object ocollapseend = word. wdcollapsedirection. wdcollapseend; object opagebreak = word. wdbreaktype. wdpagebreak; wrdrng. collapse (ref ocollapseend); wrdrng. insertbreak (ref opagebreak); wrdrng. collapse (ref ocollapseend); wrdrng. insertafter ("We're re now on page 2. here's my chart: "); wrdrng. insertparagraphafter (); // insert a chart. word. inlineshape oshape; object oclasstype = "msgraph. chart.8 "; wrdrng = odoc. bookmarks. get_item (ref oendofdoc ). range; oshape = wrdrng. inlineshapes. addoleobject (ref oclasstype, ref omissing, ref omissing ); // demonstrate use of late bound ochart and ochartapp objects to // manipulate the chart object with msgraph. object ochart; object ochartapp; ochart = oshape. oleformat. object; ochartapp = ochart. getType (). invokemember ("application", bindingflags. getproperty, null, ochart, null); // change the chart type to line. object [] parameters = new object [1]; Parameters [0] = 4; // xlline = 4 ochart. getType (). invokemember ("charttype", bindingflags. setproperty, null, ochart, parameters); // update the chart image and quit msgraph. ochartapp. getType (). invokemember ("Update", bindingflags. invokemethod, null, ochartapp, null); ochartapp. getType (). invokemember ("quit", bindingflags. invokemethod, null, ochartapp, null );//... if desired, you can proceed from here using the Microsoft Graph // object model on the ochart and ochartapp objects to make additional // Changes to the chart. // set the width of the chart. oshape. width = oword. inchestopoints (6.25f); oshape. height = oword. inchestopoints (3.57f); // Add text after the chart. wrdrng = odoc. bookmarks. get_item (ref oendofdoc ). range; wrdrng. insertparagraphafter (); wrdrng. insertafter ("the end. "); // close this form. this. close ();}

6. Scroll to the top of the code window. Add the following code linesUsingEnd of the command list:

Using word = Microsoft. Office. InterOP. Word; using system. reflection;

7. Press F5 to generate and run the program.
8. ClickButton1To start the word automation function and create a document.

After the code is executed, check the documents created for you. This document contains paragraphs, tables, and charts on two pages.

Use Template

If you want to use the automation function to create documents in a common format, it is easier to use a new document based on the preset format template to start the creation process. Compared with creating a document from scratch, using a template with the word automation client has two advantages:

You can apply more control to the format settings and layout of objects in the entire document.
You can use less code to create documents.

By using templates, You can precisely adjust the layout of tables, paragraphs, and other objects in the document, and add format settings for these objects. By using the automation function, you can create a new document based on a template containing the following code:

 
Object otemplate = "C: \ mytemplate. Dot"; odoc = oword. Documents. Add (ref otemplate, ref omissing );

In the template, you can define bookmarks so that the automation client can add variable Text to a specific location of the document, as shown below:

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

Another advantage of using templates is that you can create and store the format styles you want to apply at runtime, as shown below:

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

-Or-

 
Object ostylename = "mystyle"; oword. selection. set_style (ref ostylename );

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.