;

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

Related Post


Warning: require(commentics/upload/frontend/index.php): Failed to open stream: No such file or directory in /home/u724888740/domains/knowforgrow.com/public_html/comments.php on line 24

Fatal error: Uncaught Error: Failed opening required 'commentics/upload/frontend/index.php' (include_path='.:/opt/alt/php82/usr/share/pear:/opt/alt/php82/usr/share/php:/usr/share/pear:/usr/share/php') in /home/u724888740/domains/knowforgrow.com/public_html/comments.php:24 Stack trace: #0 /home/u724888740/domains/knowforgrow.com/public_html/related_posts.php(51): include() #1 /home/u724888740/domains/knowforgrow.com/public_html/export_datatable_csv.php(67): include('/home/u72488874...') #2 {main} thrown in /home/u724888740/domains/knowforgrow.com/public_html/comments.php on line 24