文檔金喜正規(guī)買球>>Aspose中文文檔>>查找并替換文檔部分中的文本
查找并替換文檔部分中的文本
Aspose.Words是一種高級Word文檔處理API,用于執(zhí)行各種文檔管理和操作任務。API支持生成,修改,轉換,呈現(xiàn)和打印文檔,而無需在跨平臺應用程序中直接使用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); } } }
點擊復制