i want to export in excel file on button click on web page. please help me.

this is my datatable:

            DataTable dt = new DataTable("Student");
            dt.Columns.Add("StudentId", typeof(Int32));
            dt.Columns.Add("StudentName", typeof(string));
            dt.Columns.Add("Address", typeof(string));
            dt.Columns.Add("MobileNo", typeof(string));
            //Data 
            dt.Rows.Add(1, "Abishek", "Hyderabad", "0000000000");
            dt.Rows.Add(2, "Pawan", "Hyderabad", "111111111");
            dt.Rows.Add(3, "Namit", "Pune", "1222222222");
            dt.Rows.Add(4, "Neha", "Bhagalpur", "3333333333");

1 Answers

  1. Aditya Kumar Patel
    export datatable to excel file in asp.net
    8/2/2018 8:48:03 PM

    Try to use this.

    Write the following code on your button click event:

     

        protected void btnConvertDatatableToList_Click(object sender, EventArgs e)
            {               
                DataTable dt = new DataTable("Student");
                dt.Columns.Add("StudentId", typeof(Int32));
                dt.Columns.Add("StudentName", typeof(string));
                dt.Columns.Add("Address", typeof(string));
                dt.Columns.Add("MobileNo", typeof(string));
                //Data 
                dt.Rows.Add(1, "Abishek", "Hyderabad", "0000000000");
                dt.Rows.Add(2, "Pawan", "Hyderabad", "111111111");
                dt.Rows.Add(3, "Namit", "Pune", "1222222222");
                dt.Rows.Add(4, "Neha", "Bhagalpur", "3333333333"); 
     
                Response.Clear();
                Response.ClearContent();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=ExcelFile.xls");
     
                //Create a dynamic control, populate and render it
                GridView excel = new GridView();
                excel.DataSource = dt;
                excel.DataBind();
                excel.RenderControl(new HtmlTextWriter(Response.Output)); 
                Response.Flush();
                Response.End(); 
            }

    I hope it will help to you.


Leave a answer

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like