Email: Password:       Forgot Password 
    .netCodeSG
A Saarsha Group Online Community for dot net codes group like C#, Asp.NET, VB.NET, Sharepoint, JavaScript, JQuery, Ajax, SQL, WCF, WPF.
 
TECHNOLOGIES:
 

How To Export GridView Data To CSV Word Excel PDF

Article:
Viewed:  3434 
Posted On:  01/02/2013 10:25:19 
In this article I am going to explain how we can export GridView Data To CSV Word Excel PDF.  

In this article I am going to explain how we can export GridView Data in CSV, WORD, EXCEL and PDF file.

Below is my Grid View and some button to export data..

Export1.png

Image 1.

If we click on Export to CSV

Export1_CSV.png

Image 2.

If we click on export to Word

Export1_Word.png

Image 3.

If we click on Export to excel

Export1_EXCEL.png

Image 4.

If we click on Export to PDF.

Export1_PDF.png

Image 5.

 

For this below is my aspx code:

<%@ 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>Export Data in CSV, WORD, EXCEL, PDF</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table cellpadding="2" cellspacing="2" width="60%" align="center">
            <tr>
                <td align="center" bgcolor="#FFFFFF" colspan="9">
                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%"
                        AllowPaging="True" AllowSorting="True" BackColor="White" BorderColor="#DEDFDE"
                        BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical">

                        
<RowStyle BackColor="#F7F7DE" />
                        <Columns>
                            <asp:BoundField DataField="ID" HeaderText="ID" />
                            <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                            <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                            <asp:BoundField DataField="JoiningDate" HeaderText="Join Date" />
                        </Columns>
                        <FooterStyle BackColor="#CCCC99" />
                        <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
                        <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
                        <AlternatingRowStyle BackColor="White" />
                    </asp:GridView>
                    <asp:Label ID="lblStatus" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnExportToCSV" runat="server" Text="Export To CSV" OnClick="btnExportToCSV_Click"
                        BorderColor="ActiveCaption" BorderStyle="Groove" />
                </td>
                <td>
                    <asp:Button ID="btnExportToWord" runat="server" Text="Export To Word" OnClick="btnExportToWord_Click"
                        BorderColor="ActiveCaption" BorderStyle="Groove" />
                </td>
                <td>
                    <asp:Button ID="btnExportToEXCEL" runat="server" Text="Export To EXCEL" OnClick="btnExportToEXCEL_Click"
                        BorderColor="ActiveCaption" BorderStyle="Groove" />
                </td>
                <td>
                    <asp:Button ID="btnExportToPDF" runat="server" Text="Export To PDF" OnClick="btnExportToPDF_Click"
                        BorderColor="ActiveCaption" BorderStyle="Groove" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>
 

This is my aspx.cs code

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.IO;
using System.Text;
 
public partial class _Default : System.Web.UI.Page
{
    SqlDataAdapter da;
    DataSet ds = new DataSet();
 
    protected void Page_Load(object sender, EventArgs e)
    {
        BindData();
    }
 
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
 
    private void BindData()
    {
        SqlConnection con = new SqlConnection("Server=.;Database=MyData;Uid=sa; pwd=India@123");
        SqlCommand cmd = new SqlCommand("SELECT ID, FirstName,LastName,JoiningDate FROM Employee", con);
        try
        {
            da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
             if (!object.Equals(ds.Tables[0], null))
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    GridView1.DataSource = ds.Tables[0];
                    GridView1.DataBind();
                    Session["MyTable"] = ds.Tables[0];
                }
                else
                {
                    GridView1.DataSource = null;
                    GridView1.DataBind();
                }
            }
            else
            {
                GridView1.DataSource = null;
                GridView1.DataBind();
            }
        }
        catch (Exception ex)-
        {
            lblStatus.Text = ex.Message;
        }
    }
 
    protected void btnExportToCSV_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=MyGridRecord.csv");
        Response.Charset = "";

       
Response.ContentType = "application/text";
 
        GridView1.AllowPaging = false;
        GridView1.DataBind();
 
        StringBuilder sb = new StringBuilder();
        for (int k = 0; k < GridView1.Columns.Count; k++)
        {
            sb.Append(GridView1.Columns[k].HeaderText + ',');
        }
 
        sb.Append("\r\n");
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            for (int k = 0; k < GridView1.Columns.Count; k++)
            {
                sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
            }
            sb.Append("\r\n");
        }
        Response.Output.Write(sb.ToString());
        Response.Flush();
        Response.End();
    }-
 
    protected void btnExportToWord_Click(object sender, EventArgs e)
    {
        GridView1.AllowPaging = false;
        GridView1.DataBind();
        Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MyGridRecord.doc"));
        Response.Charset = "";
        Response.ContentType = "application/ms-word";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }
 
    protected void btnExportToEXCEL_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
 
        Response.AddHeader("content-disposition", "attachment;filename=MyGridRecord.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
 
        GridView1.AllowPaging = false;
        GridView1.DataBind();

        //Change the Header Row back to white color
        GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
 
        //Apply style to Individual Cells
        GridView1.HeaderRow.Cells[0].Style.Add("background-color", "blue");-
        GridView1.HeaderRow.Cells[1].Style.Add("background-color", "blue");
        GridView1.HeaderRow.Cells[2].Style.Add("background-color", "blue");
        GridView1.HeaderRow.Cells[3].Style.Add("background-color", "blue");
 
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];
 
            //Change Color back to white
            row.BackColor = System.Drawing.Color.White;
 
            //Apply text style to each Row
            row.Attributes.Add("class", "textmode");
 
            //Apply style to Individual Cells of Alternating Row
            if (i % 2 != 0)
            {
                row.Cells[0].Style.Add("background-color", "#00CED1");
                row.Cells[1].Style.Add("background-color", "#00CED1");
                row.Cells[2].Style.Add("background-color", "#00CED1");
                row.Cells[3].Style.Add("background-color", "#00CED1");
            }
        }
        GridView1.RenderControl(hw);
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }


    protected void btnExportToPDF_Click(object sender, EventArgs e)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=MyGridRecord.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        GridView1.DataBind();
        GridView1.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();
    }
}

  Comment:
         HOME   |   Submit Article   |   Contact Us   |   About Us   |   Terms & Condition   |   Advertise With us