尝试将asp.net gridview导出到.csv文件

时间:2014-01-02 19:54:49

标签: asp.net vb.net csv gridview

我正在尝试将gridview导出到csv文件,但我的代码似乎只是导出标题。

这是我的代码:

Protected Sub btnCSV_Click(sender As Object, e As EventArgs) Handles btnCSV.Click
    Response.Clear()
    Response.Buffer = True
    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv")
    Response.Charset = ""
    Response.ContentType = "application/text"

    gvReports.AllowPaging = False
    gvReports.DataBind()

    Dim sb As New StringBuilder()
    For k As Integer = 0 To gvReports.Columns.Count - 1
        'add separator
        sb.Append(gvReports.Columns(k).HeaderText + ","c)
    Next
    'append new line
    sb.Append(vbCr & vbLf)
    For i As Integer = 0 To gvReports.Rows.Count - 1
        For k As Integer = 0 To gvReports.Columns.Count - 1
            'add separator
            sb.Append(gvReports.Rows(i).Cells(k).Text + ","c)
        Next
        'append new line
        sb.Append(vbCr & vbLf)
    Next
    Response.Output.Write(sb.ToString())
    Response.Flush()
    Response.End()
End Sub

单击“导出到CSV”按钮后,我只获得一行数据(即gridview的标题行)。我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

我找到了解决方案!!评论

     gvReports.AllowPaging = False
     gvReports.DataBind()

答案 1 :(得分:-1)

到位

gvReports.DataBind() 

通话功能

me.binddata() 

可以将数据加载到gridview。 binddata是函数名称