Friday, October 12, 2012

ASP.NET Export DataTable to excel using GridView controls

Hello this project will export DataTable to *.xls file for excel.
You can modify GridView style for display colorful format in excel.
Another project for display data in excel.
ASP.NET : Export DataTable to CSV
Two Step include sourcecode below.

Step 1 : Design ASPX HTML.
Add Export Button and GridView with colorful format for display in excel


        <asp:Button ID="btnExcel" runat="server" Text="Excel" />

        <br />

        <asp:GridView ID="gv1" runat="server" BackColor="White" BorderColor="#E7E7FF"

            BorderStyle="None" BorderWidth="1px" CellPadding="3"

            EnableModelValidation="True" GridLines="Horizontal">

            <AlternatingRowStyle BackColor="#F7F7F7" />

            <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />

            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />

            <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />

            <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />

            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />

        </asp:GridView>

Step 2 : Create method and call in Button_Click event in codebehind.

    Protected Sub btnExcel_Click(sender As Object, e As System.EventArgs) Handles btnExcel.Click
        ExportExcel2(TestData)
    End Sub

    Sub ExportExcel2(dt As DataTable)
        gv1.DataSource = TestData
        gv1.DataBind()
        Response.AddHeader("content-disposition", "attachment; filename=ExcelName.xls")
        Response.ContentType = "application/vnd.ms-excel"
        Response.Charset = "TIS-620"
        Me.EnableViewState = False
        Dim tw As New System.IO.StringWriter()
        Dim hw As New System.Web.UI.HtmlTextWriter(tw)
        Dim frm As HtmlForm = New HtmlForm()
        Me.Controls.Add(frm)
        frm.Controls.Add(gv1)
        frm.RenderControl(hw)
        Response.Write(tw.ToString())
        Response.End()
    End Sub

For export excel without format table please use method below

    Sub ExportExcel(dt As DataTable)
        Dim GV As New System.Web.UI.WebControls.GridView
        GV.DataSource = TestData
        GV.DataBind()
        Response.AddHeader("content-disposition", "attachment; filename=ExcelName.xls")
        Response.ContentType = "application/vnd.ms-excel"
        Response.Charset = "TIS-620"
        Me.EnableViewState = False
        Dim tw As New System.IO.StringWriter()
        Dim hw As New System.Web.UI.HtmlTextWriter(tw)
        Dim frm As HtmlForm = New HtmlForm()
        Me.Controls.Add(frm)
        frm.Controls.Add(GV)
        frm.RenderControl(hw)
        Response.Write(tw.ToString())
        Response.End()
    End Sub

Pls enjoy ZomDev

No comments:

Post a Comment