19 Feb 2014

print gridview data in asp.net using c# (or) export gridview to word/excel/pdf/csv in asp.net

In this post I Explained about exporting gridview data to the word or excel format. You can down load the complete grid view data on clicking the image button in the figure.




.Aspx Code :

  <form id="form1" runat="server">
    <div>&nbsp&nbsp&nbsp&nbsp
        <asp:ImageButton ID="ImgBtnBack" runat="server" ImageUrl="~/images/back.png" OnClick="ImgBtnBack_Click" />
        <asp:ImageButton ID="ImgBtnPrint" runat="server" ImageUrl="~/images/print01.png" /> &nbsp&nbsp&nbsp&nbsp
        <asp:ImageButton ID="ImgBtnWord" runat="server" ImageUrl="~/images/Word01.png" OnClick="ImgBtnWord_Click" /> &nbsp&nbsp&nbsp&nbsp
        <asp:ImageButton ID="ImgBtnExcel" runat="server" ImageUrl="~/images/Excel01.png" OnClick="ImgBtnExcel_Click" />
    </div>
    <div id="VQGridView">
        <asp:GridView ID="GridViewResult" runat="server" HorizontalAlign="Center"
            GridLines="None" Width="200%"
            CssClass="pnl-div" EmptyDataText="No Records Avaialable.."  >
            <FooterStyle BackColor="" Font-Bold="true" ForeColor="" />
            <RowStyle BackColor="#FFFFFF" HorizontalAlign="Left" />
            <EditRowStyle BackColor="" Width="100%" />
            <SelectedRowStyle BackColor="" Font-Bold="true" ForeColor="" />
            <PagerStyle BackColor="" ForeColor="" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#17C5F7" ForeColor="#FFFFFF" Font-Bold="true" HorizontalAlign="Left" />
            <AlternatingRowStyle BackColor="#B6EEFF" />
        </asp:GridView>
    </div>
    </form>

.CS Page code :

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.IO;
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;

namespace company
{
    public partial class QueryResult : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string UNAME = Convert.ToString(Session["USER_NAME"]);

            string printScript =
            @"function PrintGridView()
            {
            var gridInsideDiv = document.getElementById('VQGridView');
            var printWindow = window.open('VQGridView.htm','PrintWindow','letf=0,top=0,width=1000,height=700,toolbar=1,scrollbars=1,status=1');
            printWindow.document.write(gridInsideDiv.innerHTML);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();}";
            this.ClientScript.RegisterStartupScript(Page.GetType(), "PrintGridView", printScript.ToString(), true);
            ImgBtnPrint.Attributes.Add("onclick", "PrintGridView();");

           
            SqlConnection cn = new SqlConnection();
            cn.ConnectionString = ConfigurationManager.ConnectionStrings["connecton string here"].ConnectionString;
            cn.Open();
            string QUERY = " Your Sql Query";
            DataTable dt = new DataTable();
            SqlDataAdapter adp = new SqlDataAdapter(QUERY, cn);
            adp.Fill(dt);
            GridViewResult.DataSource = dt;
            GridViewResult.DataBind();
            cn.Close();
        }

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

        protected void ImgBtnWord_Click(object sender, ImageClickEventArgs e)
        {
            GridViewResult.AllowPaging = false;
            GridViewResult.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Visitors.doc"));
            Response.Charset = "";
            Response.ContentType = "application/ms-word";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            GridViewResult.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }

        protected void ImgBtnExcel_Click(object sender, ImageClickEventArgs e)
        {
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Visitors.xls"));
            Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            GridViewResult.AllowPaging = false;
            GridViewResult.DataBind();
            //Change the Header Row back to white color
            GridViewResult.HeaderRow.Style.Add("background-color", "#FFFFFF");
            //Applying stlye to gridview header cells
            for (int i = 0; i < GridViewResult.HeaderRow.Cells.Count; i++)
            {
                GridViewResult.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
            }
            int j = 1;
            //This loop is used to apply stlye to cells based on particular row
            foreach (GridViewRow gvrow in GridViewResult.Rows)
            {
                //gvrow.BackColor = Color.White;
                if (j <= GridViewResult.Rows.Count)
                {
                    if (j % 2 != 0)
                    {
                        for (int k = 0; k < gvrow.Cells.Count; k++)
                        {
                            gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
                        }
                    }
                }
                j++;
            }
            GridViewResult.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }

        protected void ImgBtnBack_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("back.aspx");
        }
    }

}

2 comments:

  1. Some SEO companies may only offer basic professional SEO services.
    Furthermore, a keyword should never feel like it is forced awkwardly to fit
    into content. You need to check that they are qualified accountants as many will not be.

    ReplyDelete
  2. This gives a website web presence and it gives you a major advantage over your competition. Furthermore,
    a keyword should never feel like it is forced awkwardly to fit into content.
    By using a service that can provide you will all of the
    various choices, you will save time and money getting online and noticed.

    ReplyDelete