Menu

Want to work with us? We're on the lookout for a UX/UI Designer and Digital Project Manager.

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

        Try
            Dim context As HttpContext = HttpContext.Current
            context.Response.Clear()

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

            context.Response.Write(Environment.NewLine)

            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) + ",")
                Next

                context.Response.Write(Environment.NewLine)

            Next

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

            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.