Program.cs代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Aspose.Words;
namespace WordDemo
{
class Program
{
static void Main(
string[] args)
{
var dic =
new Dictionary<
string,
string>();
dic.Add(
"姓名",
"杨幂");
dic.Add(
"学历",
"本科");
dic.Add(
"联系方式",
"18862100000");
dic.Add(
"邮箱",
"8271111111@qq.com");
dic.Add(
"头像",
".//1.jpg");
Document doc =
new Document(
".//1.doc");
DocumentBuilder builder =
new DocumentBuilder(doc);
foreach (
var key
in dic.Keys)
{
builder.MoveToBookmark(key);
if (key !=
"头像")
{
builder.Write(dic[key]);
}
else
{
builder.InsertImage(dic[key]);
}
}
doc.Save(
"书签操作.doc");
Console.WriteLine(
"已经完成书签操作");
doc =
new Document(
".//2.doc");
foreach (
var key
in dic.Keys)
{
if (key !=
"头像")
{
var repStr =
string.Format(
"&{0}&", key);
doc.Range.Replace(repStr, dic[key],
false,
false);
}
else
{
Regex reg =
new Regex(
"&头像&");
doc.Range.Replace(reg,
new ReplaceAndInsertImage(
".//1.jpg"),
false);
}
}
doc.Save(
"字符串替换操作.doc");
Console.WriteLine(
"已经完成特殊字符串替换操作");
Console.ReadKey();
}
}
public class ReplaceAndInsertImage : IReplacingCallback
{
public string url {
get;
set; }
public ReplaceAndInsertImage(
string url)
{
this.url = url;
}
public ReplaceAction
Replacing(ReplacingArgs e)
{
var node = e.MatchNode;
Document doc = node.Document
as Document;
DocumentBuilder builder =
new DocumentBuilder(doc);
builder.MoveTo(node);
builder.InsertImage(url);
return ReplaceAction.Replace;
}
}
}
运行结果如图: