There often is a need in a project's reporting module to show records of a GridView in an Excel sheet, so to do that I decided to write this article, especially focusing on beginners and those who want to learn how to export a GridView to Excel Using ASP.Net C#.
Now before creating the application, let us create a table named employee in a database with records for the GridView, the table has the following fields (shown in the following image):
I hope you have created the same type of table.
Now create the project as:
- "Start" - "All Programs" - "Microsoft Visual Studio 2010".
- "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
- Provide the Project name such as "ExportGridToExcel" or another as you wish and specify the location.
- Then right-click on the Solution Explorer and select "Add New Item" - "Default.aspx" page.
- Then add one button, one label and a GridView to the page.
private void Bindgrid() { connection(); //not recommended this i have written for example,write stored procedure for security query = "select *from Employee"; com = new SqlCommand(query, con); SqlDataReader dr = com.ExecuteReader(); GridView1.DataSource = dr; GridView1.DataBind(); con.Close(); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Bindgrid(); } }
Now, we have a record to export to Excel, let us start coding for our actual requirements. Add the VerifyRenderingInServerForm event after the page load that is required while exporting the GridView to Excel,Word and PDF formt to avoid the runtime error that occurrs, such as "GridView' must be placed inside a form tag with runat=server.".
public override void VerifyRenderingInServerForm(Control control) { //required to avoid the run time error " //Control 'GridView1' of type 'Grid View' must be placed inside a form tag with runat=server." }
private void ExportGridToExcel() { Response.Clear(); Response.Buffer = true; Response.ClearContent(); Response.ClearHeaders(); Response.Charset = ""; string FileName ="Vithal"+DateTime.Now+".xls"; StringWriter strwritter = new StringWriter(); HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType ="application/vnd.ms-excel"; Response.AddHeader("Content-Disposition","attachment;filename=" + FileName); GridView1.GridLines = GridLines.Both; GridView1.HeaderStyle.Font.Bold = true; GridView1.RenderControl(htmltextwrtter); Response.Write(strwritter.ToString()); Response.End(); }
protected void Button1_Click(object sender, EventArgs e) { ExportGridToExcel(); }
using System; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data.SqlClient; using System.IO; using System.Web; public partial class _Default : System.Web.UI.Page { private SqlConnection con; private SqlCommand com; private string constr,query; private void connection() { constr = ConfigurationManager.ConnectionStrings["getconn"].ToString(); con = new SqlConnection(constr); con.Open(); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Bindgrid(); } } public override void VerifyRenderingInServerForm(Control control) { //required to avoid the runtime error " //Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server." } private void Bindgrid() { connection(); query = "select *from Employee";//not recommended this i have wrtten just for example,write stored procedure for security com = new SqlCommand(query, con); SqlDataReader dr = com.ExecuteReader(); GridView1.DataSource = dr; GridView1.DataBind(); con.Close(); } protected void Button1_Click(object sender, EventArgs e) { ExportGridToExcel(); } private void ExportGridToExcel() { Response.Clear(); Response.Buffer = true; Response.ClearContent(); Response.ClearHeaders(); Response.Charset = ""; string FileName ="Vithal"+DateTime.Now+".xls"; StringWriter strwritter = new StringWriter(); HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType ="application/vnd.ms-excel"; Response.AddHeader("Content-Disposition","attachment;filename=" + FileName); GridView1.GridLines = GridLines.Both; GridView1.HeaderStyle.Font.Bold = true; GridView1.RenderControl(htmltextwrtter); Response.Write(strwritter.ToString()); Response.End(); } }
Now click on the "Open with" option, all the GridView records are exported into Excel as in the following:
Notes
- Change the connection string in the web.config file to specify your server location.
Summary
I hope this article is useful for all readers, if you have any suggestion then please contact me, including beginners.
Post a Comment