Sunday, 19 January 2014

Export DataTable to Excel

Simply use this method  by passing DataTable as First Parameter and also FileName in Second Paramter.

public static void ExportToSpreadsheet(DataTable table, string name)
{
   HttpContext context = HttpContext.Current;
   context.Response.Clear();
   foreach (DataColumn column in table.Columns)
   {
    context.Response.Write(column.ColumnName + ";");
   }
   context.Response.Write(Environment.NewLine);
   foreach (DataRow row in table.Rows)
   {
    for (int i = 0; i < table.Columns.Count; i++)
    {
     context.Response.Write(row[i].ToString().Replace(";", string.Empty) + ";");
    }
    context.Response.Write(Environment.NewLine);
   }
   context.Response.ContentType = "text/csv";
   context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
   context.Response.End();
}

Uses:-
DataTable DT=new DataTable();
DT=getData();  // set data in DataTable
ExportToSpreadsheet(DT,"FileName.xls");


Tag:-
export data table to excel,export excel from c#,

No comments:

Post a Comment