I was digging through my files when I found this subroutine and I thought, maybe somebody out there might need it. It’s not my original code though (and I forgot where I got it). Anyhow, I just wanted to share it and here it is:

Public Sub ExportToExcel()

Dim table as Datatable = “Query your datatable here”
Dim name as String  = “filename”

Dim context As HttpContext = HttpContext.Current
context.Response.Clear()
For Each column As DataColumn In table.Columns
context.Response.Write(column.ColumnName & “,”)
Next
context.Response.Write(Environment.NewLine)
For Each row As DataRow In table.Rows
For i As Integer = 0 To table.Columns.Count - 1
context.Response.Write(row(i).ToString().Replace(”,”, String.Empty) & “,”)
Next
context.Response.Write(Environment.NewLine)
Next
context.Response.ContentType = “text/csv”
context.Response.AppendHeader(”Content-Disposition”, “attachment; filename=” & name & “.csv”)
context.Response.[End]()

LoadData_Base()
End Sub

Tags: