apose和spire操作word

2019/04/25 05:39
阅读数 48

 

Apose

public void doSaveAsword(Dictionary<string,string> dict)
{

//--------------------------------------------------------------------------------------------
//1. Apose书签替换方法 wusir001

string Path = "D://1.docx";
Document doc = new Document(Path);
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("已经完成书签操作");

//---------------------------------------------------------------------------------------------

//2. Apose特殊字符串替换方法 wusir002

doc = new Document("D://2.docx");

FindReplaceOptions options = null;

int i = 0;
foreach (var key in dic.Keys)
{

// 1. Apose最基本的字符串替换

//if (key == "姓名")
//{
// doc.Range.Replace("xingming", "gogogoggoggogogogoggo", false, true);
//}

// 2. Apose特殊字符串替换(用书签本身的名称当做特殊字符)
// wusirRemark: the model of word should show it here;
// e.g &头像& 字符串直接写在模板中!

if (key != "头像")
{
var repStr = string.Format("&{0}&", key);

options = new FindReplaceOptions();
options.MatchCase = false;
options.FindWholeWordsOnly = false;
doc.Range.Replace(repStr,dic[key], options);
}
else
{
Regex reg = new Regex("&头像&");
doc.Range.Replace(reg, new ReplaceAndInsertImage("D://2.jpg"), false);
}
}
doc.Save("字符串替换操作.doc");//也可以保存为1.doc 兼容03-07
Console.WriteLine("已经完成特殊字符串替换操作");
Console.ReadKey();
}


public class ReplaceAndInsertImage : IReplacingCallback
{
/// <summary>
/// 需要插入的图片路径
/// </summary>
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;
}
}

//操作文本table
public static void theWayUseTable()
{
Document doc = new Document("Table.SimpleTable.doc");

// Get the first table in the document.
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

// Replace any instances of our string in the entire table.
table.Range.Replace("Carrots", "Eggs", true, true);
// Replace any instances of our string in the last cell of the table only.
table.LastRow.LastCell.Range.Replace("50", "20", true, true);

table.Rows[3].Cells[1].Range.Replace("50","77",false,false);

doc.Save("Table.ReplaceCellText Out.doc");

}
}
}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
在线直播报名
返回顶部
顶部