Gridview to CSV

  • Thread starter Thread starter Vincent
  • Start date Start date
V

Vincent

Hi, I use the following code to export to Excel, which works fine.

GVAPInv.AllowSorting = "False"
Gridvew1.DataBind()
Gridvew1.AllowSorting = "False"
Gridvew1.DataBind()
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Me.EnableViewState = False
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim frm As HtmlForm = New HtmlForm()
Me.Controls.Add(frm)
frm.Controls.Add(Gridvew1)
frm.RenderControl(hw)
Response.Write(tw.ToString())
Response.End()
Gridvew1.AllowSorting = "False"
Gridvew1.DataBind()

I'm having trouble figuring out how to export to a simple Csv file.
I've tried to change the response.contenttype to:

Response.ContentType = "text/csv"

This only generates html code (pasted sample below). Any help would be
appreciated. Thank you.
 
See if this thread helps: http://forums.asp.net/thread/1343504.aspx

Hi, I use the following code to export to Excel, which works fine.

GVAPInv.AllowSorting = "False"
Gridvew1.DataBind()
Gridvew1.AllowSorting = "False"
Gridvew1.DataBind()
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Me.EnableViewState = False
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim frm As HtmlForm = New HtmlForm()
Me.Controls.Add(frm)
frm.Controls.Add(Gridvew1)
frm.RenderControl(hw)
Response.Write(tw.ToString())
Response.End()
Gridvew1.AllowSorting = "False"
Gridvew1.DataBind()

I'm having trouble figuring out how to export to a simple Csv file.
I've tried to change the response.contenttype to:

Response.ContentType = "text/csv"

This only generates html code (pasted sample below). Any help would be
appreciated. Thank you.
 
Thanks that pointed me in the right direction and I've gotten this to
work...

Here's the code I used:

*******************************************
Dim objStreamWriter As IO.StreamWriter

'Pass the file path and the file name to the StreamWriter
constructor.
'make sure this is a path that you have permissions to save in

objStreamWriter = New
IO.StreamWriter("c:\myfiles\mycsvfile.csv")
'Write text.

Dim Str As String
Dim i As Integer
Dim j As Integer

Dim headertext =
"field1,field2,field3,field4,field5,field5,field6"
objStreamWriter.WriteLine(headertext)
For i = 0 To (Me.GridView2.Rows.Count - 1)
For j = 0 To (Me.GridView2.Columns.Count - 1)

'this IF statement stops it from adding a comma after
the last field
If j = (Me.GridView2.Columns.Count - 1) Then
Str = (Me.GridView2.Rows(i).Cells(j).Text.ToString)
Else
Str = (Me.GridView2.Rows(i).Cells(j).Text.ToString
& ",")
End If
objStreamWriter.Write(Str)
Next
objStreamWriter.WriteLine()
Next
'Close the file.
objStreamWriter.Close()

*******************************************************
 
Back
Top