日期:2014-05-18 浏览次数:21211 次
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication.Word { public partial class 循环替换Word中的书签 : System.Web.UI.Page { Microsoft.Office.Interop.Word.Document WordDoc; Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application(); private static object oMissing = System.Reflection.Missing.Value; string[] strMarks; protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// 获取word 文档中 书签项 /// </summary> /// <returns></returns> public string[] GetBookmarks() { string[] bms = new string[WordDoc.Bookmarks.Count]; int i = 0; foreach (Microsoft.Office.Interop.Word.Bookmark bm in WordDoc.Bookmarks) { bms[i++] = bm.Name; } return bms; } protected void Button1_Click(object sender, EventArgs e) { object fileName = "E:\\Test.doc"; WordDoc = WordApp.Documents.Add(ref fileName, ref oMissing, ref oMissing, ref oMissing); strMarks = GetBookmarks();//读取word中的书签 ExportWord();//循环替换书签 } protected void ExportWord() { Microsoft.Office.Interop.Word.Application appWord = null; Microsoft.Office.Interop.Word.Document doc = null; try { //使用模板,创建新的doc文档 object objTrue = true; object objFalse = false;//服务器端是否打开word object objTemplate = "";//定义模板 objTemplate = "E:\\Test.doc";//取得模板 [color=#FF0000] for (int i = 0; i < strMarks.Length; i++) { appWord = new Microsoft.Office.Interop.Word.ApplicationClass(); //word程序不可视 appWord.Visible = false; object objDocType = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument; doc = appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue); #region 文字书签 // 如果存在该书签,则动态加载值. if (doc.Bookmarks.Exists(Convert.ToString(strMarks[i]))) { //定义书签变量 object fieldname = strMarks[i]; //定义书签的结果值 string result = strMarks[i] + ":wahaha"; doc.Bookmarks.get_Item(ref fieldname).Range.Text = result;//书签赋值 fieldname = null; result = null; } #endregion }[/color] #region Word文件保存到服务器 object filename = "E:\\Test1.doc"; object miss = System.Reflection.Missing.Value; object FileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;//兼容格式 doc.SaveAs(ref filename, ref FileFormat, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); object missingValue = Type.Missing; object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges; doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue); appWord.Application.Quit(ref doNotSaveChanges, ref miss, ref mis