Showing posts with label Export to Excel file. Show all posts
Showing posts with label Export to Excel file. Show all posts

Tuesday, February 12, 2013

Export DataTable to Excel and Download file



public void ExportToSpreadsheet(DataTable table, string name)

{

var resp = Response;

resp.Clear();

foreach (DataColumn column in table.Columns)
{
   resp.Write(column.ColumnName + ",");
}

resp.Write(Environment.NewLine);

foreach (DataRow row in table.Rows)

{

for (int i = 0; i < table.Columns.Count; i++)
{
   resp.Write(row[i].ToString().Replace(",", string.Empty) + ",");
}

resp.Write(Environment.NewLine);

}

resp.ContentType = "text/csv";

resp.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");

resp.End();

}

}