Spire.Doc支持查找替换Word中的文本、图片等。 前文介绍了如何用文档、文本替换Word文本,本篇文章将介绍用图片、表格替换Word文本的方法。
更多资源查看:Spire.XLS工作表教程 | Spire.Doc系列教程 | Spire.PDF系列教程
【下载Spire.Doc最新试用版】
Spire.Doc for .NET是一个专业的Word .NET库,设计用于帮助开发人员高效地开发创建、阅读、编写、转换和打印任何来自.NET( C#, VB.NET, ASP.NET)平台的Word文档文件的功能。
C# 用图片、表格替换 Word 文本
Spire.Doc支持查找替换Word中的文本、图片等。 前文介绍了如何用文档、文本替换Word文本,本篇文章将介绍用图片、表格替换Word文本的方法。
用图片替换Word文本
测试文档:

//实例化Document类的对象,并加载测试文档Document doc = new Document();doc.LoadFromFile("testfile.docx");//加载替换的图片Image image = Image.FromFile("g.png");//获取第一个sectionSection sec= doc.Sections[0];//查找文档中的指定文本内容TextSelection[] selections = doc.FindAllString("Google", true, true);int index = 0;TextRange range = null;//遍历文档,移除文本内容,插入图片foreach (TextSelection selection in selections){ DocPicture pic = new DocPicture(doc); pic.LoadImage(image); range = selection.GetAsOneRange(); index = range.OwnerParagraph.ChildObjects.IndexOf(range); range.OwnerParagraph.ChildObjects.Insert(index, pic); range.OwnerParagraph.ChildObjects.Remove(range);}//保存文档doc.SaveToFile("result.docx", FileFormat.Docx);
替换结果:

用表格替换Word文本
测试文档:

//实例化Document类的对象,并加载测试文档Document doc = new Document();doc.LoadFromFile("test.docx");//查找关键字符串文本Section section = doc.Sections[0];TextSelection selection = doc.FindString("参考附录", true, true);//获取关键字符串所在段落的索引TextRange range = selection.GetAsOneRange();Paragraph paragraph = range.OwnerParagraph;Body body = paragraph.OwnerTextBody;int index = body.ChildObjects.IndexOf(paragraph);//添加一个两行三列的表格Table table = section.AddTable(true);table.ResetCells(2, 3);range = table[0, 0].AddParagraph().AppendText("管 (McFarland)");range = table[0, 1].AddParagraph().AppendText("0.5");range = table[0, 2].AddParagraph().AppendText("1");range = table[1, 0].AddParagraph().AppendText("0.25%BaCl2(ml)");range = table[1, 1].AddParagraph().AppendText("0.2");range = table[1, 2].AddParagraph().AppendText("0.4");//移除段落,插入表格 body.ChildObjects.Remove(paragraph);body.ChildObjects.Insert(index, table);//保存文档doc.SaveToFile("result.doc", FileFormat.Doc);
替换结果:

*购买Spire.Doc for .NET正版授权的朋友可以点击“咨询在线客服”哦~~感恩回馈进行时,超值优惠券限时领取,点击下方图片了解详情。

标签:
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!