一、通过“域”写入数据
在Word中,打开【插入】选项卡——【文档部件】——【域】,在【域】的功能对话框中,可以看到有全部、编号、等式和公式等多种类别,通过选择这些类别,可以使用域来进行自动更新的相关功能。包括公式计算、变化的时间日期、邮件合并等。
除了利用上述步骤插入域外,也可以按Ctrl+F9手工输入域。域实际上是Word中的代码,按Shift+F9可以在代码与计算结果之间进行切换。此处不理解也没关系,看下面例子就可以了。
“《》”并不是自己手动打出来的,要通过文本域构建
插入文本域。(插入--->文档部件--->域---->选择MergeFileID--->填写域名---->点击保存)
按Alt + F9 是这个样子的
这个“域”可以通过我们后台代码动态的显示我们需要的值,比如说《Name》 想要变成 Name:Ramon ,Title:《Title》变成 Ramon Title
二、代码实现
1.在实现的同时我们也需要准备好Aspose.Words.dll 破解版 可以上网找....
2.如果不是破解版他会有水印和自动生成的表头和底部信息(商用还是用正版吧)
添加一个AsposeWordHelper帮助类
using Aspose.Words; using Aspose.Words.Drawing; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; namespace WordHelper { /// <summary> /// word文档操作辅助类 /// </summary> public class AsposeWordHelper { /// <summary> /// Word /// </summary> private Document _doc; private string _tempPath; private SaveFormat _saveFormat; /// <summary> /// /// </summary> /// <param name="tempPath">模板地址</param> /// <param name="saveFormat">转换后的类型</param> public AsposeWordHelper(string tempPath, SaveFormat saveFormat = SaveFormat.Doc) { this._tempPath = tempPath; this._saveFormat = saveFormat; } /// <summary> /// 文本域处理泛型集合赋值 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="entity"></param> public void Execute<TEntity>(TEntity entity) { var type = entity.GetType(); var properties = type.GetProperties(); List<string> names = new List<string>(); List<string> values = new List<string>(); foreach (var item in properties) { names.Add(item.Name); values.Add(item.GetValue(entity, null).ToString()); } _doc.MailMerge.Execute(names.ToArray(), values.ToArray()); } /// <summary> /// 文本域处理键值对赋值 /// </summary> /// <param name="entity"></param> public void Execute(Dictionary<string, string> entity) { List<string> names = new List<string>(); List<string> values = new List<string>(); foreach (var item in entity) { names.Add(item.Key); values.Add(item.Value); } _doc.MailMerge.Execute(names.ToArray(), values.ToArray()); } /// <summary> /// 保存 /// </summary> /// <param name="filePath"></param> public void Save(string filePath) { _doc.Save(filePath, _saveFormat); } /// <summary> /// 基于模版新建Word文件 /// </summary> /// <param name="path">模板路径</param> public void OpenTempelte() { _doc = new Document(_tempPath); } /// <summary> /// 书签赋值用法 /// </summary> /// <param name="LabelId">书签名</param> /// <param name="Content">内容</param> public void WriteBookMark(string LabelId, string Content) { if (_doc.Range.Bookmarks[LabelId] != null) { _doc.Range.Bookmarks[LabelId].Text = Content; } } /// <summary> /// 列表赋值用法 /// </summary> /// <param name="dt"></param> public void WriteTable(DataTable dt) { _doc.MailMerge.ExecuteWithRegions(dt); } /// <summary> /// 不可编辑受保护,需输入密码 /// </summary> /// <param name="pwd">密码</param> public void NoEdit(string pwd) { _doc.Protect(ProtectionType.ReadOnly, pwd); } /// <summary> /// 只读 /// </summary> public void ReadOnly() { _doc.Protect(ProtectionType.ReadOnly); } /// <summary> /// 添加图片 /// </summary> /// <param name="filename">文件路径+文件名</param> /// <param name="field">文本域名</param> /// <param name="width">宽</param> /// <param name="height">高</param> public void AddImage(string filename, string field, double width = 70, double height = 70) { DocumentBuilder builder = new DocumentBuilder(_doc); Shape shape = new Shape(_doc, ShapeType.Image); shape.ImageData.SetImage(filename); shape.Width = width;//设置宽和高 shape.Height = height; shape.WrapType = WrapType.None; shape.BehindText = true; builder.MoveToMergeField(field); builder.InsertNode(shape); } /// <summary> /// 通过流导出word文件 /// </summary> /// <param name="fileName">文件名</param> public HttpResponseMessage ExportWord(string fileName) { var stream = new MemoryStream(); _doc.Save(stream, SaveFormat.Doc); fileName += DateTime.Now.ToString("yyyyMMddHHmmss"); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/msword"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = fileName + ".doc"; return result; } /// <summary> /// 通过流导出pdf文件 /// </summary> /// <param name="fileName">文件名</param> public HttpResponseMessage ExportPdf(string fileName) { var stream = new MemoryStream(); _doc.Save(stream, SaveFormat.Doc); fileName += DateTime.Now.ToString("yyyyMMddHHmmss"); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = fileName + ".pdf"; return result; } } }
调用
using Aspose.Words; using Model.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WordHelper; namespace WordTest.App { class Program { private static readonly AsposeWordHelper _AsposeWordHelper; static Program() { _AsposeWordHelper = new AsposeWordHelper(@"C:UsersNING MEIDesktop学习 est.docx"); } static void Main(string[] args) { //键值对 _AsposeWordHelper.OpenTempelte(); //打开定义好的模板 _AsposeWordHelper.Execute(new Dictionary<string, string>{ { "Name","Ramon"}, { "Title","Ramon Title"}, }); //替换域 赋值 _AsposeWordHelper.ReadOnly();// 可以设为只读 _AsposeWordHelper.Save(@"C:UsersNING MEIDesktop学习1.doc");//保存到哪个路径 //泛型 _AsposeWordHelper.OpenTempelte(); //打开定义好的模板 _AsposeWordHelper.Execute(new ContractModel() { Name = "Ramon", Title = "RamonTitle" }); //替换域 赋值 _AsposeWordHelper.ReadOnly();// 可以设为只读 _AsposeWordHelper.Save(@"C:UsersNING MEIDesktop学习2.doc");//保存到哪个路径 } } }
效果
代码只是随便的写了下还有很多可以扩展的地方的,小编就懒得扩展了,这只是一个demo