Pronunciation / adjective
Bringing something good and unforseen.
    Skip Navigation Links > Code Repository
   

Output a datagrid as an excel spreadsheet page.



 
Return

Output a datagrid as an excel spreadsheet page.

Want to be able to send data to a user as an excel spreadsheet page? Here's how:

First set up a .aspx page with your datagrid on it:
(Styles set in the datagrid will transfer over to the excel page!)
  1. <%@ Page Language="vb" AutoEventWireup="false" Codebehind="ExcelOutput.aspx.vb" Inherits="SurveysRoot.ExcelOutput"%>
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  3. <html>
  4. <head>
  5. <title>ExcelOutput</title>
  6. <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
  7. <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
  8. <meta name="vs_defaultClientScript" content="JavaScript">
  9. <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  10. </head>
  11. <body ms_positioning="GridLayout">
  12. <form id="Form1" method="post" runat="server">
  13. <asp:datagrid id="DataGrid1" Runat="server"></asp:datagrid>
  14. </form>
  15. </body>
  16. </html>


Then in your code-behind:
  1. Public Class ExcelOutput
  2. Inherits System.Web.UI.Page
  3. Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid
  4. Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  5. Try
  6. '---Bind data to your datagrid here!
  7. '---Set the pages content type to an excel spreadsheet download.
  8. Response.ContentType = "application/vnd.ms-excel"
  9. '---Clear the characterset
  10. Response.Charset = ""
  11. '---Viewstate must be turned off.
  12. Me.EnableViewState = False
  13. '---Create a string writer
  14. Dim tw As New System.IO.StringWriter
  15. '---Create an html text writer
  16. Dim hw As New System.Web.UI.HtmlTextWriter(tw)
  17. '---Output the datagrid the the html text writer
  18. DataGrid1.RenderControl(hw)
  19. '---Write out the text to the page using the string writer
  20. Response.Write(tw.ToString())
  21. Catch ExceptionCaught As Exception
  22. '---Handle any errors here
  23. End Try
  24. End Sub
  25. End Class


Return
Microsoft Certified Professional   © 2018 Fortunate.  All rights reserved.
contact: justin@aboutfortunate.com