C#Aspose.Words数据写⼊到Word
⼀、通过“域”写⼊数据
在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
/// <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:\Users\NING MEI\Desktop\学习\test.docx");
}
static void Main(string[] args)
{
/
/键值对
_AsposeWordHelper.OpenTempelte(); //打开定义好的模板
_AsposeWordHelper.Execute(new Dictionary<string, string>{
{ "Name","Ramon"},
{ "Title","Ramon Title"},
}); //替换域赋值
_AsposeWordHelper.ReadOnly();// 可以设为只读
_AsposeWordHelper.Save(@"C:\Users\NING MEI\Desktop\学习\1.doc");//保存到哪个路径
//泛型
_AsposeWordHelper.OpenTempelte(); //打开定义好的模板
_AsposeWordHelper.Execute(new ContractModel() {
Name = "Ramon",
Title = "RamonTitle"
}); //替换域赋值
_AsposeWordHelper.ReadOnly();// 可以设为只读
_AsposeWordHelper.Save(@"C:\Users\NING MEI\Desktop\学习\2.doc");//保存到哪个路径
}
}
}
效果
代码只是随便的写了下还有很多可以扩展的地⽅的,⼩编就懒得扩展了,这只是⼀个demo
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论