Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

CSV File Exporter Class - .NET Framework, ASP.NET

RSS
Modified on Fri, Oct 17, 2014, 12:01 PM by Administrator Categorized as ASP·NET MVC, ASP·NET Web Forms, ·Net Framework
// Reference: http://stackoverflow.com/questions/2422212/simple-c-sharp-csv-excel-export-class

/*===========================================================================================
    * Sample Usage
     
    List<BusinessObject> myList = GetBusinessObjectList();
    var csv = new CsvExporter<BusinessObject>(myList);
    Response.Write(csv.Export());
     
    */

public class CsvExporter<T> where T : class
{
    public List<T> Objects;

    public CsvExporter(List<T> objects)
    {
        Objects = objects;
    }

    public string Export()
    {
        return Export(true);
    }

    public string Export(bool includeHeaderLine)
    {

        StringBuilder sb = new StringBuilder();
        //Get properties using reflection.
        IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();

        if (includeHeaderLine)
        {
            //add header line.
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                sb.Append(propertyInfo.Name).Append(",");
            }
            sb.Remove(sb.Length - 1, 1).AppendLine();
        }

        //add value for each property.
        foreach (T obj in Objects)
        {
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                sb.Append(MakeValueCsvFriendly(propertyInfo.GetValue(obj, null))).Append(",");
            }
            sb.Remove(sb.Length - 1, 1).AppendLine();
        }

        return sb.ToString();
    }

    //get the csv value for field.
    private string MakeValueCsvFriendly(object value)
    {
        if (value == null) return "";
        if (value is Nullable && ((INullable)value).IsNull) return "";

        if (value is DateTime)
        {
            if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
                return ((DateTime)value).ToString("yyyy-MM-dd");
            return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
        }
        string output = value.ToString();

        if (output.Contains(",") || output.Contains("\""))
            output = '"' + output.Replace("\"", "\"\"") + '"';

        return output;

    }
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.