.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("郵箱", "304885433@qq.com");
            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;
        }
    }


}

 

模板如圖:

  

生成文檔如圖:

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM