C # Read and Write Word files,

Source: Internet
Author: User

C # Read and Write Word files.

A project report at hand is relatively simple. Therefore, the report printing engine uses the VBA engine to customize the Word template, then fill in the data according to the template needs, and then OK and print.

Implementation Method: first, we need to reference VBA to build it. I use Office2003 Professional and the Dll version is Microsoft Word11.0.

 

 

You also need to reference Interop. Word. Dll.

The Code is as follows:

/// # Region open the Word document and return the wDoc and wDoc objects. //// open the Word document and return the wDoc object, wDoc // complete Word file path + name // The returned Word. document wDoc object // The returned Word. application Object public static void CreateWordDocument (string FileName, ref Word. document wDoc, ref Word. application WApp) {if (FileName = "") return; Word. document thisDocument = null; Word. formFields formFields = null; Word. application thisApplication = new Word. applicationClass (); ThisApplication. visible = true; thisApplication. caption = ""; thisApplication. options. checkSpellingAsYouType = false; thisApplication. options. checkGrammarAsYouType = false; Object filename = FileName; Object ConfirmConversions = false; Object ReadOnly = true; Object AddToRecentFiles = false; Object PasswordDocument = System. type. missing; Object PasswordTemplate = System. type. missing; Object Revert = System. Type. missing; Object WritePasswordDocument = System. type. missing; Object WritePasswordTemplate = System. type. missing; Object Format = System. type. missing; Object Encoding = System. type. missing; Object Visible = System. type. missing; Object OpenAndRepair = System. type. missing; Object DocumentDirection = System. type. missing; Object NoEncodingDialog = System. type. missing; Object XMLTransform = System. type. mis Sing; try {Word. document wordDoc = thisApplication. documents. open (ref filename, ref ConfirmConversions, ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate, ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate, ref Format, ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection, ref NoEncodingDialog, ref XMLTransform); thisDocument = wordDoc; wDoc = wordDo C; WApp = thisApplication; formFields = wordDoc. formFields;} catch (Exception ex) {MessageBox. show (ex. message) ;}# endregion call the above static method to open the target file and fill in the data in the DataGrid to the corresponding Word tag. // # region Word data filling (For Example) ///// Word fill data /// private void WordLoadData () {Word. document wDoc = null; Word. application wApp = null; sysFun. createWordDocument ("E: \ Monitoring Report (new ). dot ", ref wDoc, ref wApp); // fill the tag" C "with object bkmC =" C "; if (wApp. activeDo Cument. bookmarks. exists ("C") = true) {wApp. activeDocument. bookmarks. get_Item (ref bkmc).select(%%%%wapp.selection.typetext(this.txt 1. text); object bkmG = "TWaterTable3"; object unit; object count; // Number of moving objects extend; extend = Word. wdMovementType. wdExtend; unit = Word. wdUnits. wdCell; // fill in the data in the DataGrid to the tag TWaterTable3 if (wApp. activeDocument. bookmarks. exists ("TWaterTable3") = true) {wApp. activeDocument. bookma Rks. get_Item (ref bkmG ). select (); for (int I = 0; I {if (I = 0) {count = 1;} else {count = 0 ;} // fill in five columns of Data wApp. selection. move (ref unit, ref count); wApp. selection. typeText (gridEX1.GetRow (I ). cells [0]. text); count = 1; wApp. selection. move (ref unit, ref count); wApp. selection. typeText (gridEX1.GetRow (I ). cells [1]. text); wApp. selection. move (ref unit, ref count); wApp. selection. typeText (gridEX1.GetRow (I ). cells [2]. text); wApp. selectio N. move (ref unit, ref count); wApp. selection. typeText (gridEX1.GetRow (I ). cells [3]. text); wApp. selection. move (ref unit, ref count); wApp. selection. typeText (gridEX1.GetRow (I ). cells [4]. text); // wrap wApp. selection. moveRight (ref unit, ref count, ref extend) ;}}# endregion and then OK. When controlling the label table, pay attention to column loops and line breaks. C # Excel operations (Import and Export) Many friends say that C # The code for exporting data to Excel is required, share it with everyone ///// read the Excel document ///// file name /// return a DataSet public DataSet ExcelToDS (string Path) {String strConn = "Provider = Microsoft. jet. OLEDB.4.0; "+" Data Source = "+ Path +"; "+" Extended Properties = Excel 8.0; "; OleDbConnection conn = new OleDbConnection (strConn); conn. open (); string strExcel = ""; OleDbDataAdapter myCommand = null; DataSet ds = null; strExcel = "select * from [sheet1 $]"; myCommand = new OleDbDataAdapter (strExcel, strConn); ds = new DataSet (); myCommand. fill (ds, "table1"); return ds ;}/ ///// Write the Excel document ///// file name public bool SaveFP2toExcel (string Path) {try {string strConn = "Provider = Microsoft. jet. OLEDB.4.0; "+" Data Source = "+ Path +"; "+" Extended Properties = Excel 8.0; "; OleDbConnection conn = new OleDbConnection (strConn); conn. open (); System. data. oleDb. oleDbCommand cmd = new OleDbCommand (); cmd. connection = conn; // cmd. commandText = "UPDATE [sheet1 $] SET Name = '2017-01-01 'WHERE employee ID = 'date '";// Cmd. ExecuteNonQuery (); for (int I = 0; I {if (fp2.Sheets [0]. Cells [I, 0]. Text! = "") {Cmd. commandText = "insert into [sheet1 $] (employee ID, name, department, title, date, time) VALUES ('" + fp2.Sheets [0]. cells [I, 0]. text + "','" + fp2.Sheets [0]. cells [I, 1]. text + "','" + fp2.Sheets [0]. cells [I, 2]. text + "','" + fp2.Sheets [0]. cells [I, 3]. text + "','" + fp2.Sheets [0]. cells [I, 4]. text + "','" + fp2.Sheets [0]. cells [I, 5]. text + "')"; cmd. executeNonQuery () ;}} conn. close (); return true;} catch (System. data. oleDb. oleDbException ex) {System. di Agnostics. Debug. WriteLine ("an error occurred when writing to Excel:" + ex. Message);} return false;} This method is quite effective. Appendix: VB. NET version to enable and disable word. If you are interested, you can study VB. NET to enable and disable Imports word' to open Dim mWordapp As word. application 'word Application Dim mobjDoc As word. document 'word Document Dim fullFileName as string' file path mWordapp = CreateObject ("word. application ") mobjDoc = mWordapp. documents. add (FullFileName) 'disable Dim missing As Object = System. reflection. missing. valuemWordapp. application. quit () If Not mobjDoc Is Nothing Then 'garbage collection System. runtime. interopServices. marshal. releaseComObject (mobjDoc) mobjDoc = NothingEnd IfIf Not mWordapp Is Nothing ThenSystem. runtime. interopServices. marshal. releaseComObject (mWordapp) mWordapp = NothingEnd If 'truly releases the word Process

 


