C#を使用して、そのマシンにWordをインストールせずに、docxファイル内のテキスト文字列を見つけて置き換える良い方法はありますか?
2 に答える
はい、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
また、Word文書内のテキストを検索して置き換えるために、Aspose.Wordsfor.NETを試すこともできます。このコンポーネントでは、MSOfficeをインストールする必要はありません。APIは非常にシンプルで、使いやすく、実装も簡単です。
開示:私はAsposeで開発者エバンジェリストとして働いています。