Copy and paste the code below into your code-behind. These subroutines are tied to a button on the aspx page: <asp:Button ID="ExprtToWordBtn1" runat="server" Text="Click Me to Export to Word" />
Public
Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
End Sub
Protected Sub ExprtToWordBtn1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ExprtToWordBtn1.Click
Response.Clear()
Response.Buffer() = True
'name your document
Dim docID as String = "MyLANDSCAPEWordDoc.doc"
HttpContext.Current.Response.ContentType = "application/msword"
HttpContext.Current.Response.ContentEncoding = System.Text.UnicodeEncoding.UTF8
"UTF-8"HttpContext.Current.Response.Charset =
"Content-Disposition", "attachment; filename=" & docID)Response.AddHeader(
Response.Write("<html>")
Response.Write("<head>")
Response.Write("<META HTTP-EQUIV=""Content-Type"" CONTENT=""text/html; charset=UTF-8"">")
Response.Write(
"<meta name=ProgId content=Word.Document>")
Response.Write("<meta name=Generator content=""Microsoft Word 9"">")
Response.Write("<meta name=Originator content=""Microsoft Word 9"">")
Response.Write("<style>")
Response.Write("@page Section1 {size:595.45pt 841.7pt; margin:.75in .5in .75in .5in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}")
Response.Write("div.Section1 {page:Section1;}")
Response.Write("@page Section2 {size:841.7pt 595.45pt;mso-page-orientation:landscape;margin:1.25in 1.0in 1.25in 1.0in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}")
Response.Write("div.Section2 {page:Section2;}")
Response.Write("<style>")
Response.Write("</head>")
Response.Write("<body>")
Response.Write("<div class=Section2>")
' Section 1: Portrait | Section2: Landscape
'put whatever you want here. it will render in your word document.
'As an example, I'll render a gridview:
Dim oStringWriter As New System.IO.StringWriter()
Dim oHtmlTextWriter As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(oStringWriter)
Gridview1.RenderControl(oHtmlTextWriter)
Response.Output.Write(oStringWriter.ToString())
Response.Write("</div>")
Response.Write("</body>")
Response.Write("</html>")
HttpContext.Current.Response.Flush()
Response.End()
End Sub
I love this stuff.