6

C#を使用して、そのマシンにWordをインストールせずに、docxファイル内のテキスト文字列を見つけて置き換える良い方法はありますか?

4

2 に答える 2

5

はい、OpenXMLを使用しています。特定の質問に対処する記事は次のとおりです。Word2007OpenXML形式のドキュメント用の単純な検索および置換ユーティリティの作成

このファイル形式を使用するための1つのオプションは、DocumentFormat.OpenXml.Packaging名前空間でOpen XML形式のアプリケーションプログラミングインターフェイス(API)を使用することです。この名前空間のクラス、メソッド、およびプロパティは、DocumentFormat.OpenXml.dllファイルにあります。このDLLファイルは、Open XMLFormatSDKバージョン1.0をインストールすることでインストールできます。この名前空間のメンバーを使用すると、Excel 2007ブック、PowerPoint 2007プレゼンテーション、およびWord2007ドキュメントのパッケージコンテンツを簡単に操作できます。

..。

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

また、Word文書内のテキストを検索して置き換えるために、Aspose.Wordsfor.NETを試すこともできます。このコンポーネントでは、MSOfficeをインストールする必要はありません。APIは非常にシンプルで、使いやすく、実装も簡単です。

開示:私はAsposeで開発者エバンジェリストとして働いています。

于 2011-08-23T16:48:47.847 に答える