Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • GridView to Excel

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 269
    Comment on it

    Hi Friends,

    Today i will tell you how to export data to excel from gridview in asp.net. For this firstly create a project in asp.net.Add a gridview control in aspx page from toolbox as shown below:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <style type="text/css">
    
            .TextAlign {
                text-align:center;
            }
    
        </style>
    
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" Height="220px" Width="440px">
                <RowStyle CssClass="TextAlign" />
            </asp:GridView>
    
        </div>
            <div>
                &nbsp;
            </div>
    
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Export To Excel" Width="163px" />
        </form>
    </body>
    </html><html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <style type="text/css">
    
            .TextAlign {
                text-align:center;
            }
    
        </style>
    
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" Height="220px" Width="440px">
                <RowStyle CssClass="TextAlign" />
            </asp:GridView>
    
        </div>
            <div>
                &nbsp;
            </div>
    
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Export To Excel" Width="163px" />
        </form>
    </body>
    </html>

    Now add the code from code behind as follows :-

        public void BindGridView()
            {
                try
                {
                    List<Student> objStudentList = GetStudentStaticData();
                    GridView1.DataSource = objStudentList;
                    GridView1.DataBind();
                }
                catch (Exception ex)
                {
                    //Log Exception 
                }
            }
            /// <summary>
            /// Static Data Function 
            /// You can get the dynamic data from database using SQL,LINQ etc.
            /// </summary>
            /// <returns></returns>
            private List<Student> GetStudentStaticData()
            {
                List<Student> objStudent = new List<Student>();
                objStudent.Add(new Student { StudentID = 1, StudentName = "John", CIty = "LA" });
                objStudent.Add(new Student { StudentID = 2, StudentName = "Sam", CIty = "WD" });
                objStudent.Add(new Student { StudentID = 3, StudentName = "Shane", CIty = "MH" });
                objStudent.Add(new Student { StudentID = 4, StudentName = "Kurt", CIty = "NY" });
                objStudent.Add(new Student { StudentID = 5, StudentName = "RVD", CIty = "NJ" });
                objStudent.Add(new Student { StudentID = 6, StudentName = "Booker", CIty = "LA" });
                objStudent.Add(new Student { StudentID = 7, StudentName = "Hilery", CIty = "MH" });
                objStudent.Add(new Student { StudentID = 8, StudentName = "Jorge", CIty = "FL" });
                objStudent.Add(new Student { StudentID = 9, StudentName = "Bill", CIty = "SL" });
                objStudent.Add(new Student { StudentID = 10, StudentName = "Angel", CIty = "PD" });
    
                return objStudent;
            }
    		
    		//This event will be fired for export to excel button
    		
            protected void Button1_Click(object sender, EventArgs e)
            {
                ExportToExcel();
            }
    
            protected void ExportToExcel()
            {
                try
                {
                    Response.Clear();
                    Response.Buffer = true;
                    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
                    Response.Charset = "";
                    Response.ContentType = "application/vnd.ms-excel";
    
                    using (StringWriter sw = new StringWriter())
                    {
    
                        HtmlTextWriter hw = new HtmlTextWriter(sw);
    
                        #region RenderGridView Under Form Tag
                        //We need to write this code because if you directly render control then 
                        //it will throw a exception of render the control under form tag.
    
                        Control parent = GridView1.Parent;
                        int GridIndex = 0;
                        if (parent != null)
                        {
                            GridIndex = parent.Controls.IndexOf(GridView1);
                            parent.Controls.Remove(GridView1);
                        }
    
                        if (parent != null)
                        {
                            parent.Controls.AddAt(GridIndex, GridView1);
                        }
    
                        GridView1.RenderControl(hw);
    
                        #endregion
    
                        //To Export all pages
                        GridView1.AllowPaging = false;
                        BindGridView();
    
                        //style to format numbers to string
                        Response.Output.Write(sw.ToString());
                        Response.Flush();
                        Response.End();
                    }
                }
                catch (Exception ex)
                {
                    //Log Exception               
                } 
            }

    Here i have created the Button1_Click event for the button i have used to Export data to excel.

    ExportToExcel() is the main function to export grid to excel.

    This will create the GridViewExport.xls file with all grid data in it.

    Thank you for reading.
    Happy Coding!!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: