C # implements a method for automatically creating Word documents through templates

Source: Internet
Author: User

The examples in this article describe how C # implements automatic creation of Word documents through templates and is a very useful technique. Share to everyone for your reference. The implementation method is as follows:

Introduction: There are projects in the previous period to generate the word format of the report in C #, through the network to find a lot of content, but are very messy, so they decided to summarize the specific steps, so that better communication and similar problems can be quickly resolved!

The specific steps are shown through the specific examples:


The first step is to make the template



1. Create a new document to set the contents of the document.

2. Insert the bookmark in the appropriate location, navigate to the location where you want to insert the bookmark, click "Insert" > "bookmark", pop up the dialog, enter the signature of the book, and click the "Add" button.

3. Save the template, named "Template 1.dot" or "Template 1.doc"


Step two, set up references in the project

1. Right-click References under Project directory in Solution Explorer, select Add Reference, open the Add Reference dialog box

2. In the Add Reference dialog box, select COM > Microsoft Word 11.0 Object Library and click the OK button

3. Same action Open the Add Reference dialog box, select the browse item, find the "Microsoft.Office.Interop.Word.dll" file, select it, and click the "OK" button

Attention:

The "Microsoft.Office.Interop.Word.dll" version you want to find here must be "11.*.*.*", "*" for the number


Step three, encode

This step is divided into two parts

The first part, the encoding of the report class

This Part I have encapsulated well, for the file "Report.cs", can be used directly

The implementation code is as follows: (There are more detailed comments in the code)

Using system;using system.collections.generic;using system.text;using microsoft.office.interop.word;namespace    MyNamespace//This side needs to be replaced by its own namespace name {classreport {private_applicationwordapp= null;    private_documentworddoc= null;      Public_applicationapplication {get {return wordapp;      } set {WordApp = value;      }} public_documentdocument {get {return worddoc;      } set {WordDoc = value;      }//Create a new document from the template publicvoidcreatenewdocument (Stringfilepath) {killwinwordprocess ();      wordapp= new ApplicationClass ();      Wordapp.displayalerts =wdalertlevel.wdalertsnone;      Wordapp.visible =false;      Objectmissing =system.reflection.missing.value;      Objecttemplatename =filepath; Worddoc= WordApp.Documents.Open (Reftemplatename, refmissing, ref missing, ref missing,ref missing, ref missing, ref Missing, ref missing, ref missing,ref missing, ref missing, Refmissing, ref missing, ref missing,ref missing, ref missing);      }//Save new File Publicvoidsavedocument (stringfilepath) {objectfilename =filepath;      Objectformat =wdsaveformat.wdformatdocument;//Save format Objectmiss =system.reflection.missing.value; Worddoc.saveas (reffilename, ref format, ref miss, ref miss, ref miss,ref miss, ref miss, ref miss, ref miss,      Ref miss, ref miss, ref miss, ref miss,ref miss, ref miss, ref miss);      Close Worddoc,wordapp object Objectsavechanges =wdsaveoptions.wdsavechanges;      Objectoriginalformat =wdoriginalformat.wdoriginaldocumentformat;      Objectroutedocument =false;      Worddoc.close (Refsavechanges, Reforiginalformat, refroutedocument);    Wordapp.quit (Refsavechanges, Reforiginalformat, refroutedocument);      }//Insert values at bookmarks Publicboolinsertvalue (Stringbookmark, stringvalue) {objectbkobj =bookmark; if (wordApp.ActiveDocument.Bookmarks.Exists (bookmark)) {Wordapp.activedocumenT.bookmarks.get_item (refbkobj).        Select ();        WordApp.Selection.TypeText (value);      return true;    } Returnfalse; }//Insert table, bookmark bookmarks publictableinserttable (stringbookmark, int rows, int columns,float width) {Objectmiss =      System.Reflection.Missing.Value;      Objectostart =bookmark; Rangerange =worddoc.bookmarks.get_item (Refostart).      range;//Table Insert position tablenewtable =worddoc.tables.add (range,rows, columns, ref miss, Refmiss); Format the table newTable.Borders.Enable = 1; Allow border, default no border (for 0 times wrong, 1 is a solid border, 2, 3 is a dashed border, after the number has not been tried) newtable.borders.outsidelinewidth=wdlinewidth.wdlinewidth050pt;/      /Border Width if (width! = 0) {newtable.preferredwidth=width;//table width} newtable.allowpagebreaks =false;    returnnewtable; }//Merge cell table name, start line number, start column number, end line number, end column number Publicvoidmergecell (Microsoft.Office.Interop.Word.Tabletable, int row1, int column1 , int row2, int column2) {table. Cell (ROW1,COLUMN1). Merge (table.    Cell (Row2,column2)); }//settingsTable content alignment Align Horizontal, vertical vertical (left-aligned, center-aligned, right-aligned align and vertical, respectively, with a value of -1,0,1) publicvoidsetparagraph_table ( Microsoft.Office.Interop.Word.Tabletable, int Align, int Vertical) {switch (Align) {case-1:table. range.paragraphformat.alignment=wdparagraphalignment.wdalignparagraphleft;break;//left-justified case 0:table. range.paragraphformat.alignment=wdparagraphalignment.wdalignparagraphcenter;break;//Horizontal Center Case 1:table.         range.paragraphformat.alignment=wdparagraphalignment.wdalignparagraphright;break;//right-justified} switch (Vertical) { Case-1: Table. range.cells.verticalalignment=wdcellverticalalignment.wdcellalignverticaltop;break;//top-aligned case 0:table. range.cells.verticalalignment=wdcellverticalalignment.wdcellalignverticalcenter;break;//Vertical Center Case 1:table. range.cells.verticalalignment=wdcellverticalalignment.wdcellalignverticalbottom;break;//Bottom Alignment}}//Set table font PU Blicvoidsetfont_table (Microsoft.Office.Interop.Word.Tabletable, StriNg FontName, double size) {if (size! = 0) {table.      Range.Font.Size =convert.tosingle (Size); } if (FontName! = "") {table.      Range.Font.Name =fontname; }}//whether to use a border, n the ordinal of the table, using Yes or no publicvoiduseborder (int n,bool uses) {if (use) {WordDoc.Content.Ta Bles[n]. Borders.Enable = 1; Borders are allowed, default is no border (0 o'clock no border, 1 is a solid border, 2, 3 is a dashed border, later numbers are not tried)} else {Worddoc.content.tables[n]. Borders.Enable = 2;      Allow a border, the default is no border (0 o'clock no border, 1 is a solid border, 2, 3 is a dashed border, the subsequent number has not been tried)}//Insert a row for the table, n table ordinal starting from 1 publicvoidaddrow (int n) {      Objectmiss =system.reflection.missing.value; Worddoc.content.tables[n].    Rows.Add (Refmiss); }//Add a row to the table Publicvoidaddrow (Microsoft.Office.Interop.Word.Tabletable) {Objectmiss =system.reflection.missi Ng.      Value; Table.    Rows.Add (Refmiss);      }//Insert rows to table, n is the ordinal of the table publicvoidaddrow (int n, int rows) {Objectmiss =system.reflection.missing.value; Microsoft.office.interop.wOrd.      tabletable = Worddoc.content.tables[n]; for (inti = 0; i < rows; i++) {table.      Rows.Add (Refmiss); }}//To insert elements into a table, table, row, row, column, value insert element Publicvoidinsertcell (Microsoft.Office.Interop.Word.Tabletab Le, int row, int column,string value) {table. Cell (Row,column).    Range.Text =value;    }//To insert elements into the table, the ordinal of the N table starts at 1, the row row number, the column number, the element Publicvoidinsertcell (int n, int row,int column, string value) {Worddoc.content.tables[n]. Cell (Row,column).    Range.Text =value;    }//Insert a row of data into the table, n is the ordinal of the table, row row number, columns column number, values insert value Publicvoidinsertcell (int n, int row,int columns, string[] values)      {Microsoft.Office.Interop.Word.Tabletable = Worddoc.content.tables[n]; for (inti = 0; i < columns; i++) {table. Cell (Row,i + 1).      Range.Text =values[i]; }}//Insert Picture Publicvoidinsertpicture (Stringbookmark, Stringpicturepath, floatwidth, float hight) {object M ISS = System.Reflection.Missing.ValuE      Objectostart =bookmark;    Objectlinktofile =false; Whether the picture is external link objectsavewithdocument =true; Whether the picture is saved with the document Objectrange =worddoc.bookmarks.get_item (Refostart).      range;//Picture insertion position wordDoc.InlineShapes.AddPicture (picturepath,ref linktofile, ref savewithdocument, Refrange); WORDDOC.APPLICATION.ACTIVEDOCUMENT.INLINESHAPES[1]. Width=width; Set picture width worddoc.application.activedocument.inlineshapes[1]. Height=hight;      Set picture Height}//Insert a paragraph of text, text content Publicvoidinserttext (Stringbookmark, stringtext) {Objectostart =bookmark; Objectrange =worddoc.bookmarks.get_item (Refostart).      Range;      PARAGRAPHWP =worddoc.content.paragraphs.add (Refrange); Wp.      Format.spacebefore= 6; Wp.      Range.Text =text; Wp.      Format.spaceafter = 24; Wp.      Range.insertparagraphafter ();    WordDoc.Paragraphs.Last.Range.Text = "\ n"; }//Kill Winword.exe Process Publicvoidkillwinwordprocess () {system.diagnostics.process[]processes=system.diagnostic S.process.getpRocessesbyname ("Winword"); foreach (System.Diagnostics.Processprocess in processes) {bool b = process.        mainwindowtitle== ""; if (process. MainWindowTitle = = "") {process.        Kill (); }      }    }  }}


The second part, the encoding of the specific generated document

The code is shown below:


1. First you need to load the template


Report: =new report ();

Report. CreateNewDocument (Tempath); Template path


2. Insert a value


Report. Insertvalue ("Bookmark_value", "World Cup");//Insert a value at the bookmark "Bookmark_value"


3. Create a table


Table Table =report. Inserttable ("Bookmark_table", 2, 3, 0); Insert a table with the largest row width of 2 rows and 3 columns at the bookmark "Bookmark_table"


4. Merging cells


Report. Mergecell (table, 1, 1, 1, 3); Table name, start line number, start column number, end line number, end column number


5. Add a row to the table


Report. AddRow (table); Table name


6. Inserting a value in a cell


Report. InsertCell (table, 2, 1, "R2c1″");//table name, line number, column number, value


7. Set the alignment of text in a table


Report. Setparagraph_table (Table,-1, 0);//left-aligned Horizontally, center-aligned vertically


8. Set the table font


Report. Setfont_table (Table, "Song Body", 9);//Arial 9 lbs


9. Add a row to an existing table


Report. AddRow (1);//Add a row to the first table in the template


10. Determine if the existing table uses a border


Report. Useborder (1,true); The first table in the template uses a solid border


11. Add multiple lines to an existing table


Report. AddRow (1, 2);//Insert 2 rows into the first table in the template


12. Insert a row of data into an existing table


String[] values={"Premier League", "Serie A", "Bundesliga", "La Liga", "French Armor"};

Report. InsertCell (1, 2, 5,values); Insert data into column 5 of the second row of the first table in a template


13. Insert Picture


String picturepath = @ "C:\Documents and settings\administrator\ desktop \1.jpg";

Report. InsertPicture ("Bookmark_picture", PicturePath, 150, 150); Bookmark location, picture path, image width, image height


14. Insert a paragraph of text


String text = "Long-term computer operators should eat more fresh vegetables and fruits, while increasing the intake of vitamin A, B1, C, E." For the prevention of corneal dryness, dry eyes, poor eyesight, and even appearance of night blindness, computer operators should eat more food rich in vitamin A, such as soy products, fish, milk, walnuts, vegetables, cabbage, water spinach, tomatoes and fresh fruit. ”;

Report. InsertText ("Bookmark_text", text);


15. Finally save the document


Report. SaveDocument (Reppath); Document Path


Fourth step, run the program to generate the document and view the resulting document

I hope this article is helpful to everyone's C # programming.

In addition to the Declaration, Running GuestArticles are original, reproduced please link to the form of the address of this article
C # implements a method for automatically creating Word documents through templates

This address: http://www.paobuke.com/develop/c-develop/pbk23495.html






Related content C # FileStream??? T?ád′?ê?ac# simple implementation method to prevent multiple programs from running C # Accessing the SQL Server database implementation Method C # implements methods to read and write INI files using the Windows API
C # generates a Word document code example in C # file path get function and file name get function Summary C # implementation terminating executing thread two examples of using ping in C #

C # implements a method for automatically creating Word documents through templates

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.