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.
Design Chamber
Step 4
Now design your application by going to GridView doc_demo.aspx and write the following code.
GridView doc_demo.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html
- xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:Gridview ID="Gridview 1" runat="server" AllowPaging="True"
- AutoGenerateColumns="False" CellPadding="4" DataKeyNames="id"
- GridLines="None" onpageindexchanging="Gridview 1_PageIndexChanging1"
- PageSize="5" ForeColor="#333333">
- <AlternatingRowStyle BackColor="White" />
- <Columns>
- <asp:TemplateField HeaderText="Name">
- <EditItemTemplate>
- <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'>
- </asp:TextBox>
- </EditItemTemplate>
- <ItemTemplate>
- <asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'>
- </asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Education">
- <EditItemTemplate>
- <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("education") %>'>
- </asp:TextBox>
- </EditItemTemplate>
- <ItemTemplate>
- <asp:Label ID="Label2" runat="server" Text='<%# Bind("education") %>'>
- </asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Email">
- <EditItemTemplate>
- <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("email") %>'>
- </asp:TextBox>
- </EditItemTemplate>
- <ItemTemplate>
- <asp:Label ID="Label3" runat="server" Text='<%# Bind("email") %>'>
- </asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Location">
- <EditItemTemplate>
- <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("location") %>'>
- </asp:TextBox>
- </EditItemTemplate>
- <ItemTemplate>
- <asp:Label ID="Label4" runat="server" Text='<%# Bind("location") %>'>
- </asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- </Columns>
- <EditRowStyle BackColor="#7C6F57" />
- <FooterStyle BackColor="#1C5E55" ForeColor="White" Font-Bold="True" />
- <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
- <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
- <RowStyle BackColor="#E3EAEB" />
- <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
- <SortedAscendingCellStyle BackColor="#F8FAFA" />
- <SortedAscendingHeaderStyle BackColor="#246B61" />
- <SortedDescendingCellStyle BackColor="#D4DFE1" />
- <SortedDescendingHeaderStyle BackColor="#15524A" />
- </asp:Gridview >
- <br />
- <br />
- </div>
- <asp:Button ID="Button1" runat="server" onclick="Button1_Click1"
- Text="Export To PDF" />
- </form>
- </body>
- </html>
Your design will look something like the following:
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.
After downloading the file, check that you have downloaded the right file or not. Here is the screenshot:
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.
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.
Now import these namespaces, since it will needed when we write code for exporting the GridView to doc.
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- using System.IO;
- using System.Text;
- using iTextSharp.text;
- using iTextSharp.text.html;
- using iTextSharp.text.html.simpleparser;
- using iTextSharp.text.pdf;
-
- public partial class _Default: System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
-
- if (!Page.IsPostBack)
- {
- refreshdata();
- }
-
-
- }
-
-
- public void refreshdata()
- {
- SqlConnection con = new SqlConnection(@
- "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
- SqlCommand cmd = new SqlCommand("select * from tbl_data", con);
- SqlDataAdapter sda = new SqlDataAdapter(cmd);
- DataTable dt = new DataTable();
- sda.Fill(dt);
- Gridview 1.DataSource = dt;
- Gridview 1.DataBind();
-
- }
-
-
- protected void Gridview 1_PageIndexChanging1(object sender, Gridview PageEventArgs e) {
- Gridview 1.PageIndex = e.NewPageIndex;
-
- refreshdata();
- }
-
-
-
- protected void Button1_Click1(object sender, EventArgs e)
- {
- Response.ContentType = "application/vnd.ms-word";
- Response.AddHeader("content-disposition", "attachment;filename=Gridview Export.doc");
- Response.Cache.SetCacheability(HttpCacheability.NoCache);
-
- StringWriter swr = new StringWriter();
- HtmlTextWriter htmlwr = new HtmlTextWriter(swr);
- Gridview 1.AllowPaging = false;
- refreshdata();
- Gridview 1.RenderControl(htmlwr);
- Response.Output.Write(swr.ToString());
- Response.End();
- }
- public override void VerifyRenderingInServerForm(Control control)
- {
-
- }
-
- }
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.
To solve this problem we just embed a code below the Button_click event like the following:
Now run your code, it works perfectly.
Output Chamber
I hope you liked this.
Have a nice day and thank you for reading.