IRONSOFTWAREHOME
编辑文本
using IronWord;

// Open existing Word
WordDocument doc = new WordDocument("sample.docx");

// Edit existing text
doc.Paragraphs[0].ReplaceText("old text.", "This is the edited text.");

      // Edit text by retrieving the old text
      doc.Paragraphs[1].ReplaceText(doc.Paragraphs[1].Texts[1].Text, "Updated content for the second paragraph.");

      // Export docx
      doc.SaveAs("document.docx");
Imports IronWord

' Open existing Word
Dim doc As New WordDocument("sample.docx")

' Edit existing text
doc.Paragraphs(0).ReplaceText("old text.", "This is the edited text.")

' Edit text by retrieving the old text
doc.Paragraphs(1).ReplaceText(doc.Paragraphs(1).Texts(1).Text, "Updated content for the second paragraph.")

' Export docx
doc.SaveAs("document.docx")
NuGet Download
PM > Install-Package IronWord
编辑文本

编辑文本

IronWord 中的"编辑文本"功能允许开发人员修改现有 DOCX 文档的内容。 开发人员可以通过访问ReplaceText方法直接更改文本。 这为需要动态更新内容的场景提供了灵活性,例如更新报告的特定部分、替换占位符或根据用户输入或数据修改文本。

能够对文本进行精细化编辑,确保可以进行精确的更改,而不会影响文档其余部分的结构或格式。 此功能在内容需要频繁更新或修改的自动化文档生成工作流程中特别有用。

编辑现有 DOCX 文件中文本的 5 个步骤

  • using IronWord;
  • WordDocument doc = new WordDocument("sample.docx");
  • doc.Paragraphs[0].ReplaceText("old text.", "This is the edited text.");
  • doc.Paragraphs[1].ReplaceText(doc.Paragraphs[1].Texts[1].Text, "Updated content for the second paragraph.");
  • doc.SaveAs("document.docx");

替换文本

此代码演示了如何使用 IronWord 编辑现有 Word 文档中的特定文本。 初始化WordDocument对象以加载"sample.docx"。 然后代码从Paragraphs集合,并修改文档的第一和第二段。 第一次修改通过调用Text对象的文本。 方法ReplaceText需要两个参数,第一个是要查找的字符串值,第二个是用于替换旧值的新文本。 在这个例子中,我们在第一个参数中提供了一个静态字符串,并用第一个段落的新字符串更新了它。

然而,有时你需要一个更动态的变量。 为了实现这一点,我们可以进一步访问第二段中的现有文本。 我们首先访问与第一个实例类似的Paragraphs集合。 仍然在旧文本字段中,我们输入更多的逐层访问,通过访问Text属性来获取现有文本。 这种方法让您可以完全控制查找和更新现有字符串,从而确保您对文档操作过程充满信心。

在IronWord教程中探索文档元素 ReplaceText ReplaceText ReplaceText

在 GitHub 上查看

准备开始了吗?

Nuget Downloads 56,401版本:2026.9刚刚发布

Key in blue circle

立即获取免费的 30 天试用版密钥

Your trial license will be sent to your email address

无任何限制。100% 解锁。无需信用卡。

bullet_checked无需信用卡或创建账户无任何限制。100% 解锁。无需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
预约您的免费现场演示
Booking Badge

深受全球数百万工程师信赖

Iron Software 的客户徽标
获取您的无义务咨询
填写下面的表格或通过sales@ironsoftware.com
您的资料将始终保密。
深受全球数百万工程师信赖
Iron Software 的客户徽标
立即获取您的免费30 天试用密钥
无需信用卡或创建账户