如何从Visual Basic中的GridView构建CSV文件?

时间:2013-03-29 20:24:03

标签: vb.net gridview csv

我有一个报告,我在VB.Net中生成,正在GridView中显示。数据是根据用户输入的一些约束从SQL中提取的,可以是任何大小,具体取决于这些。我希望能够从网格中获取这些值,并将它们放入CSV中以获取可下载的报告,而无需重新运行我的SQL选择(我知道如何以这种方式构建),最好是以通用的方式,这样可以很容易地重用。 这就是我目前所拥有的。它创建一个CSV,但只有标题存在。

Protected Sub btnExcel_Click(sender As Object, e As EventArgs) Handles btnExcel.Click
    Dim strOutput As New StringBuilder

    Response.ContentType = "application/csv"
    ' Remove the charset from the Content-Type header.
    Response.Charset = ""
    ' Turn off the view state.
    Me.EnableViewState = False
    Response.AddHeader("Content-Disposition", "filename=report.csv;")

    strOutput.AppendLine(GetCSVLine(grid.HeaderRow.Cells))
    For Each row As GridViewRow In grid.Rows
        strOutput.AppendLine(GetCSVLine(row.Cells))
    Next


    Response.Write(strOutput)

    Response.Flush()

    Response.End()
End Sub

Private Function GetCSVLine(cells As TableCellCollection) As String
    Dim returnValue As String = ""

    For Each cell As TableCell In cells
        returnValue += cell.Text + ","
    Next

    Return returnValue
End Function

和aspx页面

    <asp:GridView ID="grid" runat="server" EnableModelValidation="True" AutoGenerateColumns = "false">
                    <Columns>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="lblName" runat="server" Text='<%# Bind("Name")%>'/>&nbsp;
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Location">
                            <ItemTemplate>
                                <asp:Label ID="lblLocation" runat="server" Text='<%# Bind("Location")%>'/>&nbsp;
                            </ItemTemplate>
                        </asp:TemplateField>
<!-- There are a few more fields after this, using the same structure -->

1 个答案:

答案 0 :(得分:0)

抱歉,在这里跑了我的头脑,但我认为因为每行包含一组Label控件,其中包含文本,所以你不能使用直线cell.Text反对表格单元格以获取内容。

您可能需要对每行使用FindControl方法来获取相关控件,然后访问您检索的每个控件的属性以获取您需要在其中推出的数据。 CSV。类似的东西:

For Each row As GridViewRow In grid.Rows
    'In each row, find the control which contains the data and then get the text of the control
    Dim nameLabel As Label = CType(row.FindControl("lblName"), Label)
    Dim nameValue As String = nameLabel.Text

    'Once you have all the values, write out the StringBuilder like you are doing already
Next