将GridView导出到Excel(不工作)

时间:2012-08-31 21:21:24

标签: asp.net vb.net gridview updatepanel export-to-excel

我花了最近两天试图将一些血腥数据导出到Excel。经过大量研究后,我确定最好和最常用的方法是使用HttpResponse标题,如下面的代码所示。在调试模式中经过无数次之后,我已经确认数据实际存在,并且按照我想要的方式进行过滤和排序。但是,它不会作为Excel文件下载,也不会做任何事情。

我怀疑这可能与我的UpdatePanelImageButton没有正确回发有关,但我不确定。我究竟做错了什么?请帮我调试这个问题。我会永远感激。谢谢。 :)

标记

<asp:UpdatePanel ID="statusUpdatePanel" runat="server" UpdateMode="Conditional">
<Triggers>
    <asp:AsyncPostBackTrigger ControlID="btnExportXLS" EventName="Click" />
</Triggers>
<ContentTemplate>
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="10"
        AllowSorting="True" DataSourceID="GridView1SDS" DataKeyNames="ID">
    </asp:GridView>
    <span><asp:ImageButton ID="btnExportXLS" runat="server" /></span>
</ContentTemplate>
</asp:UpdatePanel>

代码隐藏

Protected Sub ExportToExcel() Handles btnExportXLS.Click
    Dim dt As New DataTable()
    Dim da As New SqlDataAdapter(SelectCommand, ConnectionString)

    da.Fill(dt)

    Dim gv As New GridView()
    gv.DataSource = dt
    gv.DataBind()

    Dim sw As New IO.StringWriter()
    Dim hw As New System.Web.UI.HtmlTextWriter(sw)
    Response.ContentType = "application/vnd.ms-excel"
    Response.AddHeader("content-disposition", "attachment;filename=Report.xls")
    Response.Charset = String.Empty

    gv.RenderControl(hw)
    Response.Write(sw.ToString()) 'sw is a valid html table, but no Excel file downloads. :(
    Response.End()
End Sub

2 个答案:

答案 0 :(得分:7)

  1. 我在开头时错过了Response.Clear
  2. 您正在调用GridView.RenderControl(htmlTextWriter),因此该页面引发了一个异常,即Server-Control是在Form外部呈现的。尝试在调试器中执行它,我相当确定你会看到异常。
  3. 您可以通过覆盖VerifyRenderingInServerForm

    来避免此异常
    Public Overrides Sub VerifyRenderingInServerForm(control As Control)
        ' Confirms that an HtmlForm control is rendered for the specified ASP.NET '
        ' server control at run time.  '
    End Sub
    

    请参阅herehere

    修改:我刚刚看到您使用的是UpdatePanel。确保您为该按钮创建了一个(完整 - )PostBackTrigger

    <asp:UpdatePanel ID="UpdGridInfo" runat="server" >
        <ContentTemplate>
            <asp:ImageButton ToolTip="export to Excel" ID="BtnExcelExport" ImageUrl="~/images/excel2007logo.png" runat="server" />
        </ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="BtnExcelExport" />
        </Triggers>
    </asp:UpdatePanel>
    

    但是我没有创建一个可以由excel解释的html表,而是使用像EPPlus(GPL)这样的Excel库,我可以热烈推荐。

    然后从DataTable创建Excel文件并将其写入响应就这么简单:

    Dim pck = New ExcelPackage()
    Dim ws = pck.Workbook.Worksheets.Add("Worksheet-Name")
    ws.Cells("A1").LoadFromDataTable(dt, True, OfficeOpenXml.Table.TableStyles.Medium1)
    Response.Clear()
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    Response.AddHeader("content-disposition", "attachment;  filename=ExcelFileName.xlsx")
    Response.BinaryWrite(pck.GetAsByteArray())
    Response.End()
    

    这是另一个例子:http://epplus.codeplex.com/wikipage?title=WebapplicationExample

答案 1 :(得分:0)

我的解决方案是按照以下步骤操作:

第1步(在设计页面中)

EnableEventValidation ="false"

中设置"%@ Page"
<%@ Page Title="" Language="VB" MasterPageFile="~/Aroghyam.master" EnableEventValidation ="false" AutoEventWireup="false" CodeFile="Search_IncidentStatus.aspx.vb" Inherits="Search_IncidentStatus" %>

第2步(在设计页面中)

如果有更新面板,则添加导出按钮,单击该按钮时会将网格数据导出为Excel格式asp:PostBackTrigger(请勿将其放入asp:AsyncPostBackTrigger

`<asp:PostBackTrigger ControlID="btnExportToExcel" />`

第3步(代码中)

添加以下内容:

Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)

    ' no implementation necessary,used just to handle error (just paste this to your       code)
End Sub

第4步(代码中)

生成Excel内容:

'-------------------GETTING THE DATATABLE------------------
Dim searchResultTable as new Datatable = // GET TABLE FROM DATABASE
'----------------------------------------------------------

'-------------------ASSIGNING TABLE TO GRID----------------
GvIncidentStatus.DataSource = SearchResultTable
GvIncidentStatus.DataBind()

'-----------------CODE FOR GENERATION TO EXCEL
Response.Clear()
GvIncidentStatus.AllowPaging = False
Response.Buffer = True
Me.EnableViewState = False
Response.AddHeader("content-disposition", String.Format("attachment;filename=MyExcelfile.xls"))
Response.Charset = ""
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
GvIncidentStatus.RenderControl(hw)
Response.Output.Write(sw.ToString())
Response.End()
'-----------------

单击导出按钮现在将下载Excel文档。