使用 C#,是否有一种在 docx 文件中查找和替换文本字符串的好方法,而无需在该机器上安装 word?
问问题
5075 次
2 回答
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
于 2010-07-30T22:29:45.243 回答
0
您也可以尝试使用 Aspose.Words for .NET来查找和替换 Word 文档中的文本。此组件不需要安装 MS Office。API 非常简单,易于使用和实现。
披露:我在 Aspose 担任开发人员布道师。
于 2011-08-23T16:48:47.847 回答