Search code examples
c#ms-wordfilestream

Find and replace using existing word .doc with .net core


I'm trying to find and replace specific words/strings in a word document template i have created and added to my .net core project.

I'm currently using NPOI to do this but I cant seem to figure it out as my C# knowledge is not great!

In theory I want to read the ready made .docx template and then replace what I need to and then save it.

I've tried everything I could think of but still not working.

Here the code i'm left with:

var docUrl = @"App_Data/Document_Template.docx";

using (FileStream file = new FileStream(docUrl, FileMode.Open, FileAccess.Read))
        {
            XWPFDocument doc = new XWPFDocument(file);

            // get the document template using docUrl and replace string with another string.

            doc.Write(file);

        }

Any help would be awesome as i've spent so much time researching and trying to implement this and just not having any luck!


Solution

  • For replace specific word(s) in MS Word, first you should add the below reference from nuget:

    Install-Package Microsoft.Office.Interop.Word
    

    This sample code replace specified string with another one:

    namespace MSWordReplacement
    {
        class Program
        {
            static void Main(string[] args)
            {
                Application app = new Application();
                Document doc = app.Documents.Open(@"C:\Sample.docx");
    
                // Assign a search string to a variable.
                object findText = "Find me.";
    
                // Clear formatting from previous searches.
                app.Selection.Find.ClearFormatting();
    
                if (app.Selection.Find.Execute(ref findText))
                {
                    // Replace new text.
                    app.Selection.Text = "You found me!";
                }
                else
                {
                    // Do somthing else.
                }
    
                doc.Close(true);
                app.Quit();
            }
        }
    }
    

    For warning you should know this package is working but it may not be fully compatible with dot net core!

    For more information use this link: Programmatically search for and replace text in documents