Friday, January 7, 2011

Export Datatable to Excel using Asp.Net

Exporting Data's from datatable or dataset to Excel sheet is very simple . please the see the sample code below


/// <summary>
        /// Exporting Data from DataTable to Excel file
        /// </summary>
        /// <param name="dt">Datatable which contian the data</param>
        /// <param name="filename">File name to store the data</param>
        public void ExporttoExcel(DataTable dt, string filename)
        {
            string attachment = "attachment;filname=User.xls";
            Response.ClearContent();
            Response.AddHeader("content-Disposition", attachment);
            Response.ContentType = "application/vnd.ms-excel";
            string tab = "";

            foreach (DataColumn dc in dt.Columns)
            {
                Response.Write(tab + dc.ColumnName);
                tab = "\t";
            }

            Response.Write("\n");
            foreach (DataRow dr in dt.Rows)
            {
                tab = "";
                for (int i = 0; i < dt.Columns.Count; i++) 
                {
                    Response.Write(tab + dr[i].ToString());
                    tab = "\t";
                }
                Response.Write("\n");
            }
            Response.End();
        }


Thanks for reading this article

No comments:

Post a Comment