Wednesday, March 12, 2008

Save to Word in ASP.NET

I was looking around for a code snippet to allow a user to save / export a print version of a web page to a Word file on the fly. This didn't need to be complex at all, but everything I found was either overwrought or would result in a Word document that displayed HTML tagging.

Here's an oversimplified method that works. You can build this up as needed. NOTE: Be sure to eliminate the extra space in the HTML tags below. Blogger's not behaving for me, so I had to insert them.

protected void Button1_Click(object sender, EventArgs e)
{
// Clear the response of any output
Response.Clear();
// Buffer this so the document comes down in one piece
Response.Buffer = true;
// You can do Excel, too, but I haven't tried that yet
Response.ContentType = "application/msword";
// You can use a variable instead of MyDoc, of course
Response.AddHeader("Content-Disposition", "inline;filename=MyDoc.doc");

StringBuilder myBuilder = new StringBuilder();
// This is the key bit versus other examples I've seen
// Adding the opening < html> etc forces Word to open this in Web Layout view
// If you use inline CSS, you can do much more
myBuilder.Append("< html>< head>< /head>< body>");
myBuilder.Append("< h1>Document Head< /h1>");
myBuilder.Append("< p>< strong>" + Label1.Text + "< /strong>< /p>");
myBuilder.Append("< p>" + TextBox1.Text + "< /p>");
// Do whatever else you need and append it as a string
myBuilder.Append("< /body>< /html>");

Response.Write(myBuilder);
Response.End();
Response.Flush();
}

No comments: