Showing posts with label Export. Show all posts
Showing posts with label Export. Show all posts

Wednesday, May 15, 2013

How to export DataTable to Excel using C#

In this post we will be exporting the DataTable to an Excel using C#
Below is the method which will do the trick. Just pass the parameters datatable and the filename.

private void ExportDataTableToExcel(DataTable thetable, string fileName)
        {
            string attachment = "attachment; filename=" + fileName + ".xls";

            Response.ClearContent();

            Response.AddHeader("content-disposition", attachment);

            Response.ContentType = "application/vnd.ms-excel";

            //write columns from DataTable to Excel      
            string tab = "";
            foreach (DataColumn dc in thetable.Columns)
            {
                string title = string.Empty;
                if (dc.ColumnName.Contains("Meta"))
                    title = "Metadata Properties";
                else
                    title = dc.ColumnName;
                Response.Write(tab + title);
                tab = "\t";
            }
            Response.Write("\n");

            //write rows from DataTable to Excel  
            int i;
            foreach (DataRow dr in thetable.Rows)
            {
                tab = "";
                for (i = 0; i < thetable.Columns.Count; i++)
                {
                    Response.Write(tab + dr[i].ToString());
                    tab = "\t";
                }
                Response.Write("\n");
            }
            //To throw the excel file generated
            Response.End();

        }


Hope this helps...

Popular Posts