DownLoad DataTable to CSV file
2: /// Export DataTable to CSV
4: /// <param name="searchResultsTable"></param>
5: /// <param name="filename"></param>
6: private void ExportsearchResultsTableToCSV(DataTable test, string filename)
9: //copy the structure of the data table
10: DataTable toExcel = test.Copy();
12: HttpContext context = HttpContext.Current;
14: //Loop through data table columns and output
15: foreach (DataColumn column in toExcel.Columns)
17: context.Response.Write(column.ColumnName + ",");
20: context.Response.Write(Environment.NewLine);
22: //Loop through rows and output
23: foreach (DataRow row in toExcel.Rows)
26: for (int i = 0; i < toExcel.Columns.Count; i++)
28: context.Response.Write(row[i].ToString().Replace(",", string.Empty) + ",");
32: context.Response.Write(Environment.NewLine);
36: //output the csv file
37: context.Response.ContentType = "text/csv";
38: context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");
39: context.Response.End();