我需要在docx文件中找到类似{{var1}},{{var2}} ... etc等的字符串 [英] I need to find string like {{var1}},{{var2}}...etc in docx file

查看:71
本文介绍了我需要在docx文件中找到类似{{var1}},{{var2}} ... etc等的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.docx文件,其中包含文本和表格.我需要在文字和表格中查找{{var1}},{{var2}} ...等字符串,并将其替换为其他字符串.我有可以帮助的代码...

I have .docx file which contain text as well as tables .i need to find string like {{var1}},{{var2}}...etc among text and table and replace it with some other string. i have code which will help...

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
 Dim sFind As String
        Dim sReplace As String
        sFind = "{{var}}"
 sReplace = "Naresh"

        Dim oWord As Word.Application
        Dim oDoc As Word.Document
 Try
            Dim myStoryRange As Microsoft.Office.Interop.Word.Range

            oWord = CreateObject("Word.Application")
            'soWord.Visible = True
            oDoc = oWord.Documents.Add
            oDoc = oWord.Documents.Open(TextBox1.Text)
            oDoc.Activate()

            Dim c As Integer
            Dim i As Integer
            Dim j As Integer
            j = oDoc.Sentences.Count
            For i = 1 To j
                myStoryRange = oDoc.Sentences(i)
                If (myStoryRange.Information(Word.WdInformation.wdWithInTable) = True) Then
                    ' MessageBox.Show("Document content table ")
                Else
                    'Dim st As String
                    'Dim str1 As String = myStoryRange.Text
                    'Dim str2() As String = str1.Split(" ")
                    'For Each st In str2
                    '    If String.Equals(st, sFind) Then
                    With myStoryRange.Find
                        .ClearFormatting()
                        .Text = sFind
                        .Replacement.Text = sReplace
                        .Forward = True
                        .MatchPrefix = False
                        .Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue
                        .Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceOne)
                    End With
                    'MessageBox.Show(st)
                    '    End If
                    'Next st
            'Dim str1 As String = myStoryRange.Text
            'MessageBox.Show(str1)
         
                        End If
                    Next i
 oDoc.Save()
                    If oDoc IsNot Nothing Then
                        Marshal.ReleaseComObject(oDoc)
                        oDoc = Nothing
                    End If
                    If oWord IsNot Nothing Then
                        Marshal.ReleaseComObject(oWord)
                        oWord = Nothing
                    End If
        Catch ex As ExternalException
            MessageBox.Show(ex.ErrorCode, "Error code no")
            MessageBox.Show(ex.StackTrace)
        Catch Ex As Exception
        End Try
    End Sub

推荐答案

我们创建了用户可定义的占位符(类似于Word Merge,无需用户知道如何设置Word Merge).也许有更好的方法可以做到这一点(自动合并单词);但是,这对我们的客户来说效果很好.


We created user definable placeholders (similar to a Word Merge without the user having to know how to setup the Word Merge). There may be a better way to do this (automating Word Merge); however, this works well with our client.


Dim oApp As Microsoft.Office.Interop.Word.Application = Nothing

oApp = New Microsoft.Office.Interop.Word.Application
oApp.Documents.Open(DirectCast(fileName, Object))
        'WordMergeField is an object that holds the placeholder and the value to replace.
        For Each field As WordMergeField In wordMege.MergeFields

               With oApp
                   .Selection.WholeStory()
                   .Selection.Find.ClearFormatting()
                   .Selection.Find.Replacement.ClearFormatting()

                   With .Selection.Find
                       .Text = field.Keyword
                       .Replacement.Text = field.Value
                       .Forward = True
                       .Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindAsk
                       .Format = False
                       .MatchCase = False
                       .MatchWholeWord = True
                       .MatchWildcards = False
                       .MatchSoundsLike = False
                       .MatchAllWordForms = False

                       .Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
                    End With '.Selection.Find
              End With 'oApp
           Next

           With oApp
               .Selection.SetRange(0, 0)
               .ActiveDocument.Save()
           End With



WordMergeField类如下所示(它包含占位符关键字和关联的值):



The WordMergeField class looks like this (it contains the placeholder keyword and the value associated):

Public Class WordMergeField
  Public Property Value() As Object
  Public Property Keyword() As String
End Class



然后是字段列表:



Then there is list of fields:

Public Class WordMergeFieldsList
    Inherits List(Of WordMergeField)
End Class



wordMerge对象包含WordMergeField对象的列表(特定Word文档中关联的所有关键字/值).



The wordMerge object contains the list of WordMergeField objects (all the keyword/values associated in a specific Word document).

Public Property MergeFields() As WordMergeFieldsList


大多数程序员试图在正文中搜索一些编码字符串",例如{{var1}},{{var2}} ...等.文档以将其替换为其他一些值.但这不是一个好主意!

实现此目的的最简单方法是添加自定义文档属性.
在MS Word 2003中手动操作:
1)菜单文件->属性
2)书签:非标准
3)添加新的自定义属性:
名称:var1
类型:文字
值:blablabla
现在按下添加"按钮并关闭属性"窗口.
4)将光标放在文档中要添加自定义文档属性(值)的位置.
5)菜单->插入->字段
6)在字段"窗口中:
设置类别:" =有关文档的信息".
设置字段名称:" ="DocProperty"
设置属性:" ="var1"
按下确定"按钮.
仅此而已!

{ DOCPROPERTY var1 \* MERGEFORMAT }

如果我使用了错误的菜单名称(不是MS Office的英文版),请纠正我.

以编程方式(使用MS Word):
The most of programmers trying to search some "coded strings", like {{var1}},{{var2}}...etc., in the body of document to replace them with some other values. But it''s not good idea!

The simplest way to achieve this is to add custom document properties.
Manually way in the MS Word 2003:
1) Menu File->Properties
2) Bookmark: Nonstandard
3) To add new custom property:
Name: var1
Type: Text
Value: blablabla
Now push the "Add" button and close "Properties" window.
4) Place the cursor somewhere in the document, where you want to add custom document property (value of).
5) Menu->Insert->Field
6) In the "Field" window:
set "Category:" = "Information about document".
set "Names of fields:" = "DocProperty"
set "Property:" = "var1"
Push "OK" button.
That''s all!

{ DOCPROPERTY var1 \* MERGEFORMAT }

Please correct me, if i used wrong names of menu... (not english version of MS Office).

Programmatically (in MS Word):
Option Explicit

Sub Test()
Dim rng As Range
Set rng = ThisDocument.Range
rng.Select
Selection.Delete
AddCDPWithValue "var1"
rng.InsertParagraphAfter
rng.Fields.Add Range:=rng, Type:=wdFieldEmpty, Text:= _
        "DOCPROPERTY  var1 ", PreserveFormatting:=True
MsgBox "Field {{var1}} was added!", vbInformation, "Info..."
ChangeCDP "var1", "other value"
ThisDocument.Fields.Update
MsgBox "Field {{var1}} was changed!", vbInformation, "Info..."

End Sub

Function ChangeCDP(cdpName As String, cdpValue As String) As Integer
Dim cdp As DocumentProperty
Dim retVal As Integer

On Error GoTo Err_ChangeCDP

retVal = -1 'true
Set cdp = ThisDocument.CustomDocumentProperties(cdpName)
cdp.Value = cdpValue

Exit_ChangeCDP:
    On Error Resume Next
    Set cdp = Nothing
    ChangeCDP = retVal
    Exit Function

Err_ChangeCDP:
    MsgBox Err.Description, vbExclamation, Err.Number
    retVal = 0
    Resume Exit_ChangeCDP
End Function

Function AddCDPWithValue(cdpName As String, Optional cdpValue As String = "test") As Integer
Dim cdp As DocumentProperty
Dim retVal As Integer

On Error Resume Next
ThisDocument.CustomDocumentProperties(cdpName).Delete

On Error GoTo Err_AddCDPWithValue

retVal = -1 'true
Set cdp = ThisDocument.CustomDocumentProperties.Add(Name:=cdpName, _
        LinkToContent:=False, Type:=msoPropertyTypeString, Value:=cdpValue)

Exit_AddCDPWithValue:
    On Error Resume Next
    Set cdp = Nothing
    AddCDPWithValue = retVal
    Exit Function

Err_AddCDPWithValue:
    MsgBox Err.Description, vbExclamation, Err.Number
    retVal = 0
    Resume Exit_AddCDPWithValue
End Function


这篇关于我需要在docx文件中找到类似{{var1}},{{var2}} ... etc等的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