Protected Sub GridViewToCsv(SourceGridView As GridView, Optional DefaultClientCsvFilename As String = "Table.csv")
Dim SourceDataTable As Data.DataTable = SourceGridView.DataSource
If SourceDataTable Is Nothing Then
SourceDataTable = ViewState("SourceDataTable")
End If
If SourceDataTable IsNot Nothing Then
Dim CsvMemoryStream As New IO.MemoryStream
Dim CsvStreamWriter As New IO.StreamWriter(CsvMemoryStream)
Dim FieldsAndColumnHeadersDictionary As New Dictionary(Of String, String)
For Each SourceGridViewRow As GridViewRow In SourceGridView.Rows
If SourceGridViewRow.RowType = DataControlRowType.DataRow Then
For Each GridViewDataControlFieldCell As DataControlFieldCell In SourceGridViewRow.Cells
If TypeOf GridViewDataControlFieldCell.ContainingField Is BoundField Then
Dim GridViewBoundField As BoundField = GridViewDataControlFieldCell.ContainingField
If GridViewBoundField.Visible = True Then
Dim GridViewDataField As String = GridViewBoundField.DataField
Dim GridViewColumnHeaderText As String = GridViewBoundField.HeaderText
FieldsAndColumnHeadersDictionary.Add(GridViewDataField, ControlChars.Quote & GridViewColumnHeaderText.Replace(ControlChars.Quote, ControlChars.Quote & ControlChars.Quote) & ControlChars.Quote)
End If
End If
Next GridViewDataControlFieldCell
Exit For
End If
Next SourceGridViewRow
Dim JoinedColumns As String = Join(FieldsAndColumnHeadersDictionary.Values.ToArray, ",")
CsvStreamWriter.WriteLine(JoinedColumns)
For Each SourceDataRow As Data.DataRow In SourceDataTable.Rows
Dim DataList As New Generic.List(Of String)
For Each GridViewColumn As String In FieldsAndColumnHeadersDictionary.Keys
DataList.Add(ControlChars.Quote & SourceDataRow.Item(GridViewColumn).ToString.Replace(ControlChars.Quote, ControlChars.Quote & ControlChars.Quote) & ControlChars.Quote)
Next GridViewColumn
Dim JoinedData As String = Join(DataList.ToArray, ",")
CsvStreamWriter.WriteLine(JoinedData)
Next SourceDataRow
CsvStreamWriter.Flush()
Dim CsvStreamBytes() As Byte = CsvMemoryStream.ToArray
CsvMemoryStream.Close()
Response.Clear()
Response.ContentType = "application/force-download; charset=utf-8"
Response.AddHeader("content-disposition", "attachment; filename=" & DefaultClientCsvFilename)
Context.Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble())
Response.BinaryWrite(CsvStreamBytes)
Response.End()
End If
End Sub
Tips and tricks for .NET using ASP and VB code.
Give user a .CSV file from a GridView without writing file to server.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment