0

我在 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 -->
4

1 回答 1

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
于 2013-03-29T22:59:43.760 回答