Gridview to Excel using application/vnd.ms-excel

Last post 08-11-2007 12:02 AM by RickInHouston. 3 replies.

Sort Posts:

  • Gridview to Excel using application/vnd.ms-excel

    07-09-2007, 11:23 PM

    We have been using this in classic ASP and I wanted to continue using it in ASP.NET.  It works fine but I had to adjust the routine from what I found described at MSDN and all over the net.  Here is what you find typically, for instance at MSDN:

     

    ' Set the content type to Excel.
    Response.ContentType = "application/vnd.ms-excel"
    ' Remove the charset from the Content-Type header.
    Response.Charset = ""
    ' Turn off the view state.
    Me.EnableViewState = False
     

    Dim tw As New System.IO.StringWriter()
    Dim hw As New System.Web.UI.HtmlTextWriter(tw)
    ' Get the HTML for the control.
    Me.GridView1.RenderControl(hw)
    ' Write the HTML back to the browser.
    Response.Write(tw.ToString())
    ' End the response.
    Response.End()

    I found that when I pasted all of this code into my Page_Load event, I got this error:

        System.Web.HttpException: Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.

    Here's what I can pass along based on my quick recovery:  If I remove the .rendercontrol, .write and .end statements, the page works exactly as I want.  The data loads into the gridview.  The content is formatted as HTML table.  The content is then offered up as something for Excel to handle, and the user has the option to open or save, either of which works just fine.

    Here's what surprised me:  The code on the internet that includes the lines I removed is always presented as code in some button's click event.  I tried doing the same, assuming that the page, being in a different state by the time you can click a button, needed the other statements to convert properly.  Well, that didn't work.  I found, to my surprise, that I had to remove the same lines from the button click event and then the page worked just fine.  Actually, I got a bonus out of the problem.  By chasing this up a little, I found that I could let the page render as regular HTML first, give the user a button, and let the user "export" to Excel if desired.  Pretty cool.  I may go ahead and enable editing in the gridview, since it's an admin page anyway, and then I have an editing admin interface just pretty close to free.

     My page is fine, but I'm curious to know why the code I found didn't work in the button click event.  If remove the same statements outlined above, then the button works fine.

    I'd love to know what's at work here that means I don't need the lines I'm removing.

    rick w
  • Re: Gridview to Excel using application/vnd.ms-excel

    07-09-2007, 11:55 PM

    Hi There,

    It seem to me that you have a GridView control but not fall within Form tag.

    example:

    This is in your *.aspx page

    <form id="form1" runat="server">

    ALL CONTROL MUST BE IN HERE

    <asp:GridView ...

    </form>

    DC517
    Don't forget to click "Mark as Answer" on the post that helped you.
    This credits that member, earns you a point and marks your thread as Resolved.
  • Re: Gridview to Excel using application/vnd.ms-excel

    07-10-2007, 12:46 PM
    • Loading...
    • cashmore
    • Joined on 11-25-2005, 11:58 PM
    • Shropshire UK
    • Posts 538

     Just add to your code:

       Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)


        End Sub

    Tim 

  • Re: Gridview to Excel using application/vnd.ms-excel

    08-11-2007, 12:02 AM
    Answer

     To follow up and finish my own post with the final result, here is the markup of the report page (nothing special here):

    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="ReportContacts.aspx.vb" Inherits="Report"  %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Contacts: 2007 blah blah blah meeting</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1" Caption="Contact List: 2007 blah blah blah meeting" >
                    <Columns>
                        <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                        <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
                        <asp:BoundField DataField="ContactInfoBrief" HeaderText="Contact Info at Meeting" SortExpression="ContactInfoBrief" />
                    </Columns>
                </asp:GridView>
                <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" OldValuesParameterFormatString="original_{0}"
                    SelectMethod="GetAllSegmeetingSignup" TypeName="Chevron.Upstream.Segmeeting.data.SegmeetingSignupFactory">
                    <SelectParameters>
                        <asp:Parameter DefaultValue="[name]" Name="sortExpression" Type="String" />
                    </SelectParameters>
                </asp:ObjectDataSource>
            </div>
        </form>
    </body>
    </html>
     

     Here is the code behind that does the trick:

     
    Partial Class Report
        Inherits System.Web.UI.Page

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            ' Set the content type to Excel.

            If System.Configuration.ConfigurationManager.AppSettings("reportsasexcel") = "true" Then
                Response.ContentType = "application/vnd.ms-excel"
                ' Remove the charset from the Content-Type header.
                Response.Charset = ""
            End If

        End Sub

    End Class

     That's all that's needed.  The one flourish in it is that I added "reportsasexcel" to my app settings, so that I can toggle this in web.config to either show my reports as web pages or open them as Excel files.  Very handy during development.

    rick w
Page 1 of 1 (4 items)
Microsoft Communities
Page view counter