Wednesday, 1 May 2013

Export Selected GridView Rows To Excel

http://rameshtalla.files.wordpress.com/2012/02/exportselectedgridviewrowstoexcel.png?w=511&h=309
In The Source Code:
<%@ Page Language=”C#” AutoEventWireup=”true”  EnableEventValidation=”false” EnableViewState=”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”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title>Export GridView To Excel Example</title>
<link href=”StyleSheet.css” rel=”stylesheet” type=”text/css” />
<style type=”text/css”>
.style1
{
width: 55%;
}
.style2
{
width: 184px;
}
</style>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ runat=”server” AllowPaging=”True”
DataSourceID=”sqlDataSourceGridView”
DataKeyNames=”CustomerID”
AutoGenerateColumns=”False”
onpageindexchanging=”GridView1_PageIndexChanging”
onrowdatabound=”GridView1_RowDataBound” CellPadding=”4″
ForeColor=”#333333″ GridLines=”None” >
<RowStyle BackColor=”#EFF3FB” />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID=”chkSelect” runat=”server” />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Customer ID”>
<ItemTemplate>
<asp:LinkButton ID=”lButton” runat=”server”
Text=’<%#Eval(“CustomerID”) %>’
PostBackUrl=”~/Default.aspx” >
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=”CompanyName” HeaderText=”Company”>
</asp:BoundField>
<asp:BoundField DataField=”ContactName” HeaderText=”Name”>
</asp:BoundField>
<asp:BoundField DataField=”City” HeaderText=”city”>
</asp:BoundField>
<asp:BoundField DataField=”Country” HeaderText=”Country” />
</Columns>
<FooterStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
<PagerStyle BackColor=”#2461BF” ForeColor=”White” HorizontalAlign=”Center” />
<SelectedRowStyle BackColor=”#D1DDF1″ Font-Bold=”True” ForeColor=”#333333″ />
<HeaderStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
<EditRowStyle BackColor=”#2461BF” />
<AlternatingRowStyle BackColor=”White” />
</asp:GridView>
<asp:SqlDataSource ID=”sqlDataSourceGridView” runat=”server”
ConnectionString=”<%$ ConnectionStrings:northWindConnectionString %>”
SelectCommand=”SELECT [CustomerID], [CompanyName], [ContactName],
[City], [Country] FROM [Customers]“>
</asp:SqlDataSource>
<asp:Button ID=”btnExportToExcel” runat=”server”
Text=”Export To Excel”
onclick=”btnExportToExcel_Click”/>
</div>
</form>
</body>
</html>
In The Code Behind Window:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void FindCheckedRows()
{
ArrayList checkedRowsList;
if (ViewState["checkedRowsList"] != null)
{
checkedRowsList = (ArrayList)ViewState["checkedRowsList"];
}
else
{
checkedRowsList = new ArrayList();
}
foreach (GridViewRow gvRow in GridView1.Rows)
{
if (gvRow.RowType == DataControlRowType.DataRow)
{
string rowIndex = Convert.ToString(GridView1.DataKeys[gvRow.RowIndex]["CustomerID"]);
CheckBox chkSelect = (CheckBox)gvRow.FindControl(“chkSelect”);
if ((chkSelect.Checked) && (!checkedRowsList.Contains(rowIndex)))
{
checkedRowsList.Add(rowIndex);
}
else if ((!chkSelect.Checked) && (checkedRowsList.Contains(rowIndex)))
{
checkedRowsList.Remove(rowIndex);
}
}
}
ViewState["checkedRowsList"] = checkedRowsList;
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
FindCheckedRows();
GridView1.ShowHeader = true;
GridView1.GridLines = GridLines.Both;
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Cells.RemoveAt(0);
if (ViewState["checkedRowsList"] != null)
{
ArrayList checkedRowsList = (ArrayList)ViewState["checkedRowsList"];
foreach (GridViewRow gvRow in GridView1.Rows)
{
gvRow.Visible = false;
if (gvRow.RowType == DataControlRowType.DataRow)
{
string rowIndex = Convert.ToString(GridView1.DataKeys[gvRow.RowIndex]["CustomerID"]);
if(checkedRowsList.Contains(rowIndex))
{
gvRow.Visible = true;
gvRow.Cells[0].Visible = false;
}
}
}
}
ChangeControlsToValue(GridView1);
Response.ClearContent();
Response.AddHeader(“content-disposition”, “attachment; filename=GridViewToExcel.xls”);
Response.ContentType = “application/excel”;
StringWriter sWriter = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
HtmlForm hForm = new HtmlForm();
GridView1.Parent.Controls.Add(hForm);
hForm.Attributes["runat"] = “server”;
hForm.Controls.Add(GridView1);
hForm.RenderControl(hTextWriter);
Response.Write(sWriter.ToString());
Response.End();
}
private void ChangeControlsToValue(Control gridView)
{
Literal literal = new Literal();
for (int i = 0; i < gridView.Controls.Count; i++)
{
if (gridView.Controls[i].GetType() == typeof(LinkButton))
{
literal.Text = (gridView.Controls[i] as LinkButton).Text;
gridView.Controls.Remove(gridView.Controls[i]);
gridView.Controls.AddAt(i,literal);
}
else if (gridView.Controls[i].GetType() == typeof(DropDownList))
{
literal.Text = (gridView.Controls[i] as DropDownList).SelectedItem.Text;
gridView.Controls.Remove(gridView.Controls[i]);
gridView.Controls.AddAt(i,literal);
}
else if (gridView.Controls[i].GetType() == typeof(CheckBox))
{
literal.Text = (gridView.Controls[i] as CheckBox).Checked ? “True” : “False”;
gridView.Controls.Remove(gridView.Controls[i]);
gridView.Controls.AddAt(i,literal);
}
if (gridView.Controls[i].HasControls())
{
ChangeControlsToValue(gridView.Controls[i]);
}
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
FindCheckedRows();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (ViewState["checkedRowsList"] != null)
{
ArrayList checkedRowsList = (ArrayList)ViewState["checkedRowsList"];
GridViewRow gvRow = e.Row;
if (gvRow.RowType == DataControlRowType.DataRow)
{
CheckBox chkSelect = (CheckBox)gvRow.FindControl(“chkSelect”);
string rowIndex = Convert.ToString(GridView1.DataKeys[gvRow.RowIndex]["CustomerID"]);
if(checkedRowsList.Contains(rowIndex))
{
chkSelect.Checked = true;
}
}
}
}
}

No comments:

Post a Comment