Skip to content

Instantly share code, notes, and snippets.

@arijusg
Created June 23, 2014 13:42
Show Gist options
  • Save arijusg/b54e22cf0689197dbe9e to your computer and use it in GitHub Desktop.
Save arijusg/b54e22cf0689197dbe9e to your computer and use it in GitHub Desktop.
DataTable convert into Csv and push to the browser
public class DataTableToCsv
{
public void Generate(DataTable dt, string fileName)
{
var sb = new StringBuilder();
IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field =>
string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
sb.AppendLine(string.Join(",", fields));
}
PushCsvToBrowser(sb, fileName);
}
private void PushCsvToBrowser(StringBuilder sb, string fileName)
{
string attachment = "attachment; filename=" + fileName;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.End();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment