zimcoder Level: VB Lord

 Registered: 27-10-2003 Posts: 225
|
Re: how to export the content of datagrid to excel file in asp.net
You can Export the data into CSV format that will allow excel to read it as an excel document. The method below
Get the data from the datasource of the datagrid rather than from the datagrid itself
Private Sub btnexport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnexport.Click
Dim sw As StreamWriter = New StreamWriter(ConfigurationSettings.AppSettings("reportspath") & "\myexcel.csv", False)
Dim dataset As DataSet
Dim dt As DataTable
Dim dr As DataRow
Dim i, j As Integer
'Use a function to get data from datasource and bind to 'datagrid-- GetData()
dataset =GetData()
dt = dataset.Tables(0)
Dim iColCount As Integer = dt.Columns.Count
sw.WriteLine("My excel output")
sw.WriteLine()
' Writing the headers.
For i = 0 To iColCount - 1
sw.Write(dt.Columns(i))
If i < iColCount - 1 Then
sw.Write(",")
End If
Next
sw.Write(sw.NewLine)
' Now write all the rows.
For Each dr In dt.Rows
For j = 0 To iColCount - 1
If Not Convert.IsDBNull(dr(j)) Then
sw.Write(dr(j).ToString())
End If
If j < iColCount - 1 Then
sw.Write(",")
End If
Next
sw.Write(sw.NewLine)
Next
sw.Close()End Sub |
Give the appropriate confirmation and you are done!
____________________________
BrainBench ADO.NET and ASP.NET Certified Developer
 
|