Generate Excel Report on Button Click Asp.Net, C# MS SQL Server 2008

Bangalore:Hi friends In your web application development,most of the applications we need to show reports from our database. we can use many methods to produce excel reports. Sql Server reporting , Using Interop Library or using StringWriter etc.
Now we can go to our Application
Development Tools: Visual Studio 2010,SQL Server
Create an Empty Web Application under C# and add a Default Aspx page
and add a Button inside your form. Its simple thing so I am not providing code. and double click the button then onclick event will generate in your code behind .cs page.

write the following code inside your Button click event

 protected void btreport_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("Data Source=Tonz-PC; Integrated Security=true;  Initial Catalog=Search");
            DataGrid gdvExcel = new DataGrid();
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            con.Open();
            SqlCommand cmd = new SqlCommand("Select * from userdata", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            con.Close();
            hw.WriteLine("<b><u><font size='5'> Excel Reports</font></u></b><br/><br/>");
            if (ds.Tables[0].Rows.Count > 0)
            {
                gdvExcel.DataSource = ds;
                gdvExcel.HeaderStyle.Font.Bold = true;
                gdvExcel.DataBind();
                gdvExcel.RenderControl(hw);
            }
            else
            {
                hw.WriteLine("<b><font size='4'> No Data Avaialble </font></b><br/><br/>");
            }
            Response.Write(sw.ToString());
            Response.AddHeader("content-disposition", "attachment; filename=SampleReport.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.xls";
            this.EnableViewState = false;
            Response.End();
        }



Here we are using StringWriter and HtmlTextWriter  and we declared a Data Grid on Button click and we are fetching  all data from our table and bind it into our grid view, and using Response.Write we will write all the data into our Excel File .
Finally on Button click it will give you Excel Report.
Hope you have understood it. If you have any doubt please write to us.

0 comments: