Want to work with us? We're on the lookout for digital experts.

We're hiring

Export DataTable To CSV

Web Bureau

17 December 2010 by Web Bureau

A common task that developers often encounter is exporting data to a csv file. The below code takes any datatable passed into it along with a filename and exports the datatable to csv.

Public Shared Function Export_CSV(ByVal dt As DataTable, ByVal Filename As String) As String

        Dim message As String = Nothing

            Dim context As HttpContext = HttpContext.Current

            For Each column As DataColumn In dt.Columns
                context.Response.Write(column.ColumnName + ",")


            For Each row As DataRow In dt.Rows

                For i As Integer = 0 To dt.Columns.Count - 1
                    context.Response.Write(row(i).ToString.Replace(",", String.Empty) + ",")



            context.Response.ContentType = "txt/csv"
            context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + Filename + ".csv")

            message = "Export Successful"

        Catch ex As Exception

            message = ex.Message.ToString

        End Try

        Return message

    End Function

Grow your businessStart a project with us today.

This site uses essential cookies for parts of the site to operate and have already been set. Find out more about how we use cookies and how you may delete them. You may delete cookies, but parts of the site will not work.