GridView に表示されている VB.Net で生成しているレポートがあります。データは、ユーザーが入力したいくつかの制約に基づいて SQL から取得され、これらに応じて任意のサイズにすることができます。これらの値をグリッドから取得し、SQL 選択を再実行せずにダウンロード可能なレポートの CSV に入れたい (その方法で構築する方法を知っている)、できれば一般的な方法で簡単に再利用できるようにしたい. これが私が現在持っているものです。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 -->