Saturday, January 3, 2015

Convert into Pdf Doc and Execl from GridView



Export Data
In this article  I am going to explain how to convert your GridView data into to specify format like , firstly I am going with pdf conversion.
GridView to PDF conversion

If you want to convert gridview data to pdf then you must have third parity dll “itextsharp.dll”.
So first I will show you my sql table data.

Create a table :
USE [master]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[convertdata](
      [UserId] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
      [UserName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [LastName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [Location] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
 CONSTRAINT [PK_convertdata] PRIMARY KEY CLUSTERED
(
      [UserId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


Displaying Data in Gridview :
Just write a some line of code that will display data in grid view.
SqlDataAdapter da;
DataSet ds;
 SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Connect"].ConnectionString);
          cn.Open();
          da = new SqlDataAdapter("Select * from convertdata",cn);
          ds = new DataSet();
          da.Fill(ds);
          GridView1.DataSource = ds.Tables[0];
          GridView1.DataBind();
          cn.Close();

Now its time to convert your grid view data as a pdf format, for doing it just write some line of code which is given below.

Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=test.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            HtmlForm frm = new HtmlForm();
            GridView1.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(GridView1);
            frm.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();

GridView to Word conversion

 The given below code shown you how to do it

Response.AddHeader("content-disposition", "attachment;filename=Export.doc");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/test.word";
 
            StringWriter stringWrite = new StringWriter();
           HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

       
            HtmlForm frm = new HtmlForm();
            GridView1.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(GridView1);
           frm.RenderControl(htmlWrite);
     
           Response.Write(stringWrite.ToString());
           Response.End();

GridView to Word conversion

The code for it given below

string attachment = "attachment; filename=test.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();
               GridView1.Parent.Controls.Add(frm);
               frm.Attributes["runat"] = "server";
               frm.Controls.Add(GridView1);
               frm.RenderControl(htw);
               Response.Write(sw.ToString());
               Response.End();

GridView to Execl conversion

The code for gridview to execl

var filename = Hidden1.Value;
           string attachment = "attachment; filename=" + filename + ".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();
           GridView1.Parent.Controls.Add(frm);
           frm.Attributes["runat"] = "server";
           frm.Controls.Add(GridView1);
           frm.RenderControl(htw);
           Response.Write(sw.ToString());
           Response.End();

Full aspx code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Export.aspx.cs" Inherits="Export" Title="Untitled Page" %>
  <html xmlns="http://www.w3.org/1999/xhtml">
  <head  id="head1" runat="server">
  <title></title>
  <script type="text/javascript">
      function myFunction() {
          var x;
          var site = prompt("Write name of Your File");
          if (site != null) {
              x = site;
              document.getElementById("Hidden1").value = x;
          }
      }
</script>
</head>
<body>
    <form id="form1" runat="server">


    <table style="width: 73%">
    <tr>
        <td class="style3">
            &nbsp;</td>
        <td colspan="2" style="height: 27px">
            &nbsp;</td>
    </tr>
    <tr>
        <td class="style4">
            &nbsp;</td>
        <td>
            &nbsp;</td>
        <td>
            &nbsp;</td>
    </tr>
    <tr>
        <td class="style4">
            &nbsp;</td>
        <td colspan="2">
            <br />
           <h3 style="font-family: 'Times New Roman', Times, serif; color: #800000">Convert GridView Data into PDF,DOC,Execl</h3>
            <asp:Button ID="Button2" runat="server" onclick="Button2_Click"
                style="top: 263px; left: 403px; position: absolute; height: 26px; width: 85px"
                Text="Export Word" OnClientClick="myFunction();" />
            <asp:Button ID="Button3" runat="server"
                style="top: 317px; left: 405px; position: absolute; height: 26px; width: 85px"
                Text="Export Excel" OnClientClick="myFunction();"
                onclick="Button3_Click" />
&nbsp;&nbsp;&nbsp;
            </td>
    </tr>
    <tr>
        <td class="style4">
           
            &nbsp;</td>
        <td colspan="2">
           
            <br />
           
                <input id="Hidden1" type="hidden" runat="server" />
                <div runat="server" id="divPrint">
         
                    <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
                        GridLines="None">
                        <AlternatingRowStyle BackColor="White" />
                        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
                        <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
                        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                        <SortedAscendingCellStyle BackColor="#FDF5AC" />
                        <SortedAscendingHeaderStyle BackColor="#4D0000" />
                        <SortedDescendingCellStyle BackColor="#FCF6C0" />
                        <SortedDescendingHeaderStyle BackColor="#820000" />
                    </asp:GridView>
                    <asp:Button ID="Button1" runat="server" OnClientClick="myFunction();"
                        style="top: 208px; left: 404px; position: absolute; height: 26px; width: 85px"
                        Text="Export Pdf" onclick="Button1_Click" />
            </div>   

        </td>
    </tr>
    <tr>
        <td class="style4">
            &nbsp;</td>
        <td>
            &nbsp;</td>
        <td>
            &nbsp;</td>
    </tr>
    <tr>
        <td class="style4">
            &nbsp;</td>
        <td>
            &nbsp;</td>
        <td>
            &nbsp;</td>
    </tr>
    <tr>
        <td class="style4">
            &nbsp;</td>
        <td>
            &nbsp;</td>
        <td>
            &nbsp;</td>
    </tr>
    <tr>
        <td class="style4">
            &nbsp;</td>
        <td>
            &nbsp;</td>
        <td>
            &nbsp;</td>
    </tr>
    <tr>
        <td class="style4">
            &nbsp;</td>
        <td>
            &nbsp;</td>
        <td>
            &nbsp;</td>
    </tr>
</table>

 </form>
    </body>



    </html>


        <style type="text/css">
        .style3
        {
            height: 27px;
            width: 93px;
        }
        .style4
        {
            width: 93px;
        }
    </style>




In this I create a JavaScript function that will use for taking input as file name of any format

<script type="text/javascript">
      function myFunction() {
          var x;
          var site = prompt("Write name of Your File");
          if (site != null) {
              x = site;
              document.getElementById("Hidden1").value = x;
          }
      }
</script>

After it , for executing that method  I just write a simple code “ OnClientClick="myFunction();"”
On every button click, and for using the name of file name in your c# code you just write a one line code that enables you accessing the file name in your c# code.


var filename = Hidden1.Value;

 Here hidden field accepts the file name which is given by you in prompt box.

Full aspx.cs code

using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;


public partial class Export : System.Web.UI.Page
{
    SqlDataAdapter da;
    DataSet ds;
      protected void Page_Load(object sender, EventArgs e)
    {
      if(!IsPostBack)
      {
          SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Connect"].ConnectionString);
          cn.Open();
          da = new SqlDataAdapter("Select * from convertdata",cn);
          ds = new DataSet();
          da.Fill(ds);
          GridView1.DataSource = ds.Tables[0];
          GridView1.DataBind();
          cn.Close();
      }
    }


      
       protected void Button1_Click(object sender, EventArgs e)
       {
           var filename = Hidden1.Value;
           Response.ContentType = "application/pdf";
           Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".pdf");
           Response.Cache.SetCacheability(HttpCacheability.NoCache);
           StringWriter sw = new StringWriter();
           HtmlTextWriter hw = new HtmlTextWriter(sw);
           HtmlForm frm = new HtmlForm();
           GridView1.Parent.Controls.Add(frm);
           frm.Attributes["runat"] = "server";
           frm.Controls.Add(GridView1);
           frm.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();

       }
       protected void Button2_Click(object sender, EventArgs e)
       {
           var filename = Hidden1.Value;
           Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".doc");
           Response.Cache.SetCacheability(HttpCacheability.NoCache);
           Response.ContentType = "application/vnd.word";

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


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


           Response.Write(stringWrite.ToString());
           Response.End();
       }
       protected void Button3_Click(object sender, EventArgs e)
       {
           var filename = Hidden1.Value;
           string attachment = "attachment; filename=" + filename + ".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();
           GridView1.Parent.Controls.Add(frm);
           frm.Attributes["runat"] = "server";
           frm.Controls.Add(GridView1);
           frm.RenderControl(htw);
           Response.Write(sw.ToString());
           Response.End();
       }
}


Output:

After running you website output will look like:



Output2:



Output3:



2 comments: