It seems like each time I need to do this in a project (that is create an Excel file from a GridView or SQL Query) I have to look for my little snippet on how to do this in a reusable manner.  Well here you go a nice Extension Method that will return CSV from any System.Data.DataTable.

public static String ToCSV(this DataTable dt)
{
    StringBuilder sb = new StringBuilder();

    for (int x = 0; x < dt.Columns.Count; x++)
    {
        if (x != 0)
            sb.Append(",");
        sb.Append(dt.Columns[x].ColumnName);
    }
    sb.AppendLine();
    foreach (DataRow row in dt.Rows)
    {
        for (int x = 0; x < dt.Columns.Count; x++)
        {
            if (x != 0)
                sb.Append(",");
            sb.Append(row[dt.Columns[x]].ToString());
        }

        sb.AppendLine();
    }
    return sb.ToString();
}
Submit this story to DotNetKicksShout it   Bookmark and Share