下面详细介绍在C#中如何查找文本,然后用表格替换。欢迎查阅
下载并安装 Spire.Doc for .NET,然后通过以下路径将 Spire.Doc.dll 作为引用添加到下载的 Bin 文件夹中:“..Spire.DocBinNET4.0Spire.Doc.dll”。下面详细介绍在C#中如何查找文本,然后用表格替换。
首先查看原始word文档:

第 1 步:创建一个新文档并从文件加载。
Document doc = new Document();doc.LoadFromFile("sample.docx");
第 2 步:找到要用表格替换的地方。
Section section = doc.Sections[0];//"Fortune" as a "key text"TextSelection selection = doc.FindString("Fortune", true, true);TextRange range = selection.GetAsOneRange();Paragraph paragraph = range.OwnerParagraph;Body body = paragraph.OwnerTextBody;int index = body.ChildObjects.IndexOf(paragraph);
第 3 步:添加表格并设置其样式。
Table table = section.AddTable(true);table.ResetCells(3,3);
第 4 步:删除段落并插入表格。
body.ChildObjects.Insert(index, table);
第 5 步:将文档保存到文件。
body.ChildObjects.Remove(paragraph);body.ChildObjects.Insert(index, table);
通过替换文本在word文档中间添加表格的效果截图。
完整代码:
namespace replaceTextwithTable{class Program{static void Main(string[] args){Document doc = new Document();doc.LoadFromFile("sample.docx");Section section = doc.Sections[0];TextSelection selection = doc.FindString("Fortune", 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(3,3);body.ChildObjects.Remove(paragraph);body.ChildObjects.Insert(index, table);doc.SaveToFile("Result.docx", FileFormat.Docx);}}}
以上便是 如何在C#中用表格替换word文档中的文本,如果您有其他问题也可以继续浏览本系列文章,获取相关教程,你还可以给我留言或者加入我们的官方技术交流群。
欢迎下载|体验更多E-iceblue产品
获取更多信息请咨询在线客服 ;
标签:
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!