C#用于替换docx中的文本字符串

Tim*_*man 6 c# replace docx openxml openxml-sdk

使用C#,有没有一种很好的方法来查找和替换docx文件中的文本字符串而不在该机器上安装word?

Tod*_*ain 5

是的,使用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
Run Code Online (Sandbox Code Playgroud)