There's something out there in life that will delight and amaze you.
Get up, get moving, and go find out what it is. - (Ralph Marston)

Sunday, November 04, 2007

Resource Saving Dynamic Word Doc Generation.

Most often in web development we may require to export web content or contents of a database query to some other media such as word. Creating a word document, writing the content and saving it in the web server and downloading at demand is often time and resource consuming. Here is a quick way to dynamically generate the word document using the Http Response.

To start with, lets assume you already have some content ready to write to a word doc as a response to a button click event of your web page.

Response.Clear();

Response.Charset = ""; 

Response.AppendHeader("Content-Type", "application/msword");

Response.AddHeader("Content-Disposition", "attachment; filename=" + "MyWord.doc");

Response.AddHeader("Content-Length", sb.ToString().Length.ToString());

Response.Write(sb.ToString());

Response.End();

Response.Flush();

/*  section (A)  */

Here is a way to add a little formatting to the word document. Lets assume you need to make the page orientation to landscape and want to view in the Print View with the zoom 75%. Here is how you do it.

StringBuilder sb = new StringBuilder(); 

sb.Append("<html xmlns:o='urn:schemas-microsoft-com:office:office' " +

"xmlns:w='urn:schemas-microsoft-com:office:word'" +

"xmlns='http://www.w3.org/TR/REC-html40'>" +

"<head><title>My Title</title>") ;

string sStyle = "<!--[if gte mso 9]><xml>" +

"<w:WordDocument>" +

"<w:View>Print</w:View>" +

"<w:Zoom>75</w:Zoom>" +

"<w:DoNotOptimizeForBrowser/>" +

"</w:WordDocument></xml><![endif]-->";

 sb.Append(sStyle);

 sb.Append("<style>" +

"<!-- /* Style Definitions */" +

"@page Section1" +

"   {size:841.9pt 595.3pt; " +

"   mso-page-orientation:landscape;  " +

"   margin:.5in 1.0in 1.0in .5in ; " +

"   mso-header-margin:.5in; " +

"   mso-footer-margin:.5in; mso-paper-source:0; }" +

" div.Section1" +

"   {page:Section1;}" +

"-->" +

"</style></head>");

sb.Append("<body lang=EN-US style='tab-interval:.5in'><div class=Section1>" );

/*Now append the content to be written to the word document.*/

sb.Append("<b>Sample Test <b>");

sb.Append("<div></body></html>");

And use Response.Write() section (section (A) )mentioned in the above to obtain the response as a word document.

As an overview, this is more useful when you want to extract large amount of information in a predefined word format. Such as extracting transaction information from the online bank statement for example.