C # reads the Word template to replace the corresponding string (label) to generate a new word

Source: Internet
Author: User

In the normal work, the way to generate word is mainly C # read HTML template file after processing saved as. doc file, such benefits are convenient, fast, can meet most of the needs. However, some special needs are not satisfied, such as to generate word for a table, but only a part of the string needs to change, using the method above to generate a Word table easily deformed. If we can read a Word template, replace the fixed string defined in the template with the desired text, such as {Tag 1}, and then generate a new word. This produces a very neat word.

Looking for many methods on the Web, although all are calls to Office interface, and do not have a good scenario. Through your own experiments, compare, using Microsoft.Office.Interop.Word.dll call the corresponding find all commands, the corresponding label to replace the corresponding string is useful. The following is the implementation method.

    usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Reflection;usingMicrosoft.Office.Interop.Word;namespacerenfb.word{ Public classWord {Private Object_outputname =""; Private Object_inputname =""; //output filename, save Word as file name, absolute address         Public ObjectOutputname {Get{return_outputname;} Set{_outputname =value;} }        //Enter the file name, Word's template file (with the corresponding tag {biaoji1} or any string).Absolute Address Public ObjectInputName {Get{return_inputname;} Set{_inputname =value;} }         PublicWord () {} PublicWord (ObjectInputName,Objectoutputname) {             This. _inputname =InputName;  This. _outputname =Outputname; }        PrivateDictionary _put =NewDictionary (); //param key Tag {biaoji1} or any string to replace//param value replaced by string      Public voidPut (stringKeystringvalue) {_put.        ADD (key, value); }        #regionInternal variablesPrivate ObjectMissvalue =Missing.Value; Private ObjectTrueValue =true; Private ObjectFalsevalue =false; Private Objectostory=wdunits.wdstory; Private ObjectOmove=Wdmovementtype.wdmove; PrivateApplicationClass app =NULL; PrivateDocument doc=NULL; #endregion        //Open the document.         Private voidOpenDocument () {app=NewApplicationClass (); App. Visible=false; App. DisplayAlerts=Wdalertlevel.wdalertsnone; Doc=app. Documents.Open (ref_inputname,refMissvalue,refTrueValue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refmissvalue); }        //Save the document as a new Word file.         Private voidsaveasdocument () {doc. SaveAs (ref_outputname,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refmissvalue); }        //replace the corresponding label and save         Public voidSave () {if(string. IsNullOrEmpty (_inputname. ToString ())) {Throw NewException ("InputName cannot be empty, please enter the address of the template file. InputName is the absolute address of the template file");            }            if(string. IsNullOrEmpty (_outputname. ToString ())) {Throw NewException ("Outputname cannot be empty, enter the address where you saved the template file,Outputname is the absolute address of the template file");            }            Try            {                //Open the Word document.                  This. OpenDocument (); App. Selection.homekey (refOstory,refomove); Find Find=app.                Selection.Find; Find.                ClearFormatting (); Find.                Replacement.clearformatting (); foreach(stringKeyinch_put. Keys) {Find. Text=key; Find. Replacement.text=_put[key];  This.                Executereplace (find); }                //Save the document as a new document.                  This. Saveasdocument (); }            Catch(Exception ex) {Throw NewException ("Error:"+Ex.            Message); }            finally{app. Quit (refMissvalue,refMissvalue,refmissvalue); }        }        Private BOOLExecutereplace (Find find) {return  This.        Executereplace (Find, Wdreplace.wdreplaceall); }        Private BOOLExecutereplace (Find Find,Objectobjreplaceoption) {             returnfind. Execute (refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refMissvalue,refObjreplaceoption,refMissvalue,refMissvalue,refMissvalue,refmissvalue); }    }}       

The method of use is simple. I believe we all understand. The code is as follows:

stringInputName = Server.MapPath ("1.doc");stringOutputname = Server.MapPath ("3.doc"); Word Word=NewWord (InputName, outputname); Put ("{documentversion}","2.6"); word. Put ("{ProjectName}","Renfb.word"); word. Put ("{Author}","RENFB"); word. Put ("{Createriqi}","2011.07.04"); word. Put ("{Lianxiren}","Ning Guest"); word. Put ("{num}","1"); word. Save ();

Remember to refer to assemblies Renfb.Word.dll and Microsoft.Office.Interop.Word.dll before calling, and remember to add using Renfb.word on the pages you use; This article just plays a role. Hope to give you some inspiration.

C # reads the Word template to replace the corresponding string (label) to generate a new word

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.