Exporting Div Dynamic Content To Excel in C# - ASP.Net

Category > ASP.NET || Published on : Thursday, July 2, 2015 || Views: 7774 || Exporting Div Dynamic Content To Excel in C# - ASP.Net with example Exporting Div Dynamic Content To Excel


In this article, we are going to learn how to export a div's dynamic data into excel file in ASP.NET using C#

so lets start the coding for Exporting Div Dynamic Content To Excel in C# - ASP.Net with example

Step 1: Create a new website in Visual Studio 2010

Step 2: Add a new asp.net webpage with the following codes.In below codes we have added some control to achieve the target i.e. Exporting Div Dynamic Content To Excel in C# - ASP.Net

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to Exporting a Div to Excel in ASP.NET using C#</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        function ExportDIVtoExcel() {
            var html = '';

            html += $("#divAccord").html();
            html = $.trim(html);
            html = html.replace(/>/g, '&gt;');
            html = html.replace(/</g, '&lt;');

            $("input[id$='HdnValexceldata']").val(html);

        }
    </script>

    <style type="text/css">
        .accordianContainer {
            max-height: 350px;
            overflow: auto;
        }
        /*----------------Data Grid inside Pop up----------------------*/
        .CompApp_TableScroll {
            max-height: 255px;
            overflow: auto;
        }

        .CompApp_DataTable {
            border-collapse: collapse;
        }

            .CompApp_DataTable tr th {
                background-color: #dedede;
                color: #333333;
                padding: 5px;
                border: 1px solid #cccccc;
                font-family: Arial, Helvetica, sans-serif;
                font-size: 12px;
                font-weight: normal;
                white-space: nowrap;
            }

            .CompApp_DataTable tr:nth-child(2n+2) {
                background-color: #f3f4f5;
            }

            .CompApp_DataTable tr:nth-child(2n+1) td {
                background-color: #d6dadf;
                color: #454545;
            }

            .CompApp_DataTable tr td {
                padding: 5px;
                color: #454545;
                font-family: Arial, Helvetica, sans-serif;
                font-size: 12px;
                border: 1px solid #cccccc;
                /*text-align: justify;*/
                white-space: nowrap;
            }

        /*.CompApp_DataTable tr td:first-child {
                    text-align: center;
                    font-weight: bold;
                    
                }*/
        /*-------------------------*/
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <h4>Exporting Div Dynamic Content To Excel in C# - ASP.Net</h4>
        <div id="divAccord" class="accordianContainer" runat="server">
        </div>
        <br />
        <br />
        <asp:Button ID="btnExport" runat="server" Text="Export To Excel" OnClientClick="ExportDIVtoExcel();" OnClick="btnExport_Click" />
        <asp:HiddenField ID="HdnValexceldata" runat="server" />
    </form>
</body>
</html>

Step 3: Create App_Code folder in the solution then add a new class with filename "RepeaterTemplate.cs" with the following codes:-

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

/// <summary>
/// Summary description for RepeaterTemplate
/// </summary>
public class RepeaterTemplate : System.Web.UI.ITemplate
{
    ListItemType vTemplateItemType = ListItemType.Separator;

    public RepeaterTemplate(ListItemType pListItemType)
    {
        vTemplateItemType = pListItemType;
    }

    public void InstantiateIn(System.Web.UI.Control container)
    {
        Literal lc = new Literal();
        //lc.Text = "Item number: " + itemcount.ToString() + "<BR>";            
        switch (vTemplateItemType)
        {
            // if condition to add HeaderTemplate Dynamically only Once  
            case ListItemType.Header:
                lc.Text = "<div class='CompApp_TableScroll'><table class='CompApp_DataTable' width='75%'>";

                lc.Text += "<tr>";
                lc.Text += "<td>";
                lc.Text += "<u>EmpID</u>";
                lc.Text += "</td>";

                lc.Text += "<td>";
                lc.Text += "<u>Name</u>";
                lc.Text += "</td>";

                lc.Text += "<td>";
                lc.Text += "<u>Address</u>";
                lc.Text += "</td>";

                lc.Text += "</tr>";


                break;

            // if condition to add FooterTemplate Dynamically only Once  
            case ListItemType.Footer:
                lc.Text = "</table></br>Footer Text ..</div>";
                break;

            case ListItemType.Item:
                ; break;
        }


        lc.DataBinding += new EventHandler(lc_DataBinding);
        container.Controls.Add(lc);
    }

    private void lc_DataBinding(object sender, EventArgs e)
    {
        Literal vLiteral = (Literal)sender;
        RepeaterItem vContainer = (RepeaterItem)vLiteral.NamingContainer;
        DataRowView row = (DataRowView)vContainer.DataItem;

        if (row != null)
        {
            vLiteral.Text += "<tr>";

            for (int i = 0; i < row.DataView.Table.Columns.Count; i++)
            {
                vLiteral.Text += "<td>" + row[i].ToString() + "</td>";
            }

            vLiteral.Text += "</tr>";
        }
    }
}

Step 4: Write the following codes in the code behind of the default.aspx page.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindRepeater();

        }
    }

    private void BindRepeater()
    {
        try
        {
            Repeater rContainer = null;

            DataTable dt = new DataTable();
            dt.Columns.Add("EmpId", typeof(int));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Address", typeof(string));


            dt.Rows.Add(25, "Raj", "Gurgaon");
            dt.Rows.Add(50, "Rahul", "Delhi");
            dt.Rows.Add(10, "Raja", "Delhi");
            dt.Rows.Add(21, "Amit", "Banglore");
            dt.Rows.Add(100, "Meena", "Banglore");

            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            if (dt.Rows.Count > 0)
            {
                rContainer = new Repeater();
                rContainer.DataSource = dt;
                rContainer.DataBind();

                foreach (DataTable dtCluster in ds.Tables)
                {
                    rContainer = new Repeater();

                    rContainer.ItemTemplate = new RepeaterTemplate(ListItemType.Item);
                    rContainer.HeaderTemplate = new RepeaterTemplate(ListItemType.Header);
                    rContainer.FooterTemplate = new RepeaterTemplate(ListItemType.Footer);

                    rContainer.DataSource = dtCluster;
                    divAccord.Controls.Add(rContainer);

                    this.DataBind();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected void btnExport_Click(object sender, EventArgs e)
    {
        try
        {
            string html = HdnValexceldata.Value;

            html = html.Replace("&gt;", ">");
            html = html.Replace("&lt;", "<");

            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=DemoExcelFile_" + DateTime.Now.ToString("M_dd_yyyy_H_M_s") + ".xls");
            HttpContext.Current.Response.ContentType = "application/xls";
            HttpContext.Current.Response.Write(html);
            HttpContext.Current.Response.End();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

so, In this tutorial we have learned how to Exporting Div Dynamic Content To Excel in C# - ASP.Net with example.  Happy coding!!!