Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Export GridView Data into CSVFile In Asp.net

Posted by Viral Sarvaiya on October 30, 2009

Steps.

1) Create Simple Web Application.

2) put the below control in to the page (.aspx)

2.1) GridView (id= GridView1)

2.2) Button (id=button1 and Text =Create CSV File)

3) assign data source to GridView

4) on the button_click event put the following code.


Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Try
'Create CSV file
Dim objSw As New StreamWriter(Server.MapPath("~/demo.csv"))
'get table from GridView1
Dim objDt As DataTable = DirectCast(GridView1.DataSource, DataSet).Tables(0)
'Get No Of Column in GridView
Dim NoOfColumn As Integer = objDt.Columns.Count
'Create Header
For i As Integer = 0 To NoOfColumn - 1
objSw.Write(objDt.Columns(i))
'check not last column
If i < NoOfColumn - 1 Then
objSw.Write(",")
End If
Next
objSw.Write(objSw.NewLine)
'Create Data
For Each dr As DataRow In objDt.Rows
For i As Integer = 0 To NoOfColumn - 1
objSw.Write(dr(i).ToString())

If i < NoOfColumn - 1 Then
objSw.Write(",")
End If
Next
objSw.Write(objSw.NewLine)
Next
objSw.Close()
Catch ex As Exception
Response.Write("Can Not Generate CSV File")
End Try
End Sub

Enjoy Coding….

Advertisements

2 Responses to “Export GridView Data into CSVFile In Asp.net”

  1. Thx for the infos.

  2. […] my past posts explains how to export to excel as 1. Export GridView Data into CSVFile In Asp.net 2. GridView Export to […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: