A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service
Use C #. NET design of management information system is very extensive, but its report is often used Crystal reports or other tools to form a fixed report, so that it is not easy to modify and electronic document preservation and transfer, if the output can be written to a Word document this solves this problem. Here are some ways to take advantage of C #. NET to control the operation of a Word document.
1 using C #. NET build and set up Word documents
We use C # in VS2008. NET to implement, so install the VS2008. You must add a reference to the type library from the COM Select card on the Add Reference dialog box on the Project menu before programming, and add "Usingword;" to the program header. This reference. Depending on the version of Word that is installed on your computer, the type library will be different. For example, for MicrosoftWord2003, the name of the type library is MICROSOFTWORD11.0OB2
111 The creation of Word documents
To use a Word document in C #, you first define a word app with the format word.applicationmywordapp=newword.appli2cation (). The second step is to define a Word document, apply the statement word.documentnewdoc=newword.document (), and implement. The third step is to define an object that is used to record the file name (the path in which it is contained), initialize it, and use the system-provided file function to determine whether it exists, or, if present, use the system function to delete the period, and define an object for the record file name (the path where the file is contained) Objectwfilename; Initializes the object wfilename=system.windows.forms.application.startuppath+ "sample. doc"; Determines if the file already exists if ( System.IO.File.Exists (String) wfilename) or delete System.IO.File.Delete ((string) wfilename) if it exists, or create a Word document, Define an object for the argument passing when the Word document is established before it is established, objectnoth2ing=system.reflection.missing.value; Finally, a Word document with a specified path is created by using the Word app, newdoc= Mywordapp.
Documents.Add (refnothing,refnothing,refnothing,refnothing); Page setup for a Word document
Word's page settings generally include, page horizontal portrait layout, paper type, margins, header, footer settings, and so on, the following code is the word
The page is set to portrait layout, the paper type is A4 paper, and the left and right margins are 2 centimeters.
Doc. Pagesetup.orientation=word.wdorientation.wdorientlandscape;∥ the settings page for Portrait doc. Pagesetup.pagewidth=wordapp.centimeterstopoints (29.7F); ∥ Set the paper width
Doc. Pagesetup.pageheight=wordapp.centimeterstopoints (21F); ∥ sets the paper height Newdoc. Pagesetup.topmargin=57;∥ set the top margin newdoc. Pagesetup.bottommargin=57;∥ set the bottom margin newdoc. Pagesetup.leftmargin=57;∥ set the left margin Newdoc. Pagesetup.rightmargin=57;∥ Setting the right margin 113 header footer additions and settings
A header footer is an area of information that is defined on the top and bottom margins of each page in a Word document for storing and displaying text and graphics. Header footers are commonly used in Word documents for print decoration, which can include text or graphics such as the document's current page number, document pages, document creation date time, document author, document title, document path and file name, company logo, border line, specially crafted graphics, and so on.
Mywordapp.activewindow.view.seekview=wdseekview.wdseekprimaryheader; MywordApp.ActiveWindow.ActivePane.Selection.InsertAfter ("[Header content]"
); Mywordapp.selection.paragraphformat.alignment=myword. Wdparagraphalignment.wdalignparagraphright;∥
Set Right alignment
Mywordapp.activewindow.view.seekview=wdseekview.wdseekmaindocument;∥ jump out of the header settings.
2 C # Operations on tables in Word
211 Creating tables and setting table and cell properties
Newdoc. CONTENT.TABLES.ADD (mywordApp.Selection.Range, number of table rows, number of table columns, refmissing,refautofitbehav2ior);
212 Merging cells
Newdoc. CONTENT.TABLES. Cell (I+1,J). Select (); objectmoveunit=word.wdunits.wdline;objectmovecount=1;
MywordApp.Selection.MoveUp (Refmoveunit,refmovecount,refmoveextend); MywordApp.Selection.Cells.Merge ();
Mywordapp.selection.cells.verticalalignment=word.wdcellverticalalignment.wdcellalignverticalcenter;newdoc. CONTENT.TABLES. Cell (i+1,1). range.text= "Cell content fill"; 213 split Cells
Word.tablenewtable=newdoc. Tables;objectbeforerow=newtable.rows;newtable.rows.add (Refbeforerow); Word.cellcell=newtable.cell (n); Cell. Merge (Newtable.cell); objectrownum=2;objectcolumnnum=2;
Cell. Split (Refrownum,refcolumnnum); 214 adding rows, adding columns
Newdoc. Content.tables. Rows.Add (Refbeforerow); ∥ add row Newdoc. Content.tables. Columns.Add (Refbeforecolumn); ∥ Add column
3 in C #. NET writes data from a database to a Word document
311 establishing a connection to the database
To write data to a Word document, you first establish a connection to the database, which is applied by ADO System.Data.OleDb technology to access the Access database. Add a usingSystem.data.OleDb reference before using this technique. The specific application is divided into three parts.
(1) Define a connection in the public part of the program.
Oledbconnectionmyconn=newoledbconnection ();(2) Add the following code to define the connection string in the page loading section.
Stringconnstr= "Provider=microsoft.jet.oledb.4.0;datasource=.\\basic.mdb"; myconn.connectionstring=connstr;
(3) Use MyConn.Open () and Myconn.clos () in each application function to open and close the connection. 
312 Creating a DataSet instance
In the program we use the DataReader Class of ADO to read the data from the data source in a connection way. We cannot instantiate DA2 directly
The Tareader class, but returns its instance by executing the ExecuteReader method of the Command object . For example, the following code.
Oledbcommandmycomm=newoledbcommand (sqlsr,myconn); Oledbdatareaderdr=mycomm. ExecuteReader (); 313 data written to Word document
Use C # to write the data in your program to a Word document, and you can use Newdoc when the program is good at the data in the variable. Content.in2sertafter (name); writes data from the name variable to the current position of the Word document. Use. Inserbefore (name) to write data from the name variable to the front of the Word document's current location ... InsertDateTime can insert the current system time and so on. Sets whether the font is bold with Newdoc. Paragraphs.last.range.font.bold=0, when the value is "0" is not set to bold, when "1" is set to bold, with Newdoc. Par2agraphs.last.range.font.name= "Font name"; You can set the font. With Newdoc. paragraphs.last.range.font.size=10; You can set the font size. With Newdoc. Paragraphs.last.alignment=word.wdparagraphalignment.wdalignparagraphleft; You can set the alignment. 314 getting data from the Clipboard
Opens a Word document in memory, copies the selection to the Clipboard so that we can get the data from the Clipboard, first activating the current Word document Newdoc.ActiveWindow.Selection.WholeStory (); The second step copies the selected content to the Clipboard Newdoc. ActiveWindow.Selection.Copy (); The third step defines the object Idataobjectdata=clipboard.getdataobject (); The fourth step gets the content Txtfilecontent.text=data in the data object. GetData (Dataformats.text). ToString (). With these steps we can get the selected content in the open Word document in memory and apply it to where we want it.
4 Querying and statistics with SQL statements and writing results to a Word document
SQL statement has, integrated unified, set data definition, data manipulation, data management functions in one, language style unified, can independently complete the data
The whole operation of the library is highly non-procedural, and it is proposed to "do what" rather than "how to do" the set-oriented operation, the two ways of use and the uniform Syntax knot, the SQL language is both a self-contained language and a human-embedded language, as a self-contained language, it can be used alone, Users can directly type the SQL command on the terminal to operate the database, the language is simple, easy to learn and easy to use and other characteristics. The use of SQL statements in our programs will greatly improve the efficiency of our programs.
The SQL statements are very rich, and only the aggregate functions commonly used in data analysis of statistics are introduced briefly and how C # is used to write their results into Word.
An aggregate function, also known as a column function or a group function, returns a single value based on a particular calculation in a set of values (or a set of values), and when they are used with the GROUPBY clause of a SELECT statement, each aggregate function produces a single value for each group when it is not associated with group
When used together, the By clause produces a single value for the entire table. Table 1 Introduction to aggregate functions
Table 1 Aggregate functions
Name of function
return value type meaning
Max () float returns the maximum value in the selection value min () float returns the minimum value in the selection value
Count (3) integer returns the number of rows of a SELECT statement sum () floating-point calculation of the selected value and
AVG () Floating point calculates the average of the selected value Stdev () floating point calculates the standard deviation of the selected value Var ()
Floating point Type
Calculate variance of selected values
Table 2 Execution method method names for OleDbCommand
ExecuteNonQuery () returns the number of rows affected ExecuteReader () returns SqlDataReader () object ExecuteXmlReader () return XmlReader object Executescaler ()
Returns the first row column in the result
To write the results of the SQL statement query to the Word document to do some preparatory work, first to establish a connection to the database, before I
We have described how to establish a connection to an Access database myconn; The second step defines a OleDbCommand object such as MYCMMD; the third step defines the Transact-SQL statement that is used to set the data source execution. The fourth step executes the OleDbCommand object, the Oledb2command object has four kinds of its description see table 2. This allows you to negative the results of the OleDbCommand object execution to the variables in the program, and then writes the data to the Word document using the method described earlier.
Depending on the need we can choose different OleDbCommand execution methods to get the data we need, the following is the use of the Coun (3) function in the aggregation function through the OleDbCommand of the execution method of the Executescaler () Returns an example of the number of people in a teaching unit in a jbqk table.
Stringsqlstr= "SelectCount (3) Asmmfromjbqkwhere classification = ' teaching ' and unit = '" +unitname+ "'";
Oledbcommandmycmmd=newoledbcommand (Sqlstr,myconn); jx_n= (int) mycmmd. ExecuteScalar ();
This jx_n the number of people in a teaching unit so that it can be written to the appropriate location in the Word document we need in C #. Other aggregation functions and the use of OleDbCommand are similar to those used in the above example.
5 concluding remarks
The main purpose of using C # to control word is to form flexible reports that can be modified and sent to people who need it, and can be saved as electronic documents for future use. C # is very rich in word operations, the text only to mention its basic operation, I hope to be helpful to the reader.
Based on C #. NET dynamic Word document generation and data filling research
Start building with 50+ products and up to 12 months usage for Elastic Compute Service