Replace a variable within a Word file

Asked

Viewed 803 times

3

I am trying to do in C# (Windows Form application) print a Word .doc only that exchanging some vestments of the type @Nome by a string.

In short, I have a contract and I need to print it. Stating specific fields, I already have a Word template file and just need to fill it with data.

I’m doing like this:

public void PreencherPorReplace(string CaminhoDocMatriz)
{
    //Objeto a ser usado nos parâmetros opcionais
    object missing=System.Reflection.Missing.Value;

    Word.Application oApp=new Word.Application() ;

    object template = CaminhoDocMatriz;

    Word.Document oDoc = oApp.Documents.Add(ref template , ref missing,
                                            ref missing, ref missing);

    //Troca o conteúdo de alguns tags
    Word.Range oRng= oDoc.Range(ref missing ,ref missing );

    object FindText = "@Nome";
    object ReplaceWith="Teste";
    object MatchWholeWord = true;
    object Forward = false;

    oRng.Find.Execute( ref FindText, ref missing, ref MatchWholeWord,
                       ref missing, ref missing, ref missing, ref Forward,
                       ref missing, ref missing, ref ReplaceWith, ref missing,
                       ref missing, ref missing, ref missing, ref missing);


    oApp.Visible = true;
}

But it only replaces the @Nome.

  • What you’ve tried and what you’ve failed?

  • I edited the question

  • Your oRng object returns all @Name it does not have a Findall method

1 answer

0


The syntax of the method Find.Execute is:

bool Execute(
    ref Object FindText,
    ref Object MatchCase,
    ref Object MatchWholeWord,
    ref Object MatchWildcards,
    ref Object MatchSoundsLike,
    ref Object MatchAllWordForms,
    ref Object Forward,
    ref Object Wrap,
    ref Object Format,
    ref Object ReplaceWith,
    ref Object Replace,
    ref Object MatchKashida,
    ref Object MatchDiacritics,
    ref Object MatchAlefHamza,
    ref Object MatchControl
)

In the parameter replace, specify the constant wdReplaceAll:

object replace = WdReplace.wdReplaceAll;

//...

oRng.Find.Execute( ref FindText , ref missing,ref MatchWholeWord , 
                   ref missing,ref missing,ref missing,ref Forward,
                   ref missing,ref missing,ref ReplaceWith ,ref replace,
                   ref missing,ref missing,ref missing,ref missing);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.