Click here to Skip to main content
14,268,557 members

Use OpenXML to Create a Word Document from an Existing docx File

Rate this:
4.50 (9 votes)
Please Sign up or sign in to vote.
4.50 (9 votes)
6 Feb 2014CPOL
Create a Word document from a docx template


Hi, thanks for your interest in this tip. I am writing this tip because I faced a problem in achieving a simple goal. The goal was to use a Word document as a template and create a new one, some contents from the template should get replaced by user provided values.

There are plenty of ways provided for this task but it needed more understanding of XML templates. May be some of us expect rapid task completion without spending more time on understandings. Hence this tip is useful.

A detailed problem and its solution are provided below.


OpenXML is widely used for creating/updating Office documents. It has a predefined structure of XML for document. One can refer to this link for details.

My Task: Use Open XML and create a new Word document. Template is predefined with extension as "*.docx". This template contains some words which need to be replaced by user provided values.

Let's Do It

Before you start using Visual Studio, check whether you have installed Open XML 2.0 on machine. If yes, we are good to go forward.

Follows the steps:

  1. Open Visual Studio and select the blank ASP.NET project, add references of two DLLs to the project: "WindowsBase" and "DocumentFormat.OpenXml".
  2. Then create two folders "Templates" and "New Documents".
  3. Add a Word document "mytemplate.docx" in the template folder to use it as template for new documents.
  4. Add your text in document. E.g., Hi folks, My name is “Replaceable Text”.
  5. Now on default.aspx, add the following code:
  6. Please enter your name <asp:TextBox ID="txtName" runat="server" />:

    <asp:Button ID="btnSubmit" runat="server" Text="Create" />
  7. Now click onto button to generate click event and add the below code in it.
  8. protected void btnSubmit_Click(object sender, EventArgs e){
            string sourceFile = Server.MapPath(Path.Combine("/", "Templates/mytemplate.docx"));
            string destinationFile = Server.MapPath
            (Path.Combine("/", "New Documents/FirstDocument.docx"));
            // Create a copy of the template file and open the copy 
            File.Copy(sourceFile, destinationFile, true);
           	// create key value pair, key represents words to be replace and 
    		//values represent values in document in place of keys.
            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            keyValues.Add(""Replaceable Text"", txtName.Text);                
      		SearchAndReplace(destinationFile, keyValues);
        catch (Exception ex)
            throw ex;

    Note: "Replaceable Text" can be any text like 'My text' or ::#My Text::#

  9. Add one more function below above event.
  10. // To search and replace content in a document part.
    public static void SearchAndReplace(string document, Dictionary<string, string> dict)
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
            string docText = null;
            using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                docText = sr.ReadToEnd();
            foreach (KeyValuePair<string, string> item in dict) 
                Regex regexText = new Regex(item.Key);
                docText = regexText.Replace(docText, item.Value);
            using (StreamWriter sw = new StreamWriter(
  11. Compile code and execute it and we are done with code.
  12. Enter name in text box and file will open automatically.

Expected Problems and Limitations

This article has been developed by considering that the template you are using is correctly formatted.

  1. Let me explain in detail as:
  2. Consider you are trying to replace word from document is "Employee" it will not work with above code replacement. Because docx file is formatted in XML format internally. XML format for this word can be as follows:

          <w:b />
          <w:color w:val="333333" />
          <w:sz w:val="32" />
          <w:szCs w:val="32" />
    <w:r w:rsidRPr="00DA41AA">
          <w:color w:val="333333" />
          <w:sz w:val="32" />
          <w:szCs w:val="32" />

    As you can see, it has <w:t>E</w:t> formatting for E and rest of the characters are in <w:t>mployee</w:t> XML element, hence our code won't find Employee word. So it cannot be replaced.

  3. We have used Regx class so take care of those charters used in regular expression formatting.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer
India India
No Biography provided

Comments and Discussions

QuestionRead contents of DOCX using Open XML Pin
Member 1129349816-Mar-16 19:26
memberMember 1129349816-Mar-16 19:26 
AnswerRe: Read contents of DOCX using Open XML Pin
Bajirao_27-Apr-16 20:53
memberBajirao_27-Apr-16 20:53 
QuestionHow to update the values in header and footer? Pin
Anuj Aroraa24-Feb-16 16:06
memberAnuj Aroraa24-Feb-16 16:06 
QuestionMultiple Files to create Pin
bjay tiamsic14-Jan-16 16:02
memberbjay tiamsic14-Jan-16 16:02 
SuggestionRe: Multiple Files to create Pin
Bajirao_19-Jan-16 2:07
memberBajirao_19-Jan-16 2:07 
GeneralRe: Multiple Files to create Pin
bjay tiamsic19-Jan-16 17:16
memberbjay tiamsic19-Jan-16 17:16 
Questionuse html tags in this code Pin
Member 1137111828-Jan-15 1:12
memberMember 1137111828-Jan-15 1:12 
SuggestionGreat Example Pin
Pedro Ortiz Aguirre15-Jan-15 15:22
memberPedro Ortiz Aguirre15-Jan-15 15:22 
QuestionQuite USEFUL to me Pin
phear3d20-Oct-14 2:45
memberphear3d20-Oct-14 2:45 
QuestionUsing a list Pin
Member 1104332028-Aug-14 5:42
memberMember 1104332028-Aug-14 5:42 
SuggestionRe: Using a list Pin
Bajirao_16-Oct-14 22:50
memberBajirao_16-Oct-14 22:50 
GeneralMisleading subject of article Pin
Cindy Meister7-Feb-14 6:54
memberCindy Meister7-Feb-14 6:54 
GeneralRe: Misleading subject of article Pin
.dan.g.9-Feb-14 14:07
professional.dan.g.9-Feb-14 14:07 
GeneralMessage Closed Pin
12-Jun-14 4:05
memberRobert te Kaat12-Jun-14 4:05 
GeneralRe: Misleading subject of article Pin
Bajirao_12-Jun-14 7:16
memberBajirao_12-Jun-14 7:16 
GeneralRe: Misleading subject of article Pin
.dan.g.12-Jun-14 13:06
professional.dan.g.12-Jun-14 13:06 
QuestionRisks Pin
cjb1106-Feb-14 22:18
membercjb1106-Feb-14 22:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 11 Oct 2013

Tagged as


18 bookmarked