Wednesday, February 6, 2013

VB.NET CSV Export for Custom Class


'WRITE A CSV FOR A LIST OF CUSTOM CLASS

        'Declare your customclass and customclass list and set the value of the list
        Dim reasonowed As ReasonOwedClass = New ReasonOwedClass
        Dim reasonowedlist As List(Of ReasonOwedClass) = New List(Of ReasonOwedClass)
        reasonowedlist = reasonowed.GetAllReasonOwed()

        'Configure the page to export a csv file
        Dim attachment As String = "attachment; filename=MyCsvLol.csv"
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.ContentType = "text/csv"
        HttpContext.Current.Response.AddHeader("Content-Disposition", attachment)

        'Create what you will add your information to
        Dim sb As StringBuilder = New StringBuilder()

        'Optionally declare the property names
        'Since this will be for a mail merge, column names will be customized
        'So this block will likely be useless
        For Each field As System.Reflection.PropertyInfo In reasonowed.GetType.GetProperties()
            sb.Append(field.Name.ToString + ",")
        Next
        sb.Replace(",", vbNewLine, sb.Length - 1, 1)

        'Loop through the properties in the class and add them to the stringbuilder
        'If an item is intentionally left blank, you should make sure not to add to stringbuilder
        For Each reasonowedinlist As ReasonOwedClass In reasonowedlist
            For Each field As System.Reflection.PropertyInfo In reasonowedinlist.GetType.GetProperties()
                sb.Append(field.GetValue(reasonowedinlist).ToString + ",")
            Next
            sb.Replace(",", vbNewLine, sb.Length - 1, 1)
        Next

        'Write the file using the stringbuilder information you have been appending
        HttpContext.Current.Response.Write(sb.ToString())
        HttpContext.Current.Response.End()