There are a number of commercial products available that would allow you to create a true word document on the fly. Since office automation is not really an option (MSFT doesn't recommend it http://support.microsoft.com/default.aspx?scid=kb;EN-US;q257757#kb2) you were generally stuck with those components (most of them just a pretty wrapper for old COM objects). Well, that is, until now.
If you still need to write something very specific to word, then you should still use one of the better components out there, but if your goal is pretty straight forward DOC representation of some HTML, you might find this way to be somewhat simpler.
Changing the mime-type to fool the browser is the first thing you should do. This is easy enough and can be done with the following code (but make sure to clear the buffer before):
Response.Clear();
Response.ContentType = "application/msword";
But that's not enough if you are outputting a part of an HTML document (mostly something that you generated yourself by means of a StringBuilder object or an XSLT translation). Word would simply take that html and display it in the contents of the document, tags and everything. Not the effect we are going for!
So the next step is to make the word recognize that it's dealing with HTML. Since we already changed the content type we can achieve that with the following code:
Response.Write (@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
Now we can output whatever we need by simply using Response.Write. However that might not be enough, because if user's settings are set to "ask before open" and user does in fact save the document before opening, he/she will in fact save this doc as an .aspx page. Again, NOT the effect we are going for. To fool the browser into thinking that it is delivering a file and not an .aspx page the following code would do the trick:
Response.AddHeader("Content-Disposition","inline; filename="CSCornerTest.doc");
Note: Keep in mind that this code would have to be added right after you change the content type.
Also, if you use any CSS styles, make sure that they are inline, because the ones that come from .css files will not be automatically included.
Well, that should do the trick. Happy programming!
P.S. special thanks go to Keith Marran.