stephen776
stephen776

Reputation: 9234

ASP.NET Export Data To Word Template

I have several form letters in Word 2007 templates. I need to pass data from my web forms application(Sql Server 2008 backend).

I need to do this as seamlessly as possible so generating a text file for word to use as a datasource is not an option. I also want to avoid running Office on my web server for performance reasons.

I am wondering if there is a way to store the template xml in my database and populate the proper elements with my data when the letters need to be generated, and having this file downloaded directly to the users machine.

Does anyone have a solution for this type of issue?

Upvotes: 1

Views: 2958

Answers (1)

Samuel Neff
Samuel Neff

Reputation: 74899

If you create a Word 2007 .docx file with tokens that you want to replace you can then easily replace the tokens on a server and send the client a new .docx file based on the old one with replaced tokens.

  1. Create your template as a .docx file and save it on the server
  2. Change all your mail-merge fields with easy to find and parse placeholders that are not going to appear int he document normally and will not require XML encoding. For example: {{FirstName}}.
  3. Create a new blank .docx (zip) file for each document you want to generate
  4. Read each file from inside the template .docx file
  5. As you read the source file, search for and replace your tokens as appropriate
  6. Be sure the XML Encode all text you put in the new document. You can either use HttpUtility.HtmlEncode, an XmlTextWriter instance, or a custom method to replace the offending characters (<, ', ", >) with corresponding xml entities.
  7. Send file to client

More complicated things could be done by manipulating the WordML tags but if you just want to replace some variable data, the above would be easiest/fasted method.

Upvotes: 3

Related Questions