AsposeWord 域替换 C#

docx插入域基本方法

 

打开文件

AsposeWordHelper helper = new AsposeWordHelper();
string templatePath = HttpContext.Current.Server.MapPath("~/Word/11.docx"); //模板路径
helper.OpenTempelte(templatePath); //打开模板文件

一、普通文本域替换

//域赋值
helper.ExecuteField(new string[] { "Test" }, new string[] {  "asdd" });

helper.Execute(model);//这个可以整个对象替换

二、替换图片

helper.AddImage(picAddress, "test", WrapType.None, 130, 130);

三、列表循环

需要把列表对象转为DataTable

DataTable dt1 = New DataTable();

helper.WriteTable(dt1);

word模板写法

双层循环则为嵌套写法

DataSet ds = new DataSet();
ds.Tables.Add(dt1); //集合赋值遍历
ds.Tables.Add(dt2); 
ds.Relations.Add(new DataRelation("drCP", dt1.Columns["c1"], dt2.Columns["c1"]));//关联字段 drCP是关系名称,随意命名
helper.WriteDataSet(ds);

word模板

四、列表循环中的域图片

如果DataTable中有图片,这文本域写法为<Image:图片地址>

附件

1.AsposeWordHelper

  1 using Aspose.Words;
  2 using Aspose.Words.Drawing;
  3 using System;
  4 using System.Collections.Generic;
  5 using System.Data;
  6 using System.IO;
  7 using System.Net;
  8 using System.Net.Http;
  9 using System.Net.Http.Headers;
 10 
 11 namespace Common.Helper
 12 {
 13 public enum MarkTypeEnum
 14     {
 15         /// <summary>
 16         /// 中括号 [[]]
 17         /// </summary>
 18         DEFAULT,
 19         /// <summary>
 20         /// 花括号 {{}}
 21         /// </summary>
 22         CURLYBRACES
 23     }
 24 
 25     /// <summary>
 26     /// word文档操作辅助类
 27     /// </summary>
 28     public class AsposeWordHelper
 29     {
 30         /// <summary>
 31         /// Word
 32         /// </summary>
 33         private Document _doc;
 34 
 35         /// <summary>
 36         /// 替换自定义文本
 37         /// </summary>
 38         /// <typeparam name="TEntity"></typeparam>
 39         /// <param name="entity"></param>
 40         public void Replace<TEntity>(TEntity entity, MarkTypeEnum markTypeEnum)
 41         {
 42             var type = entity.GetType();
 43             var properties = type.GetProperties();
 44             foreach (var item in properties)
 45             {
 46                 _doc.Range.Replace(ConvertMarkType(item.Name, markTypeEnum), item.GetValue(entity, null).ToString(), new Aspose.Words.Replacing.FindReplaceOptions());
 47             }
 48         }
 49 
 50         /// <summary>
 51         /// 替换自定义文本
 52         /// </summary>
 53         /// <param name="dic"></param>
 54         public void Replace(Dictionary<string, string> dic, MarkTypeEnum markTypeEnum)
 55         {
 56 
 57             foreach (var item in dic)
 58             {
 59                 _doc.Range.Replace(ConvertMarkType(item.Key, markTypeEnum), item.Value, new Aspose.Words.Replacing.FindReplaceOptions());
 60             }
 61         }
 62 
 63         /// <summary>
 64         /// 转成标签 [[]] , {{}}
 65         /// </summary>
 66         /// <param name="name"></param>
 67         /// <param name="markTypeEnum"></param>
 68         /// <returns></returns>
 69         public static string ConvertMarkType(string name, MarkTypeEnum markTypeEnum = MarkTypeEnum.DEFAULT)
 70         {
 71             switch (markTypeEnum)
 72             {
 73                 case MarkTypeEnum.CURLYBRACES:
 74                     return MarkTypeCurlyBraces(name);
 75                 default:
 76                     return MarkTypeDefault(name);
 77             }
 78         }
 79 
 80         /// <summary>
 81         /// 返回[[name]]
 82         /// </summary>
 83         /// <param name="name"></param>
 84         /// <returns></returns>
 85         private static string MarkTypeDefault(string name)
 86         {
 87             return $"[[{name}]]";
 88         }
 89 
 90         /// <summary>
 91         /// 返回{{name}}
 92         /// </summary>
 93         /// <param name="name"></param>
 94         /// <returns></returns>
 95         private static string MarkTypeCurlyBraces(string name)
 96         {
 97             return $"{{{{{name}}}}}";
 98         }
 99 
100 
101         /// <summary>
102         /// 文本域处理泛型集合赋值
103         /// </summary>
104         /// <typeparam name="TEntity"></typeparam>
105         /// <param name="entity"></param>
106         public void Execute<TEntity>(TEntity entity)
107         {
108             var type = entity.GetType();
109             var properties = type.GetProperties();
110             List<string> names = new List<string>();
111             List<string> values = new List<string>();
112             foreach (var item in properties)
113             {
114                 names.Add(item.Name);
115                 var val = item.GetValue(entity, null);
116                 if (val == null)
117                     values.Add(null);
118                 else
119                     values.Add(item.GetValue(entity, null).ToString());
120             }
121             _doc.MailMerge.Execute(names.ToArray(), values.ToArray());
122         }
123 
124         /// <summary>
125         /// 文本域处理键值对赋值
126         /// </summary>
127         /// <param name="dic"></param>
128         public void Execute(Dictionary<string, string> dic)
129         {
130             List<string> names = new List<string>();
131             List<string> values = new List<string>();
132             foreach (var item in dic)
133             {
134                 names.Add(item.Key);
135                 values.Add(item.Value);
136             }
137             _doc.MailMerge.Execute(names.ToArray(), values.ToArray());
138         }
139 
140 
141 
142         /// <summary>
143         /// 文本域赋值用法
144         /// </summary>
145         /// <param name="fieldNames">key</param>
146         /// <param name="fieldValues">value</param>
147         public void ExecuteField(string[] fieldNames, object[] fieldValues)
148         {
149             _doc.MailMerge.Execute(fieldNames, fieldValues);
150         }
151         /// <summary>
152         /// 文本域赋值用法
153         /// </summary>
154         /// <param name="fieldNames">key</param>
155         /// <param name="fieldValues">value</param>
156         public void ExecuteField(string fieldName, object fieldValue)
157         {
158             _doc.MailMerge.Execute(new string[] { fieldName }, new object[] { fieldValue });
159         }
160 
161         /// <summary>
162         /// 保存
163         /// </summary>
164         /// <param name="filePath"></param>
165         public void Save(string filePath, SaveFormat saveFormat = SaveFormat.Doc)
166         {
167             _doc.Save(filePath, saveFormat);
168         }
169 
170         /// <summary>
171         /// 基于模版新建Word文件
172         /// </summary>
173         /// <param name="path">模板路径</param>
174         public void OpenTempelte(string tempPath)
175         {
176             _doc = new Document(tempPath);
177         }
178 
179         /// <summary>
180         /// 书签赋值用法
181         /// </summary>
182         /// <param name="LabelId">书签名</param>
183         /// <param name="Content">内容</param>
184         public void WriteBookMark(string LabelId, string Content)
185         {
186             if (_doc.Range.Bookmarks[LabelId] != null)
187             {
188                 _doc.Range.Bookmarks[LabelId].Text = Content;
189             }
190         }
191 
192         /// <summary>
193         /// 书签赋值用法
194         /// </summary>
195         /// <param name="entity">键值对</param>
196         public void WriteBookMark(Dictionary<string, string> dic)
197         {
198             foreach (var item in dic)
199             {
200                 if (_doc.Range.Bookmarks[item.Key] != null)
201                 {
202                     _doc.Range.Bookmarks[item.Key].Text = item.Value;
203                 }
204             }
205         }
206 
207         /// <summary>
208         /// 列表赋值用法
209         /// </summary>
210         /// <param name="dt"></param>
211         public void WriteTable(DataTable dt)
212         {
213             _doc.MailMerge.ExecuteWithRegions(dt);
214         }
215 
216         /// <summary>
217         /// 不可编辑受保护,需输入密码
218         /// </summary>
219         /// <param name="pwd">密码</param>
220         public void NoEdit(string pwd)
221         {
222             _doc.Protect(ProtectionType.ReadOnly, pwd);
223         }
224 
225         /// <summary>
226         /// 只读
227         /// </summary>
228         public void ReadOnly()
229         {
230             _doc.Protect(ProtectionType.ReadOnly);
231         }
232 
233         /// <summary>
234         /// 添加图片
235         /// </summary>
236         /// <param name="filename">文件路径+文件名</param>
237         /// <param name="field">文本域名</param>
238         /// <param name="width"></param>
239         /// <param name="height"></param>
240         public void AddImage(string filename, string field, double width = 70, double height = 70)
241         {
242             DocumentBuilder builder = new DocumentBuilder(_doc);
243             Shape shape = new Shape(_doc, ShapeType.Image);
244             shape.ImageData.SetImage(filename);
245             shape.Width = width;//设置宽和高
246             shape.Height = height;
247             shape.WrapType = WrapType.Inline;
248             shape.BehindText = true;
249 
250             builder.MoveToMergeField(field);
251             builder.InsertNode(shape);
252         }
253 
254         /// <summary>
255         /// 添加图片
256         /// </summary>
257         /// <param name="filename">文件路径+文件名</param>
258         /// <param name="field">文本域名</param>
259         /// <param name="width"></param>
260         /// <param name="height"></param>
261         public void AddImage(string filename, string field, WrapType wrapType = WrapType.None, double width = 70, double height = 70)
262         {
263             DocumentBuilder builder = new DocumentBuilder(_doc);
264             Shape shape = new Shape(_doc, ShapeType.Image);
265             shape.ImageData.SetImage(filename);
266             shape.Width = width;//设置宽和高
267             shape.Height = height;
268             shape.WrapType = wrapType;
269             shape.BehindText = true;
270 
271             builder.MoveToMergeField(field);
272             builder.InsertNode(shape);
273         }
274 
275         /// <summary>
276         /// 添加图片
277         /// </summary>
278         /// <param name="filename">文件路径+文件名</param>
279         /// <param name="field">文本域名</param>
280         /// <param name="width"></param>
281         /// <param name="height"></param>
282         public void AddImage(string filename, string field)
283         {
284             DocumentBuilder builder = new DocumentBuilder(_doc);
285             Shape shape = new Shape(_doc, ShapeType.Image);
286             shape.ImageData.SetImage(filename);
287             shape.WrapType = WrapType.Inline;
288             shape.BehindText = true;
289             builder.MoveToMergeField(field);
290             builder.InsertNode(shape);
291         }
292 
293 
294 
295         /// <summary>
296         /// 添加图片
297         /// </summary>
298         /// <param name="filename">文件路径+文件名</param>
299         /// <param name="left"></param>
300         /// <param name="top"></param>
301         /// <param name="width"></param>
302         /// <param name="height"></param>
303         public void AddImage(string filename, double left = 0, double top = 0, double width = 70, double height = 70)
304         {
305             DocumentBuilder builder = new DocumentBuilder(_doc);
306             Shape shape = new Shape(_doc, ShapeType.Image);
307             shape.ImageData.SetImage(filename);
308             shape.Width = width;//设置宽和高
309             shape.Height = height;
310             shape.Top = top;
311             shape.Left = left;
312             builder.InsertNode(shape);
313         }
314 
315         /// <summary>
316         /// 添加图片
317         /// </summary>
318         /// <param name="field">文本域名</param>
319         /// <param name="stream"></param>
320         /// <param name="width"></param>
321         /// <param name="height"></param>
322         public void AddImageByStream(string field, Stream stream, double width = 70, double height = 70)
323         {
324             DocumentBuilder builder = new DocumentBuilder(_doc);
325             Shape shape = new Shape(_doc, ShapeType.Image);
326             shape.ImageData.SetImage(stream);
327             shape.Width = width;//设置宽和高
328             shape.Height = height;
329             shape.WrapType = WrapType.None;
330             shape.BehindText = true;
331             builder.MoveToMergeField(field);
332             builder.InsertNode(shape);
333         }
334 
335         /// <summary>
336         /// 添加图片
337         /// </summary>
338         /// <param name="stream">文件</param>
339         /// <param name="left"></param>
340         /// <param name="top"></param>
341         /// <param name="width"></param>
342         /// <param name="height"></param>
343         public void AddImage(string filename, double left = 0, double top = 0)
344         {
345             DocumentBuilder builder = new DocumentBuilder(_doc);
346             Shape shape = new Shape(_doc, ShapeType.Image);
347             shape.ImageData.SetImage(filename);
348             //shape.Width = width;//设置宽和高
349             //shape.Height = height;
350             shape.Top = top;
351             shape.Left = left;
352             builder.InsertNode(shape);
353         }
354         /// <summary>
355         /// 添加图片
356         /// </summary>
357         /// <param name="stream">文件</param>
358         /// <param name="left"></param>
359         /// <param name="top"></param>
360         /// <param name="width"></param>
361         /// <param name="height"></param>
362         public void AddImage(Stream stream, double left = 0, double top = 0)
363         {
364             DocumentBuilder builder = new DocumentBuilder(_doc);
365             Shape shape = new Shape(_doc, ShapeType.Image);
366             shape.ImageData.SetImage(stream);
367             //shape.Width = width;//设置宽和高
368             //shape.Height = height;
369             shape.Top = top;
370             shape.Left = left;
371             builder.InsertNode(shape);
372 
373         }
374         /// <summary>
375         /// 添加图片
376         /// </summary>
377         /// <param name="field">文本域名</param>
378         /// <param name="stream"></param>
379         /// <param name="width"></param>
380         /// <param name="height"></param>
381         public void AddImage2(string field, string filename)
382         {
383             DocumentBuilder builder = new DocumentBuilder(_doc);
384             Shape shape = new Shape(_doc, ShapeType.Image);
385             shape.ImageData.SetImage(filename);
386             builder.MoveToMergeField(field);
387             builder.InsertNode(shape);
388         }
389 
390         /// <summary>
391         /// 通过流导出word文件
392         /// </summary>
393         /// <param name="fileName">文件名</param>
394         public HttpResponseMessage ExportWord(string fileName, SaveFormat saveFormat = SaveFormat.Doc)
395         {
396             var stream = new MemoryStream();
397             _doc.Save(stream, saveFormat);
398             fileName += DateTime.Now.ToString("yyyyMMddHHmmss");
399             HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
400             result.Content = new StreamContent(stream);
401             result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/msword");
402             result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
403             string type = saveFormat == SaveFormat.Doc ? ".doc" : ".docx";
404             result.Content.Headers.ContentDisposition.FileName = fileName + type;
405             return result;
406         }
407 
408         /// <summary>
409         /// 通过流导出pdf文件
410         /// </summary>
411         /// <param name="fileName">文件名</param>
412         public HttpResponseMessage ExportPdf(string fileName)
413         {
414             var stream = new MemoryStream();
415             _doc.Save(stream, SaveFormat.Pdf);
416             fileName += DateTime.Now.ToString("yyyyMMddHHmmss");
417             HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
418             result.Content = new StreamContent(stream);
419             result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
420             result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
421             result.Content.Headers.ContentDisposition.FileName = fileName + ".pdf";
422             return result;
423         }
424 
425         /// <summary>
426         /// 基于模版新建Word文件
427         /// </summary>
428         /// <param name="stream">模板流</param>
429         public void OpenTempelteStream(Stream stream)
430         {
431             _doc = new Document(stream);
432         }
433 
434         /// <summary>
435         /// 保存
436         /// </summary>
437         /// <param name="filePath"></param>
438         public void SaveStream(Stream stream, SaveFormat saveFormat = SaveFormat.Doc)
439         {
440             _doc.Save(stream, saveFormat);
441         }
442 
443         public SaveFormat GetSaveFormat(string ext)
444         {
445             if (string.IsNullOrWhiteSpace(ext))
446                 return SaveFormat.Pdf;
447             switch (ext.ToLower())
448             {
449                 case ".pdf": return SaveFormat.Pdf;
450                 case ".docx": return SaveFormat.Docx;
451                 case ".doc": return SaveFormat.Doc;
452                 case ".dot": return SaveFormat.Dot;
453                 case ".html": return SaveFormat.Html;
454                 case ".png": return SaveFormat.Png;
455                 case ".xps": return SaveFormat.Xps;
456                 case ".tiff": return SaveFormat.Tiff;
457                 case ".wordml": return SaveFormat.WordML;
458                 case ".text": return SaveFormat.Text;
459                 case ".jpeg": return SaveFormat.Jpeg;
460                 case ".bmp": return SaveFormat.Bmp;
461                 default: return SaveFormat.Pdf;
462             }
463         }
464 
465         /// <summary>
466         /// 列表赋值用法(多集合)
467         /// </summary>
468         /// <param name="dt"></param>
469         public void WriteDataSet(DataSet ds)
470         {
471             _doc.MailMerge.ExecuteWithRegions(ds);
472         }
473 
474 
475         public NodeCollection GetNodeCollection()
476         {
477             return _doc.GetChildNodes(NodeType.Table, true);
478         }
479 
480         public Aspose.Words.DocumentBuilder GetDocumentBuilder()
481         {
482             return new Aspose.Words.DocumentBuilder(_doc);
483         }
484 
485         public Aspose.Words.Tables.Cell CreateCell(string value)
486         {
487             Aspose.Words.Tables.Cell c1 = new Aspose.Words.Tables.Cell(_doc);
488             Aspose.Words.Paragraph p = new Paragraph(_doc);
489             p.AppendChild(new Run(_doc, value));
490             c1.AppendChild(p);
491 
492             return c1;
493         }
494 
495 
496         public Aspose.Words.Tables.Row CreateRow(int columnCount, string[] columnValues)
497         {
498             Aspose.Words.Tables.Row r2 = new Aspose.Words.Tables.Row(_doc);
499             for (int i = 0; i < columnCount; i++)
500             {
501                 if (columnValues.Length > i)
502                 {
503                     var cell = CreateCell(columnValues[i]);
504                     r2.Cells.Add(cell);
505                 }
506                 else
507                 {
508                     var cell = CreateCell("");
509                     r2.Cells.Add(cell);
510                 }
511 
512             }
513             return r2;
514 
515         }
516 
517     }
518 }
View Code

2.Asp.Net导出

先保存在本地再导出

helper.Save(pdfAddress, SaveFormat.Docx);
FileInfo info = new FileInfo(pdfAddress);
var file = new FileStream(info.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(file);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = AttachedHelper.CLFielName(fileName + ".docx");

原文地址:https://www.cnblogs.com/cvol/p/14558710.html