Click here to Skip to main content
15,867,686 members
Articles / Productivity Apps and Services / Microsoft Office / Microsoft Word
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.50/5 (9 votes)
6 Feb 2014CPOL2 min read 133.8K   19   17
Create a Word document from a docx template

Introduction

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.

Background

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" />:

    XML
    <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. C#
    protected void btnSubmit_Click(object sender, EventArgs e){
        #region
        try
        {
            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);
    
            Process.Start(destinationFile);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    
    #endregion
    } 

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

  9. Add one more function below above event.
  10. C#
    // 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(
                      wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
            {
                sw.Write(docText);
            }
    
        }
    }
  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:

    XML
    <w:r>
        <w:rPr>
          <w:b />
          <w:color w:val="333333" />
          <w:sz w:val="32" />
          <w:szCs w:val="32" />
        </w:rPr>
        <w:t>E</w:t>
    </w:r>
    <w:r w:rsidRPr="00DA41AA">
        <w:rPr>
          <w:color w:val="333333" />
          <w:sz w:val="32" />
          <w:szCs w:val="32" />
        </w:rPr>
        <w:t>mployee</w:t>
    </w:r> 

    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.

License

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


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionRead contents of DOCX using Open XML Pin
Member 1129349816-Mar-16 19:26
Member 1129349816-Mar-16 19:26 
AnswerRe: Read contents of DOCX using Open XML Pin
Bajirao_27-Apr-16 20:53
Bajirao_27-Apr-16 20:53 
QuestionHow to update the values in header and footer? Pin
Anuj Aroraa24-Feb-16 16:06
Anuj Aroraa24-Feb-16 16:06 
QuestionMultiple Files to create Pin
bjay tiamsic14-Jan-16 16:02
bjay tiamsic14-Jan-16 16:02 
SuggestionRe: Multiple Files to create Pin
Bajirao_19-Jan-16 2:07
Bajirao_19-Jan-16 2:07 
GeneralRe: Multiple Files to create Pin
bjay tiamsic19-Jan-16 17:16
bjay tiamsic19-Jan-16 17:16 
Questionuse html tags in this code Pin
Member 1137111828-Jan-15 1:12
Member 1137111828-Jan-15 1:12 
SuggestionGreat Example Pin
Pedro Ortiz Aguirre15-Jan-15 15:22
Pedro Ortiz Aguirre15-Jan-15 15:22 
QuestionQuite USEFUL to me Pin
phear3d20-Oct-14 2:45
phear3d20-Oct-14 2:45 
QuestionUsing a list Pin
Member 1104332028-Aug-14 5:42
Member 1104332028-Aug-14 5:42 
SuggestionRe: Using a list Pin
Bajirao_16-Oct-14 22:50
Bajirao_16-Oct-14 22:50 
GeneralMisleading subject of article Pin
Cindy Meister7-Feb-14 6:54
Cindy Meister7-Feb-14 6:54 
You say you offer a solution how to create a document from a <i>template</i>. The term "template" has special meaning in Word - it's a dotx or dotm file. However, you sample does not use a Word template, simply another document.

I also concur with the other comment about your code for "replacing" not being suitable for production.
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
Robert te Kaat12-Jun-14 4:05 
GeneralRe: Misleading subject of article Pin
Bajirao_12-Jun-14 7:16
Bajirao_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
cjb1106-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.