Code Simplified – Viral Sarvaiya

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

Posts Tagged ‘export gridview to csv’

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….

Posted in ASP.NET | Tagged: , , , , , | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 44 other followers

%d bloggers like this: