Created
June 23, 2014 13:42
-
-
Save arijusg/b54e22cf0689197dbe9e to your computer and use it in GitHub Desktop.
DataTable convert into Csv and push to the browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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