Geeks With Blogs
Ben Adler's Development Posting solutions as I find them
One of my clients had users downloading a word document to edit and print out. Some of these fields in the Word Document can be pre-populated with data.

There is a dll called DocX available here: http://docx.codeplex.com/

Keep in mind, this only works with .docx, not .doc file formates

Sample code:

private void GetDocument()

        {

            //Get parameters

            string FirstName = "Benjamin";

            string LastName = "Adler";

            string Username = "Badler";

 

            //Get template

            string TemplateFileName = @"C:\temp\test.docx";

            DocX template = DocX.Load(TemplateFileName);

           

            //Replace macros with parameters

            template.ReplaceText("%FirstName%", FirstName, false, System.Text.RegularExpressions.RegexOptions.Singleline, null, null, MatchFormattingOptions.ExactMatch);

            template.ReplaceText("%LastName%", LastName, false, System.Text.RegularExpressions.RegexOptions.Singleline, null, null, MatchFormattingOptions.ExactMatch);

           

            //Save with new file name

            string newFile = string.Format(@"C:\temp\test_{0}.docx", Username);

            template.SaveAs(newFile);

        }


Posted on Friday, June 13, 2014 2:31 PM C# , ASP.Net , DocX | Back to top


Comments on this post: C# Replace Macros in Word Document .docx

# re: C# Replace Macros in Word Document .docx
Requesting Gravatar...
It is really wonderful article and I was missing knowledge about how to replacing macros in MS Word.
I would like to ask a question, I have downloaded on template from website; http://www.wordstemplates.org/ and now I want to remove macros which they have fixed there. Can you guide in this regard?
Left by Intuitive Mind on Sep 27, 2017 8:55 AM

Your comment:
 (will show your gravatar)


Copyright © BenAdler | Powered by: GeeksWithBlogs.net