Thursday, May 13, 2010

How to DataTable export to Excel in asp.net

It is a very common question is asp.net forum and other forum that how to export DataTable to excel in asp.net.
There are various ways to export data to excel, such as:

    1.    Write As XML with .XLS extensions
    2.    Render DataTable as Excel
    3.    Uisng HtmlForm object
    4.    Using VerifyRenderingInServerForm

Insha Allah, I will discuss all these export types gradually. Today I want to discuss here how to export DataTable to Excel. Its very simple ,I write down a method here just call it ana pass your DataTable as a parameter then this method generate a Excel file for you.

Code:
 public void ExportDataTable(DataTable dt)
        {
            string attachment = "attachment; filename=" + FileName.xls + "";
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader("content-disposition", attachment);
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            string sTab = "";
            foreach (DataColumn dc in dt.Columns)
            {
                HttpContext.Current.Response.Write(sTab + dc.ColumnName);
                sTab = "\t";
            }
            HttpContext.Current.Response.Write("\n");

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

2 comments:

Naresh Singh Dhami said...

Yes indeed very nice article. Many many thanks for this.

Naresh Singh Dhami said...

Yes indeed very nice article. Many many thanks for this.

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...