Export GridView to Word Document Using Itextsharp Library

In this article we will use a GridView with some fields, then we will export that GridView into a Word document using the ItextSharp library. This article is similar to my previous article were I explained how to export a GridView to a PDF.

Initial Chamber

Step 1

Open Visual Studio 2010 and create an empty website, name it GridView doc_demo.

Step 2

In Solution Explorer you will get your empty website, then add a Web Form and SQL Server Database. The following is the procedure.

For Web Form

For GridView doc_demo (your empty website), right-click and select Add New Item, Web Form. Name it GridView doc_demo.aspx.

For SQL Server Database

For GridView doc_demo (your empty website), right-click and select Add New Item, SQL Server Database. Also, add a database inside the App_Data_folder.

Database Chamber

Step 3

In Server Explorer, click on your database Database.mdf, go to Tables and Add New Table. The following is the procedure.

Table, go to tbl_data and don't forget to make ID as IS Identity true.

table design

Design Chamber

Step 4

Now design your application by going to GridView doc_demo.aspx and write the following code.

GridView doc_demo.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html  
  4.     xmlns="http://www.w3.org/1999/xhtml">  
  5.     <head runat="server">  
  6.         <title></title>  
  7.     </head>  
  8.     <body>  
  9.         <form id="form1" runat="server">  
  10.             <div>  
  11.                 <asp:Gridview  ID="Gridview 1" runat="server" AllowPaging="True"   
  12. AutoGenerateColumns="False" CellPadding="4" DataKeyNames="id"   
  13. GridLines="None" onpageindexchanging="Gridview 1_PageIndexChanging1"   
  14. PageSize="5" ForeColor="#333333">  
  15.                     <AlternatingRowStyle BackColor="White" />  
  16.                     <Columns>  
  17.                         <asp:TemplateField HeaderText="Name">  
  18.                             <EditItemTemplate>  
  19.                                 <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'>  
  20.                                 </asp:TextBox>  
  21.                             </EditItemTemplate>  
  22.                             <ItemTemplate>  
  23.                                 <asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'>  
  24.                                 </asp:Label>  
  25.                             </ItemTemplate>  
  26.                         </asp:TemplateField>  
  27.                         <asp:TemplateField HeaderText="Education">  
  28.                             <EditItemTemplate>  
  29.                                 <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("education") %>'>  
  30.                                 </asp:TextBox>  
  31.                             </EditItemTemplate>  
  32.                             <ItemTemplate>  
  33.                                 <asp:Label ID="Label2" runat="server" Text='<%# Bind("education") %>'>  
  34.                                 </asp:Label>  
  35.                             </ItemTemplate>  
  36.                         </asp:TemplateField>  
  37.                         <asp:TemplateField HeaderText="Email">  
  38.                             <EditItemTemplate>  
  39.                                 <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("email") %>'>  
  40.                                 </asp:TextBox>  
  41.                             </EditItemTemplate>  
  42.                             <ItemTemplate>  
  43.                                 <asp:Label ID="Label3" runat="server" Text='<%# Bind("email") %>'>  
  44.                                 </asp:Label>  
  45.                             </ItemTemplate>  
  46.                         </asp:TemplateField>  
  47.                         <asp:TemplateField HeaderText="Location">  
  48.                             <EditItemTemplate>  
  49.                                 <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("location") %>'>  
  50.                                 </asp:TextBox>  
  51.                             </EditItemTemplate>  
  52.                             <ItemTemplate>  
  53.                                 <asp:Label ID="Label4" runat="server" Text='<%# Bind("location") %>'>  
  54.                                 </asp:Label>  
  55.                             </ItemTemplate>  
  56.                         </asp:TemplateField>  
  57.                     </Columns>  
  58.                     <EditRowStyle BackColor="#7C6F57" />  
  59.                     <FooterStyle BackColor="#1C5E55" ForeColor="White" Font-Bold="True" />  
  60.                     <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />  
  61.                     <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />  
  62.                     <RowStyle BackColor="#E3EAEB" />  
  63.                     <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />  
  64.                     <SortedAscendingCellStyle BackColor="#F8FAFA" />  
  65.                     <SortedAscendingHeaderStyle BackColor="#246B61" />  
  66.                     <SortedDescendingCellStyle BackColor="#D4DFE1" />  
  67.                     <SortedDescendingHeaderStyle BackColor="#15524A" />  
  68.                 </asp:Gridview >  
  69.                 <br />  
  70.                 <br />  
  71.             </div>  
  72.             <asp:Button ID="Button1" runat="server" onclick="Button1_Click1"   
  73. Text="Export To PDF" />  
  74.         </form>  
  75.     </body>  
  76. </html> 

Your design will look something like the following:

design

You can show paging by going to GridView properties (press F4), then find Allow Paging and make it True. Here I made the page size to – 5. However, 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. I have provided the link below, just download the file. The file is in Zip format, just unzip the files to a suitable location, so that we can easily browse it.

Itextsharp Library download: itextsharp-all-5.5.6.

Itextsharp

After downloading the file, check that you have downloaded the right file or not. Here is the screenshot:

download the right file

Step 5

Now it's time for the server-side coding so that our application starts working. Open your GridView doc_demo.aspx.cs file and code it like the following.

First import the DLL of ItextSharp by going to your empty website (GridView doc_demo), then right-clicking and selecting Add References.

Add References

Now browse the ItextSharp unzip file and open it, be sure you get all the unzipped DLL files into your application. See the following image to understand what DLL you must import.

dll

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

namespaces

First we will bind the GridView, than we will make code for paging using the GridView event OnPageIndexChanging, then we will write the code for exporting the GridView to a Word 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(@  
  33.         "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");  
  34.         SqlCommand cmd = new SqlCommand("select * from tbl_data", con);  
  35.         SqlDataAdapter sda = new SqlDataAdapter(cmd);  
  36.         DataTable dt = new DataTable();  
  37.         sda.Fill(dt);  
  38.         Gridview 1.DataSource = dt;  
  39.         Gridview 1.DataBind();  
  40.   
  41.     }  
  42.   
  43.     // Gridview Paging code here  
  44.     protected void Gridview 1_PageIndexChanging1(object sender, Gridview PageEventArgs e) {  
  45.         Gridview 1.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.ContentType = "application/vnd.ms-word";  
  55.         Response.AddHeader("content-disposition""attachment;filename=Gridview Export.doc");  
  56.         Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  57.   
  58.         StringWriter swr = new StringWriter();  
  59.         HtmlTextWriter htmlwr = new HtmlTextWriter(swr);  
  60.         Gridview 1.AllowPaging = false;  
  61.         refreshdata();  
  62.         Gridview 1.RenderControl(htmlwr);  
  63.         Response.Output.Write(swr.ToString());  
  64.         Response.End();  
  65.     }  
  66.     public override void VerifyRenderingInServerForm(Control control)   
  67.     {  
  68.   
  69.     }  
  70.   

When you run the code, it will run perfectly, but when you click on the button you will be stuck with the following error. This error generally occurs when we are exporting a GridView to a Word, Excel or PDF because the compiler thinks that the control is not added to the form.

error

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

click event
Now run your code, it works perfectly.

Output Chamber

Output

Gridview

I hope you liked this.
Have a nice day and thank you for reading.


Similar Articles