欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.Net 使用 Aspose.Words 进行 Word替换操作

程序员文章站 2022-04-09 09:22:42
...
using Aspose.Words;
using Aspose.Words.Replacing;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;


namespace Life.Win.Excel_Word
{
    public class WordDemo
    {


        public WordDemo()
        {
            Init();
        }


        private void Init()
        {
            string dir = System.AppDomain.CurrentDomain.BaseDirectory;


            Document doc = new Document(Path.Combine(dir, "Excel-Word/Template.docx"));
            DocumentBuilder builder = new DocumentBuilder(doc);
            
            //第一种:插入书签的方式
            builder.MoveToBookmark("书签");
            builder.Write("http://ohyewang.com/-噢耶网");
            builder.MoveToBookmark("图片");
            builder.InsertImage(".//Excel-Word/zxy.jpg");
            doc.Save(Path.Combine(dir, "Excel-Word/New_File.docx"));


            //第二种:插入字符替换的方式
            doc.Range.Replace("[key]", "http://ohyewang.com/-噢耶网", new FindReplaceOptions { });
            doc.Range.Replace(new Regex(@"\[img\]"), new ReplaceAndInsertImage(".//Excel-Word/zxy.jpg"), false);
            doc.Save(Path.Combine(dir, "Excel-Word/New_File_02.docx"));
        }


    }
    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;
        }
    }




}

模板文件:

.Net 使用 Aspose.Words 进行 Word替换操作


运行效果:

.Net 使用 Aspose.Words 进行 Word替换操作

Aspose.Words下载地址:点击打开链接

相关标签: Aspose.Words