Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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;
usingSystem.Collections;
usingSystem.Configuration;
usingSystem.Data;
usingSystem.Data.SqlClient;
usingSystem.Linq;
usingSystem.Web;
using System.IO;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.HtmlControls;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Xml.Linq;

namespacecompany
{
    public partial class QueryResult : System.Web.UI.Page
    {
        protectedvoid Page_Load(objectsender, EventArgs e)
        {
            stringUNAME = Convert.ToString(Session["USER_NAME"]);

            stringprintScript =
            @"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();");

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

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

        protectedvoid ImgBtnWord_Click(objectsender, 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";
            StringWritersw = new StringWriter();
            HtmlTextWriterhtw = new HtmlTextWriter(sw);
            GridViewResult.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }

        protectedvoid ImgBtnExcel_Click(objectsender, ImageClickEventArgs e)
        {
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Visitors.xls"));
            Response.ContentType = "application/ms-excel";
            StringWritersw = new StringWriter();
            HtmlTextWriterhtw = 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");
            }
            intj = 1;
            //This loop is used to apply stlye to cells based on particular row
            foreach(GridViewRow gvrow inGridViewResult.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();
        }

        protectedvoid ImgBtnBack_Click(objectsender, ImageClickEventArgs e)
        {
            Response.Redirect("back.aspx");
        }
    }

}


This post first appeared on Asp.netSourceCodes, please read the originial post: here

Share the post

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

×

Subscribe to Asp.netsourcecodes

Get updates delivered right to your inbox!

Thank you for your subscription

×