How to Export Data to Excel from a DataSet

  1. protected void btntoExcel_Click(object sender, EventArgs e)  
  2. {  
  3.     ds = rs.onemindelayeduser("selectall", 0, """""""""""");  
  4.     if (ds != null)  
  5.     {  
  6.         if (ds.Tables[0].Rows.Count > 0)  
  7.         {  
  8.             DataTable dt = ds.Tables[0];  
  9.             dt.Columns.Remove("srno");  
  10.             string attachment = "attachment; filename=users.xls";  
  11.             Response.ClearContent();  
  12.             Response.AddHeader("content-disposition", attachment);  
  13.             Response.ContentType = "application/vnd.ms-excel";  
  14.             string tab = "";  
  15.             foreach (DataColumn dc in dt.Columns)  
  16.             {  
  17.                 Response.Write(tab + dc.ColumnName);  
  18.                 tab = "\t";  
  19.             }  
  20.             Response.Write("\n");  
  21.             int i;  
  22.             foreach (DataRow dr in dt.Rows)  
  23.             {  
  24.                 tab = "";  
  25.                 for (i = 0; i < dt.Columns.Count; i++)  
  26.                 {  
  27.                     Response.Write(tab + dr[i].ToString());  
  28.                     tab = "\t";  
  29.                 }  
  30.                 Response.Write("\n");  
  31.             }  
  32.             Response.End();  
  33.         }  
  34.     }  
  35. }