.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( " 邮箱 " , " 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; } } }
模板如图:
生成文档如图:
如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的 【 推荐 】按钮。
感谢阅读,希望这篇文章能给你带来帮助!
分类: C#
作者: Leo_wl
出处: http://www.cnblogs.com/Leo_wl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息查看更多关于.net 使用 Aspose.Words 进行 Word替换操作的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did46407