Export Gridview to Excel Using ITextSharp Library

We use one grid view with a field, then we export that grid view to an Excel document using the ItextSharp library. This article is really very similar to my previous article were I explain how to export a grid view to a Word Document.

Initial Chamber

Step 1

Open Your Visual Studio 2010 and create an Empty Website, provide a suitable name ([gridviewexcel_demo)].

Step 2

In Solution Explorer you get your empty website, then add a Web Form and SQL Server Database as in the following.

For Web Form:

gridviewexcel_demo (your empty website) then right-click then select Add New Item -> Web Form. Name it gridviewexcel_demo.aspx.

For SQL Server Database:

gridviewexcel_demo (your empty website) then right-click then select Add New Item -> SQL Server database. (Add a database inside the App_Data_folder).

Database Chamber


Step 3

In Server Explorer, click on your database (Database.mdf) then select Tables -> Add New Table. Make the table like this:

Table -> tbl_data (Don't forget to make ID as IS Identity -- True).

Identity

Design Chamber

Step 4

Now make some design for your application by going to gridviewexcel_demo.aspx and try the code like this:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 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.       
  14.       
  15.         <asp:GridView ID="GridView1" runat="server" AllowPaging="True"   
  16.             AutoGenerateColumns="False" BackColor="White" BorderColor="#999999"   
  17.             BorderStyle="None" BorderWidth="1px" CellPadding="3" DataKeyNames="id"   
  18.             GridLines="Vertical" onpageindexchanging="GridView1_PageIndexChanging1"   
  19.             PageSize="5">  
  20.             <AlternatingRowStyle BackColor="#DCDCDC" />  
  21.             <Columns>  
  22.                 <asp:TemplateField HeaderText="Name">  
  23.                     <EditItemTemplate>  
  24.                         <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>  
  25.                     </EditItemTemplate>  
  26.                     <ItemTemplate>  
  27.                         <asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>  
  28.                     </ItemTemplate>  
  29.                 </asp:TemplateField>  
  30.                 <asp:TemplateField HeaderText="Education">  
  31.                     <EditItemTemplate>  
  32.                         <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("education") %>'></asp:TextBox>  
  33.                     </EditItemTemplate>  
  34.                     <ItemTemplate>  
  35.                         <asp:Label ID="Label2" runat="server" Text='<%# Bind("education") %>'></asp:Label>  
  36.                     </ItemTemplate>  
  37.                 </asp:TemplateField>  
  38.                 <asp:TemplateField HeaderText="Email">  
  39.                     <EditItemTemplate>  
  40.                         <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("email") %>'></asp:TextBox>  
  41.                     </EditItemTemplate>  
  42.                     <ItemTemplate>  
  43.                         <asp:Label ID="Label3" runat="server" Text='<%# Bind("email") %>'></asp:Label>  
  44.                     </ItemTemplate>  
  45.                 </asp:TemplateField>  
  46.                 <asp:TemplateField HeaderText="Location">  
  47.                     <EditItemTemplate>  
  48.                         <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("location") %>'></asp:TextBox>  
  49.                     </EditItemTemplate>  
  50.                     <ItemTemplate>  
  51.                         <asp:Label ID="Label4" runat="server" Text='<%# Bind("location") %>'></asp:Label>  
  52.                     </ItemTemplate>  
  53.                 </asp:TemplateField>  
  54.             </Columns>  
  55.             <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />  
  56.             <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />  
  57.             <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />  
  58.             <RowStyle BackColor="#EEEEEE" ForeColor="Black" />  
  59.             <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />  
  60.             <SortedAscendingCellStyle BackColor="#F1F1F1" />  
  61.             <SortedAscendingHeaderStyle BackColor="#0000A9" />  
  62.             <SortedDescendingCellStyle BackColor="#CAC9C9" />  
  63.             <SortedDescendingHeaderStyle BackColor="#000065" />  
  64.         </asp:GridView>  
  65.         <br />  
  66.         <br />  
  67.       
  68.       
  69.       
  70.     </div>  
  71.     <asp:Button ID="Button1" runat="server" onclick="Button1_Click1"   
  72.         Text="Export To PDF" />  
  73.     </form>  
  74. </body>  
  75. </html>  
Your design would look like this:

design

You can show paging by going to GridView properties (Press F4) then select Find -> Allow Paging then make it True. Here I made the page size 5, you can select the page size depending on your data.

Code Chamber

Before this coding part you need to download the iTextsharp library from the Souceforge website, here is the link. Just download the file, the file is in Zip format so just unzip the files to a suitable location so that we can easily browse it.

Itextsharp Library download: itextsharp-all-5.5.6.

Itextsharp Library

After you download the file, you check this out that you downloaded the right file, look at the following image.

download

Step 5

Now for the server-side coding so that our application works. Open your gridviewexcel_demo.aspx.cs file and code it as in the following.

You first need to import the DLL of ItextSharp by going to your empty website (gridviewexcel_demo) then right-click then select Add Refrences.

add reference

Now browse to the ItextSharp unzip file and open it. Be sure you got all the DLL files unzipped into your application. See the following image to understand what DLL you need to import.

Browse the ItextSharp

Now import these namspaces, since they will be needed when we write code for exporting the GridView to Excel.

namspaces

It's time for the code, first we bind the grid view, then we make the code for paging using the GridView event OnPageIndexChanging, then we will write code for exporting the grid view to an Excel document on button click.
  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. public partial class _Default : System.Web.UI.Page  
  17. {  
  18.     protected void Page_Load(object sender, EventArgs e)  
  19.     {  
  20.   
  21.         if (!Page.IsPostBack)  
  22.         {  
  23.             refreshdata();  
  24.         }  
  25.          
  26.   
  27.     }  
  28.   
  29.     // Bind the gridview here  
  30.     public void refreshdata()  
  31.     {  
  32.         SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");  
  33.         SqlCommand cmd = new SqlCommand("select * from tbl_data", con);  
  34.         SqlDataAdapter sda = new SqlDataAdapter(cmd);  
  35.         DataTable dt = new DataTable();  
  36.         sda.Fill(dt);  
  37.         GridView1.DataSource = dt;  
  38.         GridView1.DataBind();    
  39.       
  40.     }  
  41.   
  42.     // Gridview Paging code here  
  43.     protected void GridView1_PageIndexChanging1(object sender, GridViewPageEventArgs e)  
  44.     {  
  45.         GridView1.PageIndex = e.NewPageIndex;  
  46.   
  47.         refreshdata();  
  48.     }  
  49.   
  50.   
  51.     // Exporting Gridview to pdf code here  
  52.     protected void Button1_Click1(object sender, EventArgs e)  
  53.     {  
  54.         Response.Clear();  
  55.         Response.Buffer = true;  
  56.         Response.ContentType = "application/vnd.ms-excel";  
  57.         Response.AddHeader("content-disposition""attachment;filename=GridViewExport.xls");  
  58.         Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  59.   
  60.         StringWriter swr = new StringWriter();  
  61.         HtmlTextWriter htmlwr = new HtmlTextWriter(swr);  
  62.         GridView1.AllowPaging = false;  
  63.          refreshdata();  
  64.        GridView1.RenderControl(htmlwr);  
  65.         Response.Output.Write(swr.ToString());  
  66.         Response.Flush();  
  67.         Response.End();  
  68.        
  69.   
  70.   }  
  71.     public override void VerifyRenderingInServerForm(Control control)  
  72.     {  
  73.   
  74.     }  
  75.   
  76. }  
When you run your code, it will run perfectly, but when you click on the button you will always get this error, this error generally occurs when we are exporting a GridView to Word, Excel or a PDF because the compiler thinks that the control is not in the form.

error

To solve this problem we just embed a code below the Button_click event like this.

Button click

Now run your code, it will now work perfectly.

Output Chamber

Output Chamber

Output

I hope you like this. Thank you for reading. Have a good day!