Word控件Spire.Doc 【文本】教程(6) ;用 C# 中的表格替换 Word 中的文本

这个主题只是我们在 Spire.Doc 论坛上的一位用户提出的另一个请求。为了让更多人了解这个功能,我们将在文章中通过一个示例演示来展示整个过程。此外,我们想提醒您,我们为付费用户和测试用户提供免费的定制演示。

作为一个专业的 .NET Word 组件,Spire.Doc 使开发人员能够将指定段落替换为新创建的表格或现有表格。在本例中,示例 word 文件主体中的第 3 段将替换为新建的表格。

测试文件

用 C# 中的表格替换 Word 中的文本

用表格替换文本的代码片段:

第 1 步:新建一个word文档并加载测试文件。

Document doc = new Document();doc.LoadFromFile(@"....test.docx");

第 2 步:通过找到关键文本字符串“classical antiquity science”返回 TextSection。

Section section = doc.Sections[0];TextSelection selection = doc.FindString("classical antiquity science", true, true);

第 3 步:从TextSection返回TextRange,然后通过TextRange获取OwnerParagraph。

TextRange range = selection.GetAsOneRange();Paragraph paragraph = range.OwnerParagraph;

第 4 步:返回指定段落的从零开始的索引。

Body body = paragraph.OwnerTextBody;int index = body.ChildObjects.IndexOf(paragraph);

第 5 步:创建一个新表。

Table table = section.AddTable(true);table.ResetCells(3, 3);

第 6 步:删除段落并将表格插入到集合中指定索引处。

body.ChildObjects.Remove(paragraph);body.ChildObjects.Insert(index, table);

第 7 步:保存并启动文件。

doc.SaveToFile("result.doc", FileFormat.Doc);System.Diagnostics.Process.Start("result.doc");

结果

用 C# 中的表格替换 Word 中的文本

完整的 C# 代码:

using Spire.Doc;using Spire.Doc.Documents;using Spire.Doc.Fields;namespace ReplaceText{class Program{static void Main(string[] args){Document doc = new Document();doc.LoadFromFile(@"....test.docx");Section section = doc.Sections[0];TextSelection selection = doc.FindString("classical antiquity science", 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.doc", FileFormat.Doc);System.Diagnostics.Process.Start("result.doc");}}}

欢迎下载|体验更多E-iceblue产品

获取更多信息请咨询在线客服  


标签:

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

上一篇 2022年6月23日
下一篇 2022年6月23日

相关推荐

发表回复

登录后才能评论