Sunday, December 9, 2012

Export selected rows of gridview to Excel or word in ASP.Net

Introduction: 

Here I will explain how to export only selected or checked rows or records from gridview to Word or Excel sheet using asp.net.


Description:
. how to export gridview records to excel/word based on checkbox selection in gridview. To implement this one first design one table in database as shown below and give name as “UserInformation” 

ColumnName
DataType
UserId
Int(set identity property=true)
UserName
varchar(50)
LastName
varchar(50)
Location
varchar(50)

After completion of table creation enter some dummy data and design aspx page like this 


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Export Selected records from Gridview to Excel/ Word</title>
<style type="text/css">
.GridviewDiv {font-size100%font-family'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial,Helevetica, sans-serifcolor#303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em0.5em 0.5em 0.5em;text-align:center}
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em0.5em;}
.Gridview tr{colorBlackbackground-colorWhitetext-align:left}
:link,:visited { color#DF4F13text-decoration:none }
.highlight {text-decorationnone;color:black;background:yellow;}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td align="right">
<asp:ImageButton ID="btnExcel" runat="server" ImageUrl="~/ExcelImage.jpg"
onclick="btnExportExcel_Click" />
<asp:ImageButton ID="btnWord" runat="server" ImageUrl="~/WordImage.jpg"
onclick="btnWord_Click" />
</td>
</tr>
<tr>
<td>
<div class="GridviewDiv">
<asp:GridView ID="gvdetails" runat="server" AutoGenerateColumns="False" AllowPaging="True"
AllowSorting="true" Width="540px" PageSize="10" CssClass="Gridview" DataKeyNames="UserId"OnPageIndexChanging="gvdetails_PageIndexChanging" >
<HeaderStyle BackColor="#df5015" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UserId" HeaderText="UserId" />
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Now in code behind add following namespace references

using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
After that write the following code in code behind

C# Code




protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
/// <summary>
/// This Method is used to bind gridview
/// </summary>
private void BindGridData()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
SqlCommand cmd = new SqlCommand("select * from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdetails.DataSource = ds;
gvdetails.DataBind();
}
public override void VerifyRenderingInServerForm(Control control)
{
/*Verifies that the control is rendered */
}
protected void gvdetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
SaveCheckedValues();
gvdetails.PageIndex = e.NewPageIndex;
BindGridData();
PopulateCheckedValues();
}
/// <summary>
/// This event is used to export gridview data to Excel document
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnExportExcel_Click(object sender, EventArgs e)
{
ExportFunction("attachment;filename=GridViewExport.xls""application/vnd.ms-excel");
}
/// <summary>
/// This event is used to export gridview data to word document
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnWord_Click(object sender, EventArgs e)
{
ExportFunction("attachment;filename=GridViewExport.doc""application/vnd.ms-word");
}
/// <summary>
/// This Function is used to generate Excel or word document with gridview checkbox selected values
/// </summary>
/// <param name="header"></param>
/// <param name="contentType"></param>
private void ExportFunction(string header, string contentType)
{
SaveCheckedValues();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", header);
Response.Charset = "";
Response.ContentType = contentType;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
BindGridData();
gvdetails.HeaderRow.Style.Add("background-color""#FFFFFF");
gvdetails.HeaderRow.Cells[0].Visible = false;
for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++)
{
gvdetails.HeaderRow.Cells[i].Style.Add("background-color""#df5015");
gvdetails.HeaderRow.Cells[i].Style.Add("color""#FFFFFF");
}
if (ViewState["CHECKED_ITEMS"] != null)
{
ArrayList CheckBoxArray = (ArrayList)ViewState["CHECKED_ITEMS"];
int rowIdx = 0;
for (int i = 0; i < gvdetails.Rows.Count; i++)
{
GridViewRow row = gvdetails.Rows[i];
row.Visible = false;
int index = (int)gvdetails.DataKeys[row.RowIndex].Value;
if (CheckBoxArray.Contains(index))
{
row.Visible = true;
row.Cells[0].Visible = false;
}
}
}
gvdetails.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.End();
}
/// <summary>
///This method is used to populate the saved checked status of checkbox values
/// </summary>
private void PopulateCheckedValues()
{
ArrayList userdetails = (ArrayList)ViewState["CHECKED_ITEMS"];
if (userdetails != null && userdetails.Count > 0)
{
foreach (GridViewRow gvrow in gvdetails.Rows)
{
int index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;
if (userdetails.Contains(index))
{
CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkSelect");
myCheckBox.Checked = true;
}
}
}
}
/// <summary>
/// This method is used to save the checkedstate of checkbox values
/// </summary>
private void SaveCheckedValues()
{
ArrayList userdetails = new ArrayList();
int index = -1;
foreach (GridViewRow gvrow in gvdetails.Rows)
{
index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;
bool result = ((CheckBox)gvrow.FindControl("chkSelect")).Checked;
// Check in the Session
if (ViewState["CHECKED_ITEMS"] != null)
userdetails = (ArrayList)ViewState["CHECKED_ITEMS"];
if (result)
{
if (!userdetails.Contains(index))
userdetails.Add(index);
}
else
userdetails.Remove(index);
}
if (userdetails != null && userdetails.Count > 0)
ViewState["CHECKED_ITEMS"] = userdetails;
}

After that run your application output would be like this

No comments:

Post a Comment