在这个简短的教程中,我们将了解如何使用 C#** **在 Word 文档中查找和替换文本。在 C# Word 文档中,无论您使用的是 MS Windows、Linux 还是 macOS 操作系统,都可以对任何基于 .NET 的应用程序使用简单的 API 调用来替换文本。
使用 C# 替换 Word 文档中的文本的步骤
- 使用 MS Visual Studio 从 NuGet 包管理器配置 Aspose.Words 库
- 创建 Document 类的实例以加载源 Word 文件
- 实例化 FindReplaceOptions 类对象以设置不同的属性
- 在 Replace 方法中设置搜索和替换字符串以及不同的属性
- 使用替换的字符串值保存输出 word 文件
在上述步骤中,输入的 Word 文档被加载,然后您可以指定不同的属性来查找和替换文本,包括查找整个单词、替换方向和匹配大小写。最后,在完成使用 C#* 替换 Word 文档中的文本的过程后保存输出文件。
使用 C# 在 Word 文档中查找和替换文本的代码
using System; | |
using Aspose.Words; | |
using Aspose.Words.Replacing; | |
namespace FindAndReplaceTextInWordDocumentInCsharp | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Use Aspose.Words license to remove trial version limitations after replacing text in Word document | |
License licenseForReplacingTextInWord = new License(); | |
licenseForReplacingTextInWord.SetLicense("Aspose.Words.lic"); | |
// Load an input Word file with Document class | |
Document doc = new Document("Input.docx"); | |
// Initialize FindReplaceOptions class object to replace text string | |
FindReplaceOptions options = new FindReplaceOptions(); | |
options.MatchCase = true; | |
options.Direction = FindReplaceDirection.Forward; | |
options.FindWholeWordsOnly = true; | |
// Set the search and replace string in the Replace method | |
doc.Range.Replace("Sample", "Replace", options); | |
// Save the result | |
doc.Save("FindAndReplace.docx"); | |
} | |
} | |
} |
在上面的示例中,只需几行代码即可轻松使用 C# DOCX 替换文本。该过程首先使用 Document class 的实例加载输入 Word 文档,然后设置 FindReplaceOptions Class 的不同属性以调整文本替换过程。最后 replace text in Word document using C# 由 Save 方法完成。
在本文中,我们了解了如何轻松使用 C# 替换 Word 文档中的文本。但是,如果您想学习通过电子邮件发送 Word 文档,请参阅 如何使用 C# 通过电子邮件发送 Word 文档 上的文章。