c# word interop find and replace everything
Asked Answered
R

5

14

I have some code to replace text inside a word 2010 docx.

        object fileName = Path.Combine(System.Windows.Forms.Application.StartupPath, "document.docx");

        Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application { Visible = true };

        Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(ref fileName, ReadOnly: false, Visible: true);

        aDoc.Activate();

        Microsoft.Office.Interop.Word.Find fnd = wordApp.ActiveWindow.Selection.Find;

        fnd.ClearFormatting();
        fnd.Replacement.ClearFormatting();
        fnd.Forward = true;

        fnd.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;

        fnd.Text = "{id}";
        fnd.Replacement.Text = "123456";
        fnd.Execute(Replace: WdReplace.wdReplaceAll);

This works without formatting. But when {id} is formatted it does not replace the text.

How can I make this code ignore formatting?

Reproductive answered 8/10, 2013 at 15:41 Comment(0)
G
44

I use this function to find and replace. you can specify any of the options.

private void FindAndReplace(Microsoft.Office.Interop.Word.Application doc, object findText, object replaceWithText)
{
    //options
    object matchCase = false;
    object matchWholeWord = true;
    object matchWildCards = false;
    object matchSoundsLike = false;
    object matchAllWordForms = false;
    object forward = true;
    object format = false;
    object matchKashida = false;
    object matchDiacritics = false;
    object matchAlefHamza = false;
    object matchControl = false;
    object read_only = false;
    object visible = true;
    object replace = 2;
    object wrap = 1;
    //execute find and replace
    doc.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
        ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace,
        ref matchKashida ,ref matchDiacritics, ref matchAlefHamza, ref matchControl);                
}

And usage would be :

object fileName = Path.Combine(System.Windows.Forms.Application.StartupPath, "document.docx");
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application { Visible = true };
Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(fileName, ReadOnly: false, Visible: true);
aDoc.Activate();
FindAndReplace(wordApp, "{id}", "12345");

And you can use the FindAndReplace function over and over....
Hope this helps.

Glutinous answered 9/10, 2013 at 22:30 Comment(6)
This is inconsistent. Sometimes it works, sometimes it doesn't.Bobbie
It works! But the problem is formatting. It will changed the formatting of replaced fileTurgeon
how to find and replace in headers and footers? (above code not work)Calves
the text inside Shape or TextBox doesn't work. Anyone have solution?Zeuxis
@SovandaraLENG Check answer of Nayana AdassuriyaDebtor
@Debtor Thank you, I have try that solution but It doesn't fit to my problem. I found another way for do itZeuxis
D
7

From Visual Studio 2013 you can do this:

Microsoft.Office.Interop.Word.Range range = this.Application.ActiveDocument.Content;
range.Find.ClearFormatting();
range.Find.Execute(FindText: "find text", ReplaceWith: "replace text", Replace: Word.WdReplace.wdReplaceAll);

(Posted for the benefit of anyone, like me, who came across this question but is not necessarily using the same versions of the tools as the OP.)

Discophile answered 14/8, 2017 at 8:45 Comment(2)
Word is in the following namespace : Microsoft.Office.InteropUprise
Thanks for the suggestion! I'm using VS2019 with Office365 (MS Word 2016), so i had to change the last option in the range.execute to : "range.Find.Execute(FindText: Target, ReplaceWith: value, Replace: WdReplace.wdReplaceAll);"Fettle
G
4

A method that divides a string if the string contains more than 255 characters.

    void FindAndReplace(Microsoft.Office.Interop.Word.Application doc, string findText, string replaceWithText)
    {
        if (replaceWithText.Length > 255)
        {
            FindAndReplace(doc, findText, findText + replaceWithText.Substring(255));
            replaceWithText = replaceWithText.Substring(0, 255);
        }

        //options
        object matchCase = false;
        object matchWholeWord = true;
        object matchWildCards = false;
        object matchSoundsLike = false;
        object matchAllWordForms = false;
        object forward = true;
        object format = false;
        object matchKashida = false;
        object matchDiacritics = false;
        object matchAlefHamza = false;
        object matchControl = false;
        object read_only = false;
        object visible = true;
        object replace = 2;
        object wrap = 1;

        //execute find and replace
        doc.Selection.Find.Execute(findText, ref matchCase, ref matchWholeWord,
            ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, replaceWithText, ref replace,
            ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
    }
Goatee answered 12/12, 2017 at 13:57 Comment(0)
A
4

If someone looking for answer in 2021 and uses VS2019, You can fallow this method including replace the text inside shapes such as text boxes.

 private void FindAndReplace(Application app,Document doc, string findText, string replaceWithText)
        {
            Find findObject = app.Selection.Find;
            findObject.ClearFormatting();
            findObject.Text = findText;
            findObject.Replacement.ClearFormatting();
            findObject.Replacement.Text = replaceWithText;
            object missing = System.Reflection.Missing.Value;
            object replaceAll = WdReplace.wdReplaceAll;
            findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceAll, ref missing, ref missing, ref missing, ref missing);

            var shapes = doc.Shapes;
            foreach (Shape shape in shapes)
            {
                if (shape.TextFrame.HasText != 0)
                {
                    var initialText = shape.TextFrame.TextRange.Text;
                    var resultingText = initialText.Replace(findText, replaceWithText);
                    if (initialText != resultingText)
                    {
                        shape.TextFrame.TextRange.Text = resultingText;
                    }
                }
            }
        }
Amena answered 19/3, 2021 at 19:31 Comment(2)
This solution is better, because of replacing in shapesDebtor
the problem its remove table formattingZeena
B
1

You can try this :

var doc =  new Microsoft.Office.Interop.Word.Application().Documents.Open("document.docx");

doc.Content.Find.Execute( "{id}", false, true, false, false, false, true, 1, false,  "12345", 2,
false, false, false, false);
doc.Save();
Berner answered 22/8, 2014 at 8:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.