Export Selected Data From GridView In Excel In ASP.NET Using C#

Initial chamber

Step 1: Open Visual Studio 2010 and create an empty website Give a suitable name: gridviewexcel_demo.

Step 2: In Solution Explorer you will get your empty website, then add a Web Form and SQL Server Database. By going like the following:

For Web Form

gridviewexcel_demo (Your Empty Website) - Right Click, Add New Item, then Web Form. Name it gridviewexcel_demo.aspx.

For SQL Server Database:

gridviewexcel_demo (Your Empty Website) - Right Click, Add New Item, then SQL Server Database. Add Database inside the App_Data_folder.

Database chamber


Step 3: In Server Explorer, click on your Database Database.mdf - Tables, Add New Table and make a table like the following:

Table - tbl_data  (Don’t Forget to make ID as IS Identity - True)

table

Design chamber

Step 4: Now make some design for your application by going to gridviewexcel_demo.aspx and try the following code snippet:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" EnableEventValidation = "false"  Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.       
  13.         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"   
  14.             CellPadding="4" ForeColor="#333333" GridLines="None">  
  15.             <AlternatingRowStyle BackColor="White" />  
  16.             <Columns>  
  17.   
  18.             <asp:TemplateField>  
  19.               
  20.             <ItemTemplate>  
  21.               
  22.          
  23.                     <asp:CheckBox ID="Checkbox1"  runat="server" />  
  24.                     </ItemTemplate>  
  25.               
  26.             
  27.               
  28.               
  29.             </asp:TemplateField>  
  30.   
  31.                  
  32.                 <asp:TemplateField HeaderText="ID">  
  33.                     <EditItemTemplate>  
  34.                         <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("id") %>'></asp:TextBox>  
  35.                     </EditItemTemplate>  
  36.                     <ItemTemplate>  
  37.                         <asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>'></asp:Label>  
  38.                     </ItemTemplate>  
  39.                 </asp:TemplateField>  
  40.                 <asp:TemplateField HeaderText="Name">  
  41.                     <EditItemTemplate>  
  42.                         <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>  
  43.                     </EditItemTemplate>  
  44.                     <ItemTemplate>  
  45.                         <asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>  
  46.                     </ItemTemplate>  
  47.                 </asp:TemplateField>  
  48.                 <asp:TemplateField HeaderText="City">  
  49.                     <EditItemTemplate>  
  50.                         <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("city") %>'></asp:TextBox>  
  51.                     </EditItemTemplate>  
  52.                     <ItemTemplate>  
  53.                         <asp:Label ID="Label3" runat="server" Text='<%# Bind("city") %>'></asp:Label>  
  54.                     </ItemTemplate>  
  55.   
  56.                       
  57.                 </asp:TemplateField>  
  58.             </Columns>  
  59.             <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />  
  60.             <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />  
  61.             <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />  
  62.             <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />  
  63.             <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />  
  64.             <SortedAscendingCellStyle BackColor="#FDF5AC" />  
  65.             <SortedAscendingHeaderStyle BackColor="#4D0000" />  
  66.             <SortedDescendingCellStyle BackColor="#FCF6C0" />  
  67.             <SortedDescendingHeaderStyle BackColor="#820000" />  
  68.         </asp:GridView>  
  69.       
  70.         <br />  
  71.       
  72.     </div>  
  73.     <asp:Button ID="Button1" runat="server" onclick="Button1_Click"   
  74.         Text="Export to Excel" />  
  75.     </form>  
  76. </body>  
  77. </html>  
You’re design looks like the following code snippet:

design

Code chamber

Before this coding part you need to download iTextsharp library from the souceforge website, here is the link just download the file, the file is in zip format, so just unzipped the files at suitable location, so that we can easily browse.

Itextsharp Library download - - itextsharp-all-5.5.6

Itextsharp Library

After you download the file, please check that you download the right file or not. Here's an image:

download the file

Step 5: Now it’s time for server side coding so that our application gets  working.  Open your gridviewexcel_demo.aspx.cs file and code it like the following.

Firstly, import the dll of ItextSharp by going to your empty website gridviewexcel_demo. Right click and Add References.

empty website

Now browse the ItextSharp unzip file and open it. Make sure you got all unzip dll files into your application. See the following image to know what .dll you have to import.

add reference

Now import these namespaces, since it will be needed when we write the code for exporting the GridView to excel.

namespace
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. using System.IO;  
  10. using System.Text;  
  11. using iTextSharp.text;  
  12. using iTextSharp.text.html;  
  13. using iTextSharp.text.html.simpleparser;  
  14. using iTextSharp.text.pdf;  
  15.   
  16.   
  17. public partial class _Default : System.Web.UI.Page  
  18. {  
  19.     protected void Page_Load(object sender, EventArgs e)  
  20.     {  
  21.         if (!Page.IsPostBack)  
  22.         {  
  23.             refreshdata();  
  24.         }  
  25.     }  
  26.   
  27.     public void refreshdata()  
  28.     {  
  29.   
  30.         SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");  
  31.         SqlCommand cmd = new SqlCommand("select * from tbl_data", con);  
  32.         SqlDataAdapter sda = new SqlDataAdapter(cmd);  
  33.         DataTable dt = new DataTable();  
  34.         sda.Fill(dt);  
  35.         GridView1.DataSource = dt;  
  36.         GridView1.DataBind();  
  37.          
  38.       
  39.       
  40.     }  
  41.     protected void Button1_Click(object sender, EventArgs e)  
  42.     {  
  43.         bool isselected = false;  
  44.   
  45.         foreach (GridViewRow gvrow in GridView1.Rows)  
  46.         {  
  47.             CheckBox chck = gvrow.FindControl("Checkbox1"as CheckBox;  
  48.             if (chck != null && chck.Checked)  
  49.             {  
  50.                 isselected = true;  
  51.                 break;  
  52.             }  
  53.         }  
  54.         if (isselected)  
  55.         {  
  56.             GridView grdxport = GridView1;  
  57.   
  58.             grdxport.Columns[0].Visible = false;  
  59.             foreach (GridViewRow gvrow in GridView1.Rows)  
  60.             {  
  61.                 grdxport.Rows[gvrow.RowIndex].Visible = false;  
  62.                 CheckBox chck = gvrow.FindControl("Checkbox1"as CheckBox;  
  63.                 if (chck != null && chck.Checked)  
  64.                 {  
  65.                     grdxport.Rows[gvrow.RowIndex].Visible = true;  
  66.                 }  
  67.             }  
  68.   
  69.             Response.Clear();  
  70.             Response.Buffer = true;  
  71.             Response.AddHeader("content-disposition""attachment;filename=GridViewExport.xls");  
  72.             Response.Charset = "";  
  73.   
  74.             Response.ContentType = "application/vnd.ms-excel";  
  75.   
  76.   
  77.             StringWriter swr = new StringWriter();  
  78.             HtmlTextWriter htmlwtr = new HtmlTextWriter(swr);  
  79.             grdxport.RenderControl(htmlwtr);  
  80.             Response.Output.Write(swr.ToString());  
  81.             Response.End();  
  82.   
  83.         }  
  84.   
  85.     }  
  86.   
  87.         public override void VerifyRenderingInServerForm(Control control)  
  88.         {  
  89.   
  90.         }  
  91.     }  
Output chamber

Excel Sheet
In Excel Sheet:

Output