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:
- 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
- Go to “Save As Html, Filtered”, and save it in a writeable directory.
- In your C# code, first load the entire document into a string
- Convert that string into an instance of StringBuilder
- Use the StringBuilder Replace function, it would look something like this – sb.Replace(“[FULLNAME]”, strFullName);
- Create a TextWriter, and write the StringBuilder to it – make sure you’re saving it with a “.doc” extension.
- Close the TextWriter
All told, the code looks like this
//Create a new filenamestring 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 textsb.Replace(“[FULLNAME]”, strFullName);//save it outTextWriter tw = new StreamWriter(strPathRoot + strFileName + “.doc”);// write a line of text to the filetw.WriteLine(sb.ToString());// close ittw.Close();tw.Dispose();
That’s it!
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