Wednesday, 13 November 2013

EXPORT DATA IN EXCEL SHEET USING ASP.NET C#

  public static void ExportToExcel(DataTable dt, string fileName)
    {
        if (dt != null)
        {
            HttpContext cont = HttpContext.Current;
            cont.Response.Clear();

            string header = "attachment; filename=" + fileName + ".xls";
            cont.Response.AppendHeader("content-disposition", header);
            cont.Response.ContentType = "application/vnd.ms-excel";

            StringBuilder sb = new StringBuilder();

            // Render out an HTML table to pass into Excel
            sb.Append("<table cellpadding=2 cellspacing=2>");

            // Get all column names
            sb.Append("<tr>");

            foreach (DataColumn dc in dt.Columns)
            {
                sb.Append("<td>");

                sb.Append("<b>" + dc.ColumnName.Replace("_", " ") + "</b>");

                sb.Append("</td>");
            }

            sb.Append("</tr>");

            // Handle table rows and cells
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append("<tr>");

                foreach (DataColumn dc in dt.Columns)
                {
                    sb.Append("<td>");

                    sb.Append(dt.Rows[i][dc].ToString());

                    sb.Append("</td>");
                }

                sb.Append("</tr>");
            }

            // Close the table tag
            sb.Append("</table>");

            dt.Dispose();

            // Pass the table HTML string into the response output stream to be passed to Excel
            cont.Response.Write(sb.ToString());
            cont.Response.End();
            cont.Response.Clear();
        }
        else
        {
            throw new Exception("The data table cannot be null.");
        }
    }



U CAN CALL THIS METHOD LIKE BELOW IN PAGE LOAD

 ExportToExcel( dt,filename  );

No comments:

Post a Comment