Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Contents tagged with Export DataTable data to CSV file

  • DownLoad DataTable to CSV file

       1: /// <summary>
       2: /// Export DataTable to CSV
       3: /// </summary>
       4: /// <param name="searchResultsTable"></param>
       5: /// <param name="filename"></param>
       6: private void ExportsearchResultsTableToCSV(DataTable test, string filename)
       7: {
       8:         
       9: //copy the structure of the data table
      10: DataTable toExcel = test.Copy();
      11: //set http contex 
      12: HttpContext context = HttpContext.Current;
      13:  
      14: //Loop through data table columns and output
      15: foreach (DataColumn column in toExcel.Columns)
      16: {
      17: context.Response.Write(column.ColumnName + ",");
      18:             
      19: }
      20: context.Response.Write(Environment.NewLine);
      21:         
      22: //Loop through rows and output
      23: foreach (DataRow row in toExcel.Rows)
      24: {
      25:                 
      26: for (int i = 0; i < toExcel.Columns.Count; i++)
      27: {
      28: context.Response.Write(row[i].ToString().Replace(",", string.Empty) + ",");
      29:                 
      30: }
      31:             
      32: context.Response.Write(Environment.NewLine);
      33:            
      34: }
      35:  
      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();
      40: