Create MS Word Document from dynamic data from Sitecore


Figure 1-1: Advanced Properties Dialog

Ever need to create a MS Word document from Sitecore content? I recently was asked to create a MS Word document from a mixture of Sitecore and web service data. I had already been working with a .NET library called DocX by NovaCode, so that is where I decided to start my investigation. DocX supports populating document properties so that seemed like the logical approach to solving this. The idea is to create a MS word document that uses Word fields that merge the document properties into the actual MS Word document.

Step 1: Create the Word document
Figure 1-2: Fields Dialog
  1. Create a docx word document
  2. Edit the Word document
  3. Create the document properties
    • File --> Info --> Properties --> Advanced Properties
    • Go to Custom Tab (See Figure 1-1). Fill in Name and Value then click Add
  4.  Within the document, add fields by hitting CTRL+F9
  5.  Right click --> select Edit Field
  6. Within the field editor (see Figure 1-2), select DocProperty, then select the Property, and make sure to check the “Preserve formatting during updates” as this will force the document to update the fields upon opening.  
  7. Save the DocX file and deploy to a location on your server
 Step 2: Programmatically populate the template and create a new word document for download
  1.  Create a FileStream to open the template created in step 1 and Load into a DocX object
  2.  Next, populate the document properties
  3. Finally save as a MemoryStream and flush the response 


        protected void btnExportDOC_Click(object sender, System.EventArgs e)
        {
            MPRProject mprProject = GetMPRProject();
            Item projectItem = GetProjectItem();

            FileStream fileStream = new FileStream(Request.MapPath(templatePath),System.IO.FileMode.Open, FileAccess.Read);
            DocX template = DocX.Load(fileStream);
            fileStream.Close();
            DocX createdDoc = CreateExportFromTemplate(template, mprProject, projectItem);
            
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            createdDoc.SaveAs(stream);

            Response.Clear();
            Response.ContentType = "Application/msword";
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.docx", mprProject.ProjectNumber));
            Response.BinaryWrite(stream.ToArray());
            Response.Flush();
            Response.Close();
            Response.End();
        }

        private DocX CreateExportFromTemplate(DocX template,MPRProject mprProject,Item projectItem )
        {
            //set custom properties            
            template.AddCustomProperty(new CustomProperty("Project_Title", mprProject.Title));
            //do additional properties
            return template;
        }

Comments