.NET & Word - 如何将文档中的纯文本转换为 MergeField

.NET & Word - How to Convert PlainText to MergeField in Document

我正在使用 Visual Studio .NET (VB) 因此,如果您有 C# 中的解决方案,请先转到此处 (http://converter.telerik.com/)

我有一个包含文本的文档和一组要替换的单词: 我需要替换明文并替换为实际的 mergefield

Dim replacements(,) As String =
        New String(,) {{"[firstname]", "$Field.FName"},
               {"[lastname]", "$Field.LName"},
               {"[addr]", "$Field.Addr.St"},
               {"[city]", "$Field.City"}}

Dim dotXLoc "c:/test/result.dotx"

Dim Fileformat As Microsoft.Office.Interop.Word.WdSaveFormat = Word.WdSaveFormat.wdFormatXMLTemplate  'SAVE AS DOT
Dim wordApp As Object = New Microsoft.Office.Interop.Word.Application()
Dim currentDoc As Microsoft.Office.Interop.Word.Document = wordApp.Documents.Open(dotXLoc)

' Get bounds of the array.
Dim bound0 As Integer = replacements.GetUpperBound(0)

' Loop over all elements.
For i As Integer = 0 To bound0
    ' Get element.
    Dim FieldFind As String = replacements(i, 0)
    Dim FieldReplace As String = replacements(i, 1)

        '<<< CODE HERE TO REPLACE TEXT WITH MERGEFIELD >>>
Next

currentDoc.SaveAs(dotXLoc & " v2.dotx", Fileformat)
currentDoc.Close()
wordApp.Quit()

这是最终结果

 Public sub main()

            Dim rtfLoc = "c:/temp.rtf"
            Dim dotXLoc = "c:/temp.dotx"
            Dim Fileformat As Microsoft.Office.Interop.Word.WdSaveFormat = Word.WdSaveFormat.wdFormatXMLTemplate
            Dim wordApp As Word.Application = New Microsoft.Office.Interop.Word.Application()
            Dim currentDoc As Microsoft.Office.Interop.Word.Document = wordApp.Documents.Open(rtfLoc)


            TextToMergeField(currentDoc)

            currentDoc.SaveAs(dotXLoc, Fileformat)
            currentDoc.Close()
            wordApp.Quit()
 End Sub

我们从主函数调用 TextToMergeField(currentDoc) 这样我们就可以遍历多个文档并替换所有实例

 Private Sub TextToMergeField(ByRef currentdoc As Word.Document)
    Dim rng As Word.Range
    Dim replacements(,) As String =
    New String(,) {{"[firstname]", "$Field.FName"},
           {"[lastname]", "$Field.LName"},
           {"[addr]", "$Field.Addr.St"},
           {"[city]", "$Field.City"}}
    Dim bound0 As Integer = replacements.GetUpperBound(0)
    currentdoc.Activate()
    For i As Integer = 0 To bound0
        rng = currentdoc.Range
        With rng.Find
            .Text = replacements(i, 0)
            Do While .Execute(Replace:=WdReplace.wdReplaceOne)
                currentdoc.Fields.Add(rng, WdFieldType.wdFieldMergeField, replacements(i, 1))
            Loop
        End With
    Next 
End Sub

希望这对某人有所帮助