zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

c#教程 控件 文本 表格 替换 word doc
2023-09-11 14:14:49 时间

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

Spire.Doc for.NET 最新下载(群:767755948)icon-default.png?t=M85Bhttps://www.evget.com/product/3368/download

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

测试文件

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

第 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# 代码:

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");

}
}
}