标签:文件 Document word using doc Words new Aspose DocumentBuilder
Wrod文档根据自定义特殊插入数据
1.根据wrod模板中指定标记替换对应数据。生产新的word文档
2.我这里演示都是固定数据-很多异常验证暂时没写。
3.需要引入 Aspose.Words.dll
1.
//获取文件路径--模板文件
string FilePath = "F:\\NetProject\\WebFile\\1.doc";
//生产后的文件路径-生产后的文件路径以及名字 可自定义。
string physicspath = "F:\\NetProject\\NewFIle\\2.docx";`
Document doc = new Document(FilePath);//程序加载指定doc文件。当doc文件被使用或者打开 这里会抛出异常。自行捕获
DocumentBuilder builder = new DocumentBuilder(doc);
DocumentBuilder是一个用来操作Document的很强大的类。它提供了一系列的方法,方便你插入文本、段落、列表、表格、图片和其他内容。使用它有点类似于使用java的StringBuilder。
DOM的Node能办到的事,使用DocumentBuilder也一样能办到。而且比使用dom的方式操作document的代码要少。
DocumentBuilder内部维护了一个游标Cursor,它允许你指向任何你想指向的地方。我们通过调用DocumentBuilder.MoveToXXX这个方法来指向。比方说,DocumentBuilder.MoveToDocumentStart,DocumentBuilder.MoveToField。
MoveToXXX之后,你可以通过DocumentBuilder.InsertXXX在那里插入文字,图片,书签,域或者是其他元素。比方说, DocumentBuilder.InsertField, DocumentBuilder.InsertHtml。
普通插入字符串内容
1.doc文件内容如下
使用得是邮件合并得一个域代码生成得《Test1》
using Aspose.Words;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
//获取文件路径
string FilePath = "E:\\NetProject\\WebFile\\1.doc";
//生产后的文件路径
string physicspath = "E:\\NetProject\\NewFIle\\2.docx";
Document doc = new Document(FilePath);
DocumentBuilder builder = new DocumentBuilder(doc);
Dictionary<string, string> dic = new Dictionary<string, string>();//这里可以为一个List<T> 存需要替换的标记
dic.Add("Test1", "第一段内容");
dic.Add("Test2", "第二段内容");
List<string> listfield = new List<string>(); //装标记
List<string> listvalue = new List<string>(); //装值
//将对应值装入 容器中
foreach (var item in dic)
{
listfield.Add(item.Key);
listvalue.Add(item.Value);
}
String[] fieldNames = listfield.ToArray();
Object[] fieldValues = listvalue.ToArray();
doc.MailMerge.Execute(fieldNames, fieldValues);//执行对应域标签提交
doc.MailMerge.DeleteFields();
try
{
doc.Save(physicspath, Aspose.Words.Saving.SaveOptions.CreateSaveOptions(SaveFormat.Docx));//生产Doc文件
}
catch (Exception ex)
{
Console.WriteLine("完成");
}
Console.ReadLine();
}
}
}
生成后的文件展示
标签:文件,Document,word,using,doc,Words,new,Aspose,DocumentBuilder 来源: https://www.cnblogs.com/zhmlxx/p/14544955.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。