C# 使用Aspose.Words实现数据导出自定义word
最后的模板效果是这样的
核心代码(简单易懂):
string path = AppDomain.CurrentDomain.BaseDirectory;//获取运行环境路径
string newWord = path+"new.doc";
File.Copy(path + "template.doc", newWord,true);//复制模板到一个新的文档命名为new.doc
Document doc = new Document(newWord);
string content = doc.Range.Text;//文档内容
string[] splitContent=content.Split(new char[2] { '«', '»' });
List<string> key = new List<string>();//key的集合
for (int i = 0; i < splitContent.Length; i++)
{
if (i % 2 != 0) {
key.Add(splitContent[i]);
}
}
int count = key.Count;
DocumentBuilder docBuilder = new DocumentBuilder(doc);
List<string> lists = new List<string>() {"35", "高起强", "强盛小灵通", "强盛集团" };//模拟数据
for (int i = 0; i < count; i++)
{
if (docBuilder.MoveToMergeField(key[i]))
{
docBuilder.Writeln(lists[i]);//写入数据
}
}
doc.Save(newWord);//保存
核心代码(优化):
using Aspose.Words;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace wordDC
{
class Program
{
static void Main(string[] args)
{
string path = AppDomain.CurrentDomain.BaseDirectory;//获取运行环境路径
string newWord = path+"new.doc";
File.Copy(path + "template.doc", newWord,true);//复制模板到一个新的文档命名为new.doc
List<string> lists = new List<string>() { "35", "高起强", "强盛小灵通", "强盛集团" };//模拟数据
Document doc = new Document(newWord);
DocumentBuilder docBuilder = new DocumentBuilder(doc);
string content = doc.Range.Text;//文档内容
string[] splitContent=content.Split(new char[2] { '«', '»' });
int j = 0;
for (int i = 0; i < splitContent.Length; i++)
{
if (i % 2 != 0) {
string key = splitContent[i];
if (docBuilder.MoveToMergeField(key)){
docBuilder.Writeln(lists[j++]);//写入数据
}
}
}
doc.Save(newWord);//保存
}
}
}
最后运行结果截图: