Vb.net导出gridview为excel

时间:2013-09-20 17:13:25

标签: asp.net vb.net excel gridview

我无法将gridview导出到excel文件。一切正常,除非我点击导出按钮,应该导出到excel文件的数据显示在网页上。我怀疑这是Response.ContentType和我指定的文件名的问题。但是,我已经完成了多个文档和示例,看起来这两个问题似乎不是我的问题。有人可以帮忙吗?

<asp:Button ID="btnExport" runat="server" Text="Export To MS Excel File" CssClass="btnMain" OnClick="btnExport_Click" />    




Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) 

        Dim filename As String = "PerformanceEval Status Report" & Date.Now.Year.ToString & "-" & _
                                    formatNumberTo2Digits(DateTime.Now.Month) & "-" & formatNumberTo2Digits(DateTime.Now.Day) & ".xls"

        With Page.Response

            .Clear()
            .Buffer = True
            .AddHeader("content_disposition", "attachment;filename" & filename)
            .Charset = ""

            '--to open the Excel file without saving then comment out the line below
            '.Cache.SetCacheability(HttpCacheability.NoCache)

            '.ContentType = "application/vnd.xls"   'data appears on web page 
            '.ContentType = "application/vnd.ms-excel"  'try to download .aspx document NOT .xml
            .ContentType = "application/ms-excel"  'data appears on web page 

        End With


        Dim strWriter As New System.IO.StringWriter
        Dim htmlWriter As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(strWriter)

        Dim gvexport As GridView = New GridView
        gvexport.AutoGenerateColumns = False
        gvexport.CssClass = "gridData"
        gvexport.GridLines = GridLines.Horizontal
        gvexport.HeaderStyle.CssClass = "gridHeader"
        gvexport.RowStyle.CssClass = "gridRow"
        gvexport.AlternatingRowStyle.CssClass = "gridRow_Alt"
        gvexport.FooterStyle.CssClass = "gridFooter"

        Dim dv As DataView = New DataView(Me.ds.Tables(0))  'default is sorted by last name
        'Dim dv As DataView = New DataView(Me.ds.Tables(0))
        dv.RowFilter = GetFilter()

        '-- add columns for report
        addGVcolumn("Employee Name", "EmployeeName", gvexport, -1, HorizontalAlign.Left)
        addGVcolumn("Employee ID", "SID", gvexport, -1, HorizontalAlign.Left)
        addGVcolumn("Email", "WorkEmail", gvexport, -1, HorizontalAlign.Left)
        addGVcolumn("StatusID", "StatusID", gvexport, 50, HorizontalAlign.Center)

        gvexport.DataSource = dv
        gvexport.DataBind()

        gvexport.RenderControl(htmlWriter)

        Response.Output.Write(strWriter.ToString())

        Response.Flush()
        Response.End()

同样,我能够生成内容,但无法将我的数据导出为ex​​cel。非常感谢!

1 个答案:

答案 0 :(得分:0)

你给出了错误的标题:

.AddHeader "content-disposition", "attachment; filename="& filename &";"