Hi,
I was wondering how to edit - replace a text in a Word file, but without the Word application scope activity.
I cannot install or use Microsoft Office in the environment where I am executing the robot, so how can I replace a text in a Word file under these circunstamces?
I’ve been reading and you’re supposed to achieve it by using the documentformat.OpenXML package along with the Invoke code activity. However, I’ve been trying to do it without success.
This is the code inside of the Invoke code using VBNet:
I’m passing in 4 arguments.
Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing
Public Sub ReplaceTextAndCreateNewDocx(filePath As String, newFilePath As String, oldText As String, newText As String)
' Load the document
Using wordprocessingDocument As WordprocessingDocument = WordprocessingDocument.Open(filePath, False)
' Copy the document to create a new one
wordprocessingDocument.MainDocumentPart.Document.Save(newFilePath)
End Using
' Load the new document
Using wordprocessingDocument As WordprocessingDocument = WordprocessingDocument.Open(newFilePath, True)
' Get the main document part
Dim mainPart As MainDocumentPart = wordprocessingDocument.MainDocumentPart
' Get the document text
Dim docText As String = mainPart.Document.Body.InnerText
' Replace the text
docText = docText.Replace(oldText, newText)
' Update the document text
mainPart.Document.Body.InnerXml = docText
End Using
End Sub
What am I doing wrong? Is there any other workaround?
Thanks!