Friday, 10 February 2012

How to Export Gridview contents into Excel in ASP.NET

Add a Webform to your project.Then Add a Gridview control and a Button control to the default.aspx page.
You can either use SQLDATASource Control from the toolbox to setup the connection to database and select the table you want to retrieve or you can use the ADO.NET way to establish the connection to the database and retrieve the table.
If you are using ADO.NET then this might be useful code for you



using System;using System.Data;using System.Data.SqlClient;

///
/// Demonstrates how to work with SqlConnection objects
///
class SqlConnectionDemo{static void Main(){
// 1. Instantiate the connection
SqlConnection conn = new SqlConnection(“Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI”);
//use “Trusted_Connection=true” if you are using Windows Authentication
SqlDataReader rdr = null;try{
// 2. Open the connection
conn.Open();
// 3. Pass the connection to a command object
SqlCommand cmd = new SqlCommand(“select * from Customers”, conn);
//
// 4. Use the connection
//
// get query results
rdr = cmd.ExecuteReader()
// print the CustomerID of each record
while (rdr.Read()){Console.WriteLine(rdr[0]);}}finally{
// close the reader
if (rdr != null){rdr.Close();}
// 5. Close the connection
if (conn != null){conn.Close();}}}}
After the establishiment to connection is succesfull then go the Button Click event and Write the following Code
protected void Button1_Click(object sender, EventArgs e){Response.Clear();Response.AddHeader(“content-disposition”, “attachment;filename=shippingreport.xls”);System.IO.StringWriter sw = new System.IO.StringWriter();HtmlTextWriter hm = new HtmlTextWriter(sw);GridView1.RenderControl(hm);Response.Write(sw.ToString());Response.End();}
If you run this code you will get an error that control Gridview must be placed inside a Form tag with runat=”server” attribute because we are rendering the gridview in html in our above code…..The easiest method For removing this error is override the renderingcontrol method in you code and comment its base bethod..the Code will be like this
public override void VerifyRenderingInServerForm(Control control){//base.VerifyRenderingInServerForm(control);}

Thats it,Your job is done.For generating the content in Word replace the .xls with .doc or .docx.

No comments:

Post a Comment