Export Data from datatable to csv in ASP.NET and C#
To export data from a datatable to csv file in ASP.NET using C# use the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
//export to CSV
public void ExportTOCSV(DataTable dt, string reportName)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AppendHeader("Content-Disposition",
string.Format("attachment; filename={0}", reportName));
StringBuilder sb = new StringBuilder();
string[] columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
sb.AppendLine(string.Join(",", columnNames));
HttpContext.Current.Response.Output.Write(sb.ToString());
foreach (DataRow row in dt.Rows)
{
sb = null;
sb = new StringBuilder();
IEnumerable<string> fields = row.ItemArray.Select(field =>
string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
string[] arr = fields.ToArray();
sb.AppendLine(string.Join(",", arr));
HttpContext.Current.Response.Output.Write(sb.ToString());
}
//File.WriteAllText("testReport.csv", sb.ToString());
//HttpContext.Current.Response.Output.Write(sb.ToString());
sb = null;
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
catch (Exception ex)
{
throw ex;
}
}
Comments
Post a Comment