Share Blog

Monday, August 04, 2014

Export GridView Data to Excel, Word, Pdf, Text and Csv Format and Print Using in Asp.Net

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!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 id="Head1" runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <link href="Styles/nivo-slider.css" rel="stylesheet" type="text/css" />
    <link href="Styles/Default.css" rel="stylesheet" type="text/css" />
    <link href="Styles/nivo-slider.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/Demo.js" type="text/javascript"></script>
    <script type="text/javascript">
        function PrintGridData() {
            var prtGrid = document.getElementById('<%=gvDetails.ClientID %>');
            var prtwin = window.open('', 'PrintGridView',
'left=100,top=100,width=400,height=400,tollbar=0,scrollbars=1,status=0,resizable=1');
            prtwin.document.write(prtGrid.outerHTML);
            prtwin.document.close();
            prtwin.focus();
            prtwin.print();
            prtwin.close();
        }
   </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td colspan="3" align="center">
                    <asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false">
                        <Columns>
                            <asp:BoundField DataField="CustomerID" HeaderText="Employee Id" />
                            <asp:BoundField DataField="Name" HeaderText="Last Name" />
                            <asp:BoundField DataField="company" HeaderText="Company" />
                        </Columns>
                    </asp:GridView>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnExel" runat="server" Text="Export to Exel" OnClick="btnExel_Click" />
                </td>
                <td>
                    <asp:Button ID="btnWord" runat="server" Text="Export to Word" OnClick="btnWord_Click" />
                </td>
                <td>
                    <asp:Button ID="btnPdf" runat="server" Text="Export to Pdf" OnClick="btnPdf_Click" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnCsv" runat="server" Text="Export to Csv" OnClick="btnCsv_Click" />
                </td>
                <td>
                    <asp:Button ID="btnText" runat="server" Text="Export to Text" OnClick="btnText_Click" />
                </td>
                <td>
                    <asp:Button ID="btnPrint" runat="server" Text="Print"
                        OnClientClick="PrintGridData();" onclick="btnPrint_Click" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

</html>




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;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;


public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();
        }
    }
    public void Bind()
    {
        SqlConnection con = new SqlConnection("Data Source=SERVER02\\sqlserver;Initial Catalog=EMPLOYEE;User ID=***;Password=********");

        SqlDataAdapter da = new SqlDataAdapter("select *  from customers", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        gvDetails.DataSource = ds;
        gvDetails.DataBind();

    }
    protected void btnExel_Click(object sender, EventArgs e)
    {
        Bind();
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Documents.xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter ht = new HtmlTextWriter(sw);
        gvDetails.RenderControl(ht);
        Response.Write(sw.ToString());
        Response.End();
    }
    protected void btnWord_Click(object sender, EventArgs e)
    {
        Bind();
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Documents.doc"));
        Response.ContentType = "application/ms-word";
        StringWriter sw = new StringWriter();
        HtmlTextWriter ht = new HtmlTextWriter(sw);
        gvDetails.RenderControl(ht);
        Response.Write(sw.ToString());
        Response.End();
    }
    protected void btnPdf_Click(object sender, EventArgs e)
    {
        Bind();
        Response.ContentType = "Sunil/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=Documents.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();
    }
    protected void btnText_Click(object sender, EventArgs e)
    {
        Bind();
        Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Documents.txt"));
        Response.ContentType = "application/text";
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < gvDetails.Columns.Count; i++)
        {
            str.Append(gvDetails.Columns[i].HeaderText + ',');
        }
        str.Append("\n");
        for (int j = 0; j < gvDetails.Rows.Count; j++)
        {
            for (int k = 0; k < gvDetails.Columns.Count; k++)
            {
                str.Append(gvDetails.Rows[j].Cells[k].Text + ',');
            }
            str.Append("\n");
        }
        Response.Write(str.ToString());
        Response.End();
    }
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        Bind();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
    protected void btnCsv_Click(object sender, EventArgs e)
    {
        Bind();
        Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Documents.txt"));
        Response.ContentType = "application/text";
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < gvDetails.Columns.Count; i++)
        {
            str.Append(gvDetails.Columns[i].HeaderText + ',');
        }
        str.Append("\n");
        for (int j = 0; j < gvDetails.Rows.Count; j++)
        {
            for (int k = 0; k < gvDetails.Columns.Count; k++)
            {
                str.Append(gvDetails.Rows[j].Cells[k].Text + ',');
            }
            str.Append("\n");
        }
        Response.Write(str.ToString());
        Response.End();
    }
}

No comments:

Post a Comment