Answers from the experts:
1. Create a New word template by searching for the word documents that need to be filled with a program and using "bookmarks" (insert --> bookmarks --> Enter id --> OK) mark and save.
2. Add everyone readable to the word template to prevent files from being opened.
3. Add "Reference" to the project and find "Microsoft Word 10.0 Object Library" or "Microsoft Word 11.0 Object Library.
4. The new class is WordOp. cs, which means to operate the word class.
The content is as follows:
Using System; using System. web. security; using Microsoft. office. interop. word; using System. IO; // <summary> /// Brief description of Word /// </summary> public class WordOp {public WordOp () {/// TODO: add the constructor logic //} private ApplicationClass WordApp; private Document WordDoc; private static bool isOpened = false; // determine whether the word template is occupied by public void SaveAs (string strFileName, bool isReplace) {if (isReplace & File. exists (strFileName) {File. delete (strFileName);} object missing = Type. missing; object fileName = strFileName; WordDoc. saveAs (ref fileName, ref missing, ref missing, ref missing, ref missing);} // defines a Word. application object public void activeWordApp () {WordApp = new ApplicationClass ();} public void Quit () {object missing = System. reflection. missing. value; WordApp. application. quit (ref missing, ref missing, ref missing); isOpened = false;} // create the Word file public void OpenTempelte (string strTemppath) {object Missing = Type based on the template. missing; // object Missing = System. reflection. missing. value; activeWordApp (); WordApp. visible = false; object oTemplate = (object) strTemppath; try {while (isOpened) {System. threading. thread. sleep (500);} WordDoc = WordApp. documents. add (ref oTemplate, ref Missing); isOpened = true; WordDoc. activate ();} catch (Exception Ex) {Quit (); isOpened = false; throw new Exception (Ex. message) ;}} public void FillLable (string LabelId, string Content) {// open the Word template // OpenTempelte (tempName); // fill the LabelId tag with Content, that is, the email subject item object bkmC = LabelId; if (WordApp. activeDocument. bookmarks. exists (LabelId) = true) {WordApp. activeDocument. bookmarks. get_Item (ref bkmC ). select ();} WordApp. selection. typeText (Content); // SaveAs (saveAsFileName); // Quit ();}}
5. Call in the background of the page to be used, for example:
String path = Server. mapPath ("download"); string templatePath = path + "file: // downloadczql.doc/"; WordOp wop = new WordOp (); wop. openTempelte (templatePath); wop. fillLable ("id", "1"); wop. fillLable ("usr_name", "test"); wop. saveAs (path + "file: // savetest.doc", true/); wop. quit (); Response. redirect (@ "/download/savetest.doc"); // do a jump to download.