繁体   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