我在 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")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%# Bind("Location")%>'/>
</ItemTemplate>
</asp:TemplateField>
<!-- There are a few more fields after this, using the same structure -->