文档半岛外围网上直营>>Aspose中文文档>>查找并替换文档部分中的文本
查找并替换文档部分中的文本
Aspose.Words是一种高级Word文档处理API,用于执行各种文档管理和操作任务。API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsoft Word。
Aspose API支持流行文件格式处理,并允许将各类文档导出或转换为固定布局文件格式和最常用的图像/多媒体格式。
使用Aspose.Words
在 Aspose.Words 中,使用Replace方法查找和替换文本。
以下代码示例演示如何查找和替换文档部分中的文本:
public static void SearchAndReplaceTextFeature()
{
Document doc = new Document(MyDir + "Search and replace text.docx");
Regex regex = new Regex("Hello World!", RegexOptions.IgnoreCase);
doc.Range.Replace(regex, "Hi Everyone!");
doc.Save(ArtifactsDir + "Search and replace text - Aspose.Words.docx");
}
点击复制
使用 Open XML SDK
需要添加的命名空间:
using System.IO; using System.Text.RegularExpressions; using DocumentFormat.OpenXml.Packaging; using NUnit.Framework;
点击复制
以下代码示例演示如何获取和设置文档中的书签文本:
public static void SearchAndReplaceTextFeature()
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(MyDir + "Search and replace text.docx", true))
{
string docText;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("Hello world!");
docText = regexText.Replace(docText, "Hi Everyone!");
using (StreamWriter sw = new StreamWriter(File.Create(ArtifactsDir + "Search and replace text - OpenXML.docx")))
{
sw.Write(docText);
}
}
}
点击复制

QQ交谈
在线咨询

渝公网安备
50010702500608号

客服热线