簡體   English   中英

C# 替換 docx 中的文本字符串

[英]C# to replace strings of text in a docx

使用 C#,有沒有一種好方法可以在 docx 文件中查找和替換文本字符串,而無需在該機器上安裝 word?

是的,使用Open XML 這是一篇解決您的具體問題的文章: 為 Word 2007 Open XML 格式文檔創建簡單的搜索和替換實用程序

要使用此文件格式,一種選擇是使用 DocumentFormat.OpenXml.Packaging 命名空間中的 Open XML 格式應用程序編程接口 (API)。 此命名空間中的類、方法和屬性位於 DocumentFormat.OpenXml.dll 文件中。 您可以通過安裝 Open XML Format SDK 1.0 版來安裝此 DLL 文件。 此命名空間中的成員允許您輕松處理 Excel 2007 工作簿、PowerPoint 2007 演示文稿和 Word 2007 文檔的包內容。

...

 Private Sub Search_Replace(ByVal file As String) Dim wdDoc As WordprocessingDocument = WordprocessingDocument.Open(file, True) ' Manage namespaces to perform Xml XPath queries. Dim nt As NameTable = New NameTable Dim nsManager As XmlNamespaceManager = New XmlNamespaceManager(nt) nsManager.AddNamespace("w", wordmlNamespace) ' Get the document part from the package. Dim xdoc As XmlDocument = New XmlDocument(nt) ' Load the XML in the part into an XmlDocument instance. xdoc.Load(wdDoc.MainDocumentPart.GetStream) ' Get the text nodes in the document. Dim nodes As XmlNodeList = Nothing nodes = xdoc.SelectNodes("//w:t", nsManager) Dim node As XmlNode Dim nodeText As String = "" ' Make the swap. Dim oldText As String = txtOldText.Text Dim newText As String = txtNewText.Text For Each node In nodes nodeText = node.FirstChild.InnerText If (InStr(nodeText, oldText) > 0) Then nodeText = nodeText.Replace(oldText, newText) ' Increment the occurrences counter. numChanged += 1 End If Next ' Write the changes back to the document. xdoc.Save(wdDoc.MainDocumentPart.GetStream(FileMode.Create)) ' Display the number of change occurrences. txtNumChanged.Text = numChanged End Sub

您也可以嘗試Aspose.Words for .NET查找和替換 Word 文檔中的文本 此組件不需要安裝 MS Office。 API 非常簡單,易於使用和實現。

披露:我在 Aspose 擔任開發人員布道者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM