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.Charset = ""; 

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

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

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




/*  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=''>" +

"<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/>" +



 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;}" +

"-->" +


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>");


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.


At 4:57 PM, Anonymous huntygowk said...


Thanks for the article, was just what I was looking for. I was having problems generating a word document on the server and getting it to open in Word in landscape format and in the print layout view by default . This solved the problems.

At 5:20 PM, Blogger Gayani Devapriya said...

You are most welcome

At 6:33 PM, Blogger GJ.Balaji said...


I saw your articles, really superb it helps lot.



Post a Comment

<< Home