CodeKicks.com
Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Wednesday, October 11, 2006

ASP.NET function for Exporting Data to Excel

protected void Page_Load
       (object sender, EventArgs e)
{
       SqlConnection cn =
       new SqlConnection("yourconnectionstring");
       cn.Open();
       SqlDataAdapter da =
        new SqlDataAdapter("SELECT *
           FROM Users", cn);
       DataTable dt = new DataTable();
       da.Fill(dt);
       cn.Close();
       Response.Clear();
       Response.ContentType =
         "application/vnd.ms-excel";
       string sep = "";
       foreach (DataColumn dc in dt.Columns)
       {
              Response.Write(sep + dc.ColumnName);
              sep = "\t";
       }
       Response.Write("\n");
       int i;
       foreach (DataRow dr in dt.Rows)
       {
              sep = "";
              for (i = 0; i < dt.Columns.Count; i++)
              {
                     Response.Write(sep + dr[i].ToString());
                     sep = "\t";
              }
              Response.Write("\n");
       }
}

Post a Comment