Wednesday, 3 April 2013

How to Convert the Gridview Data to Pdf, Excel & Word Format









<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td align="right">
                    <asp:ImageButton ID="ImageButton2" runat="server" Height="32px"  ImageUrl="~/Image/Word.jpg"
                        onclick="ImageButton2_Click" Width="32px" />
                    <asp:ImageButton ID="ImageButton1" runat="server" Height="32px"  ImageUrl="~/Image/Excel.jpg"
                        onclick="ImageButton1_Click" Width="32px" />
                    <asp:ImageButton ID="btnPDF" runat="server" ImageUrl="~/Image/PDF.jpg" Width="32px" Height="32px"
                        OnClick="btnPDF_Click" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:GridView ID="gvdetails" AllowPaging="false" runat="server" AllowSorting="true"
                        AutoGenerateColumns="false">
                        <RowStyle BackColor="#EFF3FB" />
                        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                        <HeaderStyle Font-Bold="True"/>
                        <AlternatingRowStyle BackColor="White" />
                        <Columns>
                            <asp:BoundField DataField="Name" HeaderText="Name" />
                            <asp:BoundField DataField="Address" HeaderText="Address" />
                            <asp:BoundField DataField="Course" HeaderText="Course" />
                        </Columns>
                    </asp:GridView>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

In the Code Behind just write the following code
-------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;

public partial class GridviewToPDF : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            fillgrid();
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {

    }
    void fillgrid()
    {
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["cnstr"].ConnectionString);
        SqlDataAdapter ad = new SqlDataAdapter("Select * from Student", con);
        DataSet ds = new DataSet();
        ad.Fill(ds);
        gvdetails.DataSource = ds;
        gvdetails.DataBind();
    }

    protected void btnPDF_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            Response.Clear(); //this clears the Response of any headers or previous output
            Response.Buffer = true; //ma
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=DataTable.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            gvdetails.RenderControl(hw);

            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }


//For Excel file

    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        string attachment = "attachment; filename=Export.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        gvdetails.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(gvdetails);
        frm.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }

// For Word file
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {
        Response.AddHeader("content-disposition", "attachment;filename=Export.doc");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.word";

        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        HtmlForm frm = new HtmlForm();
        gvdetails.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(gvdetails);
        frm.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());
        Response.End();
    }
}


2 comments: