A simple way to create a Microsoft Word document from a template in Asp.net/C# - Digital Tool Factory blog A simple way to create a Microsoft Word document from a template in Asp.net/C# - Digital Tool Factory blog

A simple way to create a Microsoft Word document from a template in Asp.net/C#

Will code for food I recently had the need to create a Microsoft Word document from a template. I initially tried using Office Web Components and Interop but all that really wasn’t worth the trouble.  I wound up doing global replacements in the html of html   Here is how I did it:

  1. Open up your template document in word, and put any target areas in special Brackets, the text would read something like “I, [FULLNAME] do hereby affirm that”.  I found that the target area had to be in uppercase, I’m not sure why
  2. Go to “Save As Html, Filtered”, and save it in a writeable directory.
  3. In your C# code, first load the entire document into a string
  4. Convert that string into an instance of StringBuilder
  5. Use the StringBuilder Replace function, it would look something like this –  sb.Replace(“[FULLNAME]”, strFullName);
  6. Create a TextWriter, and write the StringBuilder to it – make sure you’re saving it with a “.doc” extension.
  7. Close the TextWriter

All told, the code looks like this

//Create a new filename
string strFileName = System.Guid.NewGuid().ToString();
string strPathRoot = “d:domainsMyDomainWord”;
string strPath = strPathRoot + “TemplateHtml.doc”;
string str = System.IO.File.ReadAllText(strPath);
StringBuilder sb = new StringBuilder();
sb.AppendLine(s);
//replace the text
sb.Replace(“[FULLNAME]”, strFullName);
//save it out
TextWriter tw = new StreamWriter(strPathRoot + strFileName + “.doc”);
// write a line of text to the file
tw.WriteLine(sb.ToString());
// close it
tw.Close();
tw.Dispose();

That’s it!

Creative Commons License
photo credit: pvera

 

This post originally appeared on the Stronico blog – with the absorption of Stronico into Digital Tool Factory this post has been moved to the Digital Tool Factory blog

 

Written By Steve French

 

2 responses to “A simple way to create a Microsoft Word document from a template in Asp.net/C#”

Leave a Reply

Your email address will not be published. Required fields are marked *






Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.