首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >.NET & Word -如何在文档中将PlainText转换为MergeField

.NET & Word -如何在文档中将PlainText转换为MergeField
EN

Stack Overflow用户
提问于 2015-06-05 20:57:56
回答 1查看 666关注 0票数 0

我使用的是Visual .NET (VB),所以如果您在C#中有一个解决方案,请先到这里(http://converter.telerik.com/)

我有一份带有文本的文件,还有一组需要替换的单词:我需要用实际的mergefield替换纯文本。

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-08 18:31:57

这是最终结果

代码语言:javascript
复制
 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),这样就可以循环遍历多个文档并替换所有实例。

代码语言:javascript
复制
 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

希望这能帮到别人

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30675693

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档