.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

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

Posted By:Sanjeeb Lenka       Posted Date: November 29, 2013    Points: 25    Category: ASP.NET    URL: http://www.dotnetspark.com  

This article describes how to export a GridView data to excel, word, pdf, text, csv format and print in ASP.Net.
 

Introduction

This article describes how to export a GridView data to excel, word, pdf, text, csv format and print in ASP.Net.

Description

Since there is no support for pdf conversion, we require a third-party DLL to be referenced by our application that will use for convert the grid to pdf.

  1. itextsharp.dll

You can download it from the source code attached to this article.  

Design

Now add GridvView, six Button for export. Design your screen as in the following screen.

Or you can copy the following source code:

<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="EmpId" HeaderText="Employee ID" />
                            <asp:BoundField DataField="EmpName" HeaderText="Employee Name" />
                            <asp:BoundField DataField="Education" HeaderText="Education" />
                            <asp:BoundField DataField="Place" HeaderText="Place" />
                        </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();" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>


Now go to the code view.

Here I use a static datatable data to bind it to grid. but you can use database data to bind.

Import the reference of
using System.Data;

following is the code to bind data to grid method and call this method in :

    

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridDetails();
        }
    }
    protected void BindGridDetails()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("EmpId", typeof(Int32));
        dt.Columns.Add("EmpName", typeof(string));
        dt.Columns.Add("Education", typeof(string));
        dt.Columns.Add("Place", typeof(string));
        DataRow dtrow = dt.NewRow();
        dtrow["EmpId"] = 1;
        dtrow["EmpName"] = "Sanjeeb";
        dtrow["Education"] = "MCA";
        dtrow["Place"] = "Hyderabad";
        dt.Rows.Add(dtrow);
        dtrow = dt.NewRow();
        dtrow["EmpId"] = 2;
        dtrow["EmpName"] = "Laku";
        dtrow["Education"] = "MBA";
        dtrow["Place"] = "Hyderabad";
        dt.Rows.Add(dtrow);
        dtrow = dt.NewRow();
        dtrow["EmpId"] = 3;
        dtrow["EmpName"] = "Pankaj";
        dtrow["Education"] = "B.Tech";
        dtrow["Place"] = "Bihar";
        dt.Rows.Add(dtrow);
        dtrow = dt.NewRow();
        dtrow["EmpId"] = 4;
        dtrow["EmpName"] = "Srikanth";
        dtrow["Education"] = "B.Tech";
        dtrow["Place"] = "Hyderabad";
        dt.Rows.Add(dtrow);
        gvDetails.DataSource = dt;
        gvDetails.DataBind();
    }     

Now run the application you will see the gridview with data.



GridView with data is ready for export.

Import the reference of
using System.IO;

Now write this code under button click event of Exel.

//This code is for export grid to exel
    protected void btnExel_Click(object sender, EventArgs e)
    {
        BindGridDetails();
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Details.xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter ht = new HtmlTextWriter(sw);
        gvDetails.RenderControl(ht);
        Response.Write(sw.ToString());
        Response.End();
    }    


 write this code under button click event of Word:

//This code is for export grid to word
    protected void btnWord_Click(object sender, EventArgs e)
    {
        BindGridDetails();
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Details.doc"));
        Response.ContentType = "application/ms-word";
        StringWriter sw = new StringWriter();
        HtmlTextWriter ht = new HtmlTextWriter(sw);
        gvDetails.RenderControl(ht);
        Response.Write(sw.ToString());
        Response.End();
    }

Import the reference of
using System.Text;

 write this code under button click event of Text:

    
 

//This code is for export grid to text
    protected void btnText_Click(object sender, EventArgs e)
    {
        BindGridDetails();
        Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Details.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();
    }

write this code under button click event of Csv:

///This code is for export grid to text

     protected void btnText_Click(object sender, EventArgs e)
     {
         BindGridDetails();
         Response.ClearContent();
         Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Details.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();
     }


Before write the code for pdf 1st add the reference of itextsharp.dll.

Import these namspaces.

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

write this code under button click event of Pdf:

///This code is for export grid to text

     protected void btnText_Click(object sender, EventArgs e)
     {
         BindGridDetails();
         Response.ClearContent();
         Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Details.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();
     }


For print button write this javascript code in head section of aspx page.

<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> 

Call this function in print button OnClientClick.

<asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick="PrintGridData();" />

Now if you run the application you will got an error like this 


To avoid this error write this code :

//Verifies the control is rendered
    public override void VerifyRenderingInServerForm(Control control)
    {
    }


Now run the application and check the app by clicking on export Buttons. 


 Subscribe to Articles

     

Further Readings:

Responses
Author: gorge         Company URL: http://www.dotnetspark.com
Posted Date: May 30, 2014

hi,

great sulotion for users of itextsharp.but for others who're not using this toolkit,there will be another wonderful solution on this aratile,check-
http://www.e-iceblue.com/Knowledgebase/Spire.DataExport/Spire.DataExport-Program-Guide/How-to-Export-Data-from-Datatable-to-Word-Document-in-C.html
Sample codes and demo are as well availabe.

regards

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend