How to dynamically create a word document in ASP.NET

July 31, 2010 - 05:30

The easiest way i have found to generate a word document from website content is to use the feature of word to read in HTML documents and display as a normal word document.

Firstly, Create your template document in word and save as Web Page (HTML) format. Open this up in notepad and look at the html code. Transfer this into your editor and add the following lines to the top.

Response.AddHeader("Content-Type","application/msword")
Response.AddHeader("Content-disposition", "attachment; filename=mydocument.doc" )
Response.Charset="utf-8"


This basically tells the browser that the document is a worddocument for download and NOT an html document. Notice that the filename is renamed to .doc extension also. Even though the code is html the document still appears as a normal word document when saved on your pc.


To dynamically create the content of the word document, then just use the normal way in which you would alter the contents of a webpage, use "response.write" etc. to add dynamic data which has been taken from a database for example.

What you will find is that when word saves the html document it defaults to the html page view when opened up in the browser. I always prefer it to open up with the print view as it looks more like a normal word document. To do this look at your word generated HTML source and you will find the lines looking somehing like: (Please ignore the br's on the end of each line, that won't show on your code)


<xmp><w:WordDocument>
<w:GrammarState>Clean</w:GrammarState>
<w:Compatibility>
<w:BreakWrappedTables/>
<w:SnapToGridInCell/>
<w:WrapTextWithPunct/>
<w:UseAsianBreakRules/>
<w:UseFELayout/>
</w:Compatibility>
<w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
</w:WordDocument>
</xmp>


Add the 2 additional lines:

<xmp><w:WordDocument>
<w:View>Print</w:View>
<w:Zoom>80</w:Zoom>
<w:GrammarState>Clean</w:GrammarState>
<w:Compatibility>
<w:BreakWrappedTables/>
<w:SnapToGridInCell/>
<w:WrapTextWithPunct/>
<w:UseAsianBreakRules/>
<w:UseFELayout/>
</w:Compatibility>
<w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
</w:WordDocument>
</xmp>


This will make sure when the document is opened then the view is in print mode and zoomed at 80%.





© 2011 simplevb.net