Monday, January 25, 2010

Simple way to export data to excel

Protected Sub ExportToExcel(ByVal MyDataSet As DataSet)
Dim sw As New StreamWriter(Server.MapPath("~/ProjectReport.csv"), False)
' First we will write the headers.
Dim dt As DataTable = MyDataSet.Tables(0)
Dim iColCount As Integer = dt.Columns.Count
For i As Integer = 0 To iColCount - 1
sw.Write(dt.Columns(i))
If i < iColCount - 1 Then
sw.Write(",")
End If
Next
sw.Write(sw.NewLine)
sw.Write(sw.NewLine)
' Now write all the rows.
For Each dr As DataRow In dt.Rows
For i As Integer = 0 To iColCount - 1
If Not Convert.IsDBNull(dr(i)) Then
sw.Write(dr(i).ToString())
End If
If i < iColCount - 1 Then
sw.Write(",")
End If

sw.Write(sw.NewLine)
Next
sw.Close()
System.Diagnostics.Process.Start(Server.MapPath("~/ProjectReport.csv"))
End Sub

No comments:

Post a Comment