1. 程式人生 > >.net 使用 Aspose.Words 進行 Word替換操作

.net 使用 Aspose.Words 進行 Word替換操作

之前在工作中,需要實現Word列印功能,並且插入圖片。當時採取的方式則是使用書籤進行操作。首先在word內插入書籤,完成後,存為模板。程式載入該模板,找到書籤,並在指定位置寫入文字即可。

後期維護過程中,發現模板經常需要變更,但是書籤在word中不方便檢視,使用者在編輯word的時候容易出錯。於是想採取特殊字串標識的方式進行替換。此時,圖片的插入就存在問題,游標無法直接移動到指定字串。

查閱 Aspose.Words提供的API,發現有Range類有該方法:

public int Replace(Regex pattern, IReplacingCallback handler, bool
isForward);

該方法則是在使用正則表示式進行文件內替換的同時可以執行IReplacingCallback介面

具體實現程式碼如下:

/* ==============================================================================
   * 文 件 名:Program
   * 功能描述:
   * Copyright (c) 2013 武漢經緯視通科技有限公司
   * 創 建 人: alone
   * 建立時間: 2013/4/2 11:16:19
   * 修 改 人: 
   * 修改時間: 
   * 修改描述: 
   * 版    本: v1.0.0.0
   * ==============================================================================
*/ using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using Aspose.Words; namespace WordDemo { class Program { static void Main(string[] args) { var dic = new Dictionary<string, string>(); dic.Add(
"姓名", "楊冪"); dic.Add("學歷", "本科"); dic.Add("聯絡方式", "02759597666"); dic.Add("郵箱", "[email protected]"); dic.Add("頭像", ".//1.jpg"); //使用書籤操作 Document doc = new Document(".//1.doc"); DocumentBuilder builder = new DocumentBuilder(doc); foreach (var key in dic.Keys) { builder.MoveToBookmark(key); if (key != "頭像") { builder.Write(dic[key]); } else { builder.InsertImage(dic[key]); } } doc.Save("書籤操作.doc");//也可以儲存為1.doc 相容03-07 Console.WriteLine("已經完成書籤操作"); //使用特殊字串替換 doc = new Document(".//2.doc"); foreach (var key in dic.Keys) { if (key != "頭像") { var repStr = string.Format("&{0}&", key); doc.Range.Replace(repStr, dic[key], false, false); } else { Regex reg = new Regex("&頭像&"); doc.Range.Replace(reg, new ReplaceAndInsertImage(".//1.jpg"), false); } } doc.Save("字串替換操作.doc");//也可以儲存為1.doc 相容03-07 Console.WriteLine("已經完成特殊字串替換操作"); Console.ReadKey(); } } public class ReplaceAndInsertImage : IReplacingCallback { /// <summary> /// 需要插入的圖片路徑 /// </summary> public string url { get; set; } public ReplaceAndInsertImage(string url) { this.url = url; } public ReplaceAction Replacing(ReplacingArgs e) { //獲取當前節點 var node = e.MatchNode; //獲取當前文件 Document doc = node.Document as Document; DocumentBuilder builder = new DocumentBuilder(doc); //將游標移動到指定節點 builder.MoveTo(node); //插入圖片 builder.InsertImage(url); return ReplaceAction.Replace; } } }