Tuesday 23 July 2013

How to Export GridView Row or Record to MSExcel or ExcelSheet in Asp.Net



Description:-

In this Example we Explain That how to export Gridview rows or Record to the Microsoft Excel Document when Click on Export or Image of Excel.or export selected or checked rows from gridview to Excel sheet without using any third party control in asp.net.

If you  exporting the document to Excel directly as done in case of word the row background color is automatically  applied throughout to all the columns in the Excel Sheet.so this reason we have to avoid it.
First I am manually changing the background color of each row of the exported rows of gridview black to white.

second we are applying the background color to each individual cell of the Gridview rather than the whole row. because when you export rows you will notice that the formatting is applied only to the GridView’s cells and not all.

Also I am applying textmode style class to all cells of the Grid and then adding the style CSS class to the GridView before rendering it to the Excel or word or pdf document.

This is very useful when we have to generally Create a Report or you can Directally print the Document. In this Example when user click on the Image of Excel at that All Gridview Record are Exported to the Excel Document with same Look and same color as in Gridview.

you have set ContentType of the page Before sending or Exporting data to ExcelSheet like



Response.ContentType = "application/vnd.xls";


you can also Export your Gridview to Word or PDF to show this Example please click below link.



Export Gridview to PDF :-   Gridview to PDF

To show Example of Rotate the Ads or Advertised in Webpage Rotate Ads without Refreshing Webpage

Enter only Ahpabet in TextBox validation input only Alphabet in TextBox

word.aspx:-





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



<!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 id="Head1" runat="server">

<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table border="1" id="tb" runat="server">
<tr>
<td>

<asp:ImageButton ID="btnWord" runat="server" ImageUrl="~/WordImage.jpg"
onclick="btnWord_Click" />
</td>
    <td>

<asp:ImageButton ID="btnExcel" runat="server" ImageUrl="~/index.jpg" Width="20"
onclick="btnexcel_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView runat="server" ID="gvdetails"   AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="id" HeaderText="UserId" />
<asp:BoundField DataField="FirstName" HeaderText="UserName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="age" HeaderText="age" />
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

word.aspx.cs:-  



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Web.UI.HtmlControls;


public partial class word : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            grid();
        }

    }
    public void grid()
    {
        DataSet ds = new DataSet();

        string con = @"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demoh;Password=Demo1@";

        string q = "select * from tierword";

        SqlConnection conn = new SqlConnection(con);

        SqlCommand cmd = new SqlCommand(q, conn);



        SqlDataAdapter sa = new SqlDataAdapter();
        conn.Open();
        cmd.ExecuteNonQuery();
        sa.SelectCommand = cmd;
        sa.Fill(ds);
        gvdetails.DataSource = ds;
        gvdetails.DataBind();

    }

    public override void VerifyRenderingInServerForm(Control control)
    {

        /* Verifies that the control is rendered */

    }
    protected void btnexcel_Click(object sender, ImageClickEventArgs e)
    {
       try
        {
             Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
            Response.Charset = "";
          
            Response.ContentType = "application/vnd.xls";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
             gvdetails.RenderControl(htmlWrite);
             Response.Write(stringWrite.ToString());
            Response.End();
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message + "')</script>");
        }
    


    }
}

 

0 comments:

Post a Comment