Skip to main content

How to export any gridview to excel, doc, pdf, csv

Hello friend here you can find the example how to export any gridview to excel, doc, pdf, csv


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

<!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>GridView Export</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
<asp:GridView ID="GridView1" runat="server" 
        AutoGenerateColumns = "false" Font-Names = "Arial" 
        Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"  
        HeaderStyle-BackColor = "green" AllowPaging ="true"   
        OnPageIndexChanging = "OnPaging" >
        <Columns>
                <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
                    SortExpression="id" />
                <asp:BoundField DataField="title" HeaderText="title" />
                <asp:BoundField DataField="description" HeaderText="description" />
                <asp:BoundField DataField="status" HeaderText="status" />
            </Columns>
    </asp:GridView>
    </div>
        <br />
        <asp:Button ID="btnExportWord" runat="server" Text="ExportToWord" OnClick="btnExportWord_Click" />
        &nbsp;
        <asp:Button ID="btnExportExcel" runat="server" Text="ExportToExcel" OnClick="btnExportExcel_Click" />
        &nbsp;
        <asp:Button ID="btnExportPDF" runat="server" Text="ExportToPDF" OnClick="btnExportPDF_Click" />
         &nbsp;
        <asp:Button ID="Button1" runat="server" Text="ExportToCSV" OnClick="btnExportCSV_Click" />
    </form>
</body>
</html>


-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.Text;

public partial class CSharp : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string strQuery = "SELECT * FROM [servicespage]";
        SqlCommand cmd = new SqlCommand(strQuery);
        DataTable dt = GetData(cmd);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    private DataTable GetData(SqlCommand cmd)
    {
        DataTable dt = new DataTable();
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["export_to_excelConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        SqlDataAdapter sda = new SqlDataAdapter();
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        try
        {
            con.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);
            return dt;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            sda.Dispose();
            con.Dispose();
        }
    }
   

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
    protected void OnPaging(object sender, GridViewPageEventArgs  e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataBind();  
    }

    protected void btnExportWord_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.doc");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-word ";
        StringWriter sw= new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        GridView1.DataBind(); 
        GridView1.RenderControl(hw);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }

    protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
       
        Response.AddHeader("content-disposition", 
         "attachment;filename=GridViewExport.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", "green");
        GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
        GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
        GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");   

        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", "#C2D69B");
                row.Cells[1].Style.Add("background-color", "#C2D69B");
                row.Cells[2].Style.Add("background-color", "#C2D69B");
                row.Cells[3].Style.Add("background-color", "#C2D69B");   
            }
        }
        GridView1.RenderControl(hw);

        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>"; 
        Response.Write(style); 
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }

    protected void btnExportPDF_Click(object sender, EventArgs e)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.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();  
    }
    protected void btnExportCSV_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.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++)
        {
            //add separator
            sb.Append(GridView1.Columns[k].HeaderText + ',');
        }
        //append new line
        sb.Append("\r\n");
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            for (int k = 0; k < GridView1.Columns.Count; k++)
            {
                //add separator
                sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
            }
            //append new line
            sb.Append("\r\n");
        }
        Response.Output.Write(sb.ToString());
        Response.Flush();
        Response.End();
    }
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

To check the online demo 

please check the following link : http://www.aspsnippets.com/Demos/16/

To Download the source code: https://docs.google.com/file/d/0B45Hpp8-i2BcVjNZSVl5NGFSYlE/edit?usp=sharing



Comments

Popular posts from this blog

10 jQuery Custom Scrollbar Plugins

10 jQuery Custom Scrollbar Plugins If you ever wanted to add some custom scrollbars to your website, to scroll the contents and the default browser scrollbars just doesn’t match up with your design, than make sure you check this list of 10 jQuery custom scrollbar plugins. Hope you find the following information helpful. 1. jScrollPane – custom cross-browser scrollbars Kelvin Luck’s jScrollPane was originally developed in December 2006. It is a jQuery plugin which provides you with custom scrollbars which work consistently across all modern browsers. You can style the scrollbars using simple CSS and they degrade gracefully where JavaScript is disabled. 2. Plugin JQuery : Scrollbar This page is written in french so use Google’s translate service to translate this page to your preferred language. Download is available for the plugin.  The purpose of this plugin is to add a scrollbar to the item of your choice, to view any content which is larger than the size – vizible sp

connect ftp with gridview / display files in gridview from ftp or server

HTML Markup Below is the HTML Markup of the page, where I have an ASP.Net control  FileUpload  to upload files, a  Button control to trigger file uploads and an ASP.Net GridView control to display the files from folder. < asp : FileUpload   ID ="FileUpload1"   runat ="server"   /> < asp : Button   ID ="btnUpload"   runat ="server"   Text ="Upload"   OnClick ="UploadFile"   /> < hr   /> < asp : GridView   ID ="GridView1"   runat ="server"   AutoGenerateColumns ="false"   EmptyDataText   =   "No files uploaded">      < Columns >          < asp : BoundField   DataField ="Text"   HeaderText ="File Name"   />          < asp : TemplateField >              < ItemTemplate >                  < asp : LinkButton   ID ="lnkDownload"   Text   =   "Download"   CommandArgument   =   ' &

Working with Ajax UpdatePanel in asp.net

During work with our applications if we entered any values in textbox controls and click on a button in form we will see full postback of our page and we will lost all the controls values whatever we entered previously this happend because of postback. If we want to avoid this full postback of page and round trip to server we need to write much code instead of writing much code we can use ajax updatepanel control. Ajax updatepanel will help us to avoid full postback of the page i.e., avoid refresh of the whole page content with postback and stop flickering of the page which is associated with a postback and allows only partial postbacks. By using Ajax updatepanel we can refresh only required part of page instead of refreshing whole page. Ajax updatepanel works on very smooth concepts. but in some cases we got stuck while using Ajax updatepanel. But you need not to worry. Here i am showing you how to resolve the issues for different cases Lets start with very basic use of A