Thursday, 14 September 2017

C# ASP.NET Convert DataTable to CSV and Download

StringBuilder sb = new StringBuilder();
DataTable dt = ds.Tables[0];

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));
}

Response.Clear();
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "inline;filename=export.csv");
Response.AddHeader("Content-Type", "application/Excel");
Response.ContentType = "text/csv";
Response.Write(sb);
Response.End();


No comments:

SQL: Generate a range of numbers

SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n FROM       (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),      (VALU...