ASP.NET DataSet or DataTable to Excel
Post # 84 permalink Topic #84 by mreschke on 2008-07-16 15:23:11 (viewed 720 times)

Export a dataset or datatable to excel .csv then stream (prompt for download) the file.

Dataset or Datatable[-][- -][++]

This code uses a datatable, if you have a dataset, just convert to datatable like so

Code Snippet
Dim dt as new DataTable
dt = ds.Tables(0)

Export to .CSV file[-][- -][++]

Code Snippet
Dim sw As New System.IO.StreamWriter(Server.MapPath("~/data.csv"), false);
Dim ds As New DataSet
Dim dt As New DataTable
ds = Session("trkDsResults")
dt = ds.Tables(0)

Dim iCol As Int16 = dt.Columns.Count
Dim i As Int16

For i = 0 To iCol - 1
    sw.Write(dt.Columns(i))
    If i < iCol - 1 Then sw.Write(",")
Next
sw.Write(sw.NewLine)

For Each dr As DataRow In dt.Rows
    For i = 0 To iCol - 1
        If Not IsDBNull(dr(i)) Then
            sw.Write(dr(i).ToString)
            If i < iCol - 1 Then sw.Write(",")
        End If
    Next
    sw.Write(sw.NewLine)
Next
sw.Close()

Then you can call a nice stream function like so:
Code Snippet
Me.DownloadFile(Server.MapPath("~/", "data.csv"))

See ASP.NET Stream File

Resources[-][- -][++]