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:
Copy codeThe Code is as follows: using System;
Using System. Web. Security;
Using Microsoft. Office. Interop. Word;
Using System. IO;
/// <Summary>
/// Word summary
/// </Summary>
Public class WordOp
{
Public WordOp ()
{
//
// TODO: add the constructor logic here
//
}
Private ApplicationClass WordApp;
Private Document WordDoc;
Private static bool isOpened = false; // determines whether the word template is occupied
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 );
}
// Define 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 a Word file based on the template
Public void OpenTempelte (string strTemppath)
{
Object Missing = Type. 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 in the Content of the LabelId label, that is, the mail subject
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:Copy codeThe Code is as follows: 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.