Symbol in C Language <Yes

Left shift operator (<)

Removes all the binary bits of an operation object from the left and adds 0 to the right ).

For example, a = a <2 shifts the binary bits of a two places to the left and complements 0 to the right,

Move 1 to the left and then a = a * 2;

If the left shift does not include 1 in the Discard high position, then shifts one bit left, which is equivalent to multiplying the number by 2.
Shift right operator (>)

Shifts all the binary bits of a number to several places to the right, and adds 0 to the left of the positive number, 1 to the left of the negative number, and discards the right of the negative number.

The operand shifts one digit to the right, which is equivalent to dividing the number by 2.

For example, a = a> 2 shifts the binary bit of a two places to the right,

0 or 1 to see whether the number is positive or negative.

Symbol in C Language <Yes

Left shift operator (<)

Removes all the binary bits of an operation object from the left and adds 0 to the right ).

For example, a = a <2 shifts the binary bits of a two places to the left and complements 0 to the right,

Move 1 to the left and then a = a * 2;

If the left shift does not include 1 in the Discard high position, then shifts one bit left, which is equivalent to multiplying the number by 2.
Shift right operator (>)

Shifts all the binary bits of a number to several places to the right, and adds 0 to the left of the positive number, 1 to the left of the negative number, and discards the right of the negative number.

The operand shifts one digit to the right, which is equivalent to dividing the number by 2.

For example, a = a> 2 shifts the binary bit of a two places to the right,

0 or 1 to see whether the number is positive or negative.

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.