ASP.Net GridView Export only selected columns to Excel Sheet
In this article I will describe how to export only those columns in ASP.Net GridView control that are selected or checked by the user.
HTML Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExportToExcel.aspx.cs" enableEventValidation ="false" Inherits="ExcelApplication.ExportToExcel" ValidateRequest = "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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Font-Names="Arial"
Font-Size="11pt" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="green"
AllowPaging="true" OnPageIndexChanging="OnPaging">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkCol0" runat="server" Checked="true" />
<asp:Label ID="lblCol0" runat="server" Text="CustomerID" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblCustomerID" runat="server" Text='<%# Eval("CustomerID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkCol1" runat="server" Checked="true" />
<asp:Label ID="lblCol1" runat="server" Text="ContactName" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblContactName" runat="server" Text='<%# Eval("ContactName")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkCol2" runat="server" Checked="true" />
<asp:Label ID="lblCol2" runat="server" Text="City"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView></div>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Export To Excel" />
</form>
</body>
</html>
Designer File :
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ExcelApplication {
public partial class ExportToExcel {
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// GridView1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView GridView1;
/// <summary>
/// Button1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button1;
}
}
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace ExcelApplication
{
public partial class ExportToExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
GetCheckBoxStates();
BindGrid();
}
//Exporting the GridView with selected columns to Excel Sheet
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition","attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
ArrayList arr = (ArrayList)ViewState["States"];
GridView1.HeaderRow.Cells[0].Visible = Convert.ToBoolean(arr[0]);
GridView1.HeaderRow.Cells[1].Visible = Convert.ToBoolean(arr[1]);
GridView1.HeaderRow.Cells[2].Visible = Convert.ToBoolean(arr[2]);
GridView1.HeaderRow.Cells[0].FindControl("chkCol0").Visible = false;
GridView1.HeaderRow.Cells[1].FindControl("chkCol1").Visible = false;
GridView1.HeaderRow.Cells[2].FindControl("chkCol2").Visible = false;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
row.Cells[0].Visible = Convert.ToBoolean(arr[0]);
row.Cells[1].Visible = Convert.ToBoolean(arr[1]);
row.Cells[2].Visible = Convert.ToBoolean(arr[2]);
row.BackColor = System.Drawing.Color.White;
row.Attributes.Add("class", "textmode");
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
//You’ll notice I am calling one more function GetCheckBoxStates() in the Page Load event of the Page.
//The job of this function is to maintain the states of the GridView header checkboxes in ViewState.
//The function is described below
private void GetCheckBoxStates()
{
CheckBox chkCol0 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol0");
CheckBox chkCol1 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol1");
CheckBox chkCol2 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol2");
ArrayList arr;
if (ViewState["States"] == null)
{
arr = new ArrayList();
}
else
{
arr = (ArrayList)ViewState["States"];
}
arr.Add(chkCol0.Checked);
arr.Add(chkCol1.Checked);
arr.Add(chkCol2.Checked);
ViewState["States"] = arr;
}
//Binding Data
private void BindGrid()
{
string strQuery = "select CustomerID,City,ContactName from customers";
DataTable dt = new DataTable();
String strConnString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand(strQuery);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
//Call when page index changed
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}
}
}
Database
I am using Microsoft’s Northwind Sample Database for this article. You can download the same using the link below
Download Northwind DatabaseHTML Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExportToExcel.aspx.cs" enableEventValidation ="false" Inherits="ExcelApplication.ExportToExcel" ValidateRequest = "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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Font-Names="Arial"
Font-Size="11pt" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="green"
AllowPaging="true" OnPageIndexChanging="OnPaging">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkCol0" runat="server" Checked="true" />
<asp:Label ID="lblCol0" runat="server" Text="CustomerID" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblCustomerID" runat="server" Text='<%# Eval("CustomerID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkCol1" runat="server" Checked="true" />
<asp:Label ID="lblCol1" runat="server" Text="ContactName" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblContactName" runat="server" Text='<%# Eval("ContactName")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkCol2" runat="server" Checked="true" />
<asp:Label ID="lblCol2" runat="server" Text="City"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView></div>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Export To Excel" />
</form>
</body>
</html>
Designer File :
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ExcelApplication {
public partial class ExportToExcel {
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// GridView1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView GridView1;
/// <summary>
/// Button1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button1;
}
}
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace ExcelApplication
{
public partial class ExportToExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
GetCheckBoxStates();
BindGrid();
}
//Exporting the GridView with selected columns to Excel Sheet
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition","attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
ArrayList arr = (ArrayList)ViewState["States"];
GridView1.HeaderRow.Cells[0].Visible = Convert.ToBoolean(arr[0]);
GridView1.HeaderRow.Cells[1].Visible = Convert.ToBoolean(arr[1]);
GridView1.HeaderRow.Cells[2].Visible = Convert.ToBoolean(arr[2]);
GridView1.HeaderRow.Cells[0].FindControl("chkCol0").Visible = false;
GridView1.HeaderRow.Cells[1].FindControl("chkCol1").Visible = false;
GridView1.HeaderRow.Cells[2].FindControl("chkCol2").Visible = false;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
row.Cells[0].Visible = Convert.ToBoolean(arr[0]);
row.Cells[1].Visible = Convert.ToBoolean(arr[1]);
row.Cells[2].Visible = Convert.ToBoolean(arr[2]);
row.BackColor = System.Drawing.Color.White;
row.Attributes.Add("class", "textmode");
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
//You’ll notice I am calling one more function GetCheckBoxStates() in the Page Load event of the Page.
//The job of this function is to maintain the states of the GridView header checkboxes in ViewState.
//The function is described below
private void GetCheckBoxStates()
{
CheckBox chkCol0 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol0");
CheckBox chkCol1 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol1");
CheckBox chkCol2 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol2");
ArrayList arr;
if (ViewState["States"] == null)
{
arr = new ArrayList();
}
else
{
arr = (ArrayList)ViewState["States"];
}
arr.Add(chkCol0.Checked);
arr.Add(chkCol1.Checked);
arr.Add(chkCol2.Checked);
ViewState["States"] = arr;
}
//Binding Data
private void BindGrid()
{
string strQuery = "select CustomerID,City,ContactName from customers";
DataTable dt = new DataTable();
String strConnString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand(strQuery);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
//Call when page index changed
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}
}
}
As you’ll notice above everything is same as the normal GridView to Excel export the only difference is that I am hiding the GridView cells based on the values of their respective checkboxes in the Header row
ASP.Net GridView with ability to select/unselect columns
Exported Excel sheet with selected columns
Hope this will help you.......
Ref: try this link
Please explain how this work in Excel 2010 (xlsx)
ReplyDeleteExport gridview data to pdf file in .net application
ReplyDeleteExport gridview data to pdf file in .net application
ReplyDeleteI really enjoy your blog it's a nice post
ReplyDelete.Net Online Training Bangalore
https://bayanlarsitesi.com/
ReplyDeleteTokat
Kastamonu
Tekirdağ
Gümüşhane
YKL
Denizli
ReplyDeleteKonya
Denizli
ısparta
Bayburt
O4W
bitlis
ReplyDeletesakarya
van
tunceli
ankara
S0ROP
van
ReplyDeleteerzincan
sivas
ağrı
manisa
İJ7
Malatya Lojistik
ReplyDeleteAntep Lojistik
Urfa Lojistik
Sivas Lojistik
Erzurum Lojistik
8CMPAF
van evden eve nakliyat
ReplyDeletesivas evden eve nakliyat
çankırı evden eve nakliyat
bartın evden eve nakliyat
erzincan evden eve nakliyat
YİDKJP
5012D
ReplyDeleteMardin Lojistik
İzmir Evden Eve Nakliyat
Kırıkkale Evden Eve Nakliyat
Nevşehir Evden Eve Nakliyat
Konya Parça Eşya Taşıma
687D5
ReplyDeleteAdıyaman Evden Eve Nakliyat
Muş Lojistik
Yalova Parça Eşya Taşıma
Trabzon Lojistik
Rize Lojistik
AB871
ReplyDeleteBitfinex Güvenilir mi
Bitcoin Nasıl Alınır
Çanakkale Parça Eşya Taşıma
Mercatox Güvenilir mi
Antalya Parça Eşya Taşıma
Balıkesir Şehirler Arası Nakliyat
Diyarbakır Evden Eve Nakliyat
Ardahan Lojistik
Ünye Organizasyon
2D457
ReplyDeleteBitexen Güvenilir mi
Kırklareli Lojistik
Yenimahalle Parke Ustası
Ünye Oto Boya
Btcturk Güvenilir mi
Bursa Evden Eve Nakliyat
Çerkezköy Evden Eve Nakliyat
Manisa Şehir İçi Nakliyat
Bayburt Evden Eve Nakliyat
783EF
ReplyDeletesamsun sesli sohbet mobil
hakkari parasız görüntülü sohbet
ücretsiz sohbet siteleri
zonguldak canlı sohbet sitesi
ığdır Sohbet Odaları
mobil sohbet sitesi
Şırnak Yabancı Görüntülü Sohbet Uygulamaları
en iyi rastgele görüntülü sohbet
trabzon kadınlarla ücretsiz sohbet
14770
ReplyDeleteSui Coin Hangi Borsada
Binance Sahibi Kim
Kripto Para Madenciliği Nedir
Görüntülü Sohbet
Bonk Coin Hangi Borsada
Bitcoin Nasıl Kazılır
Coin Para Kazanma
Clysterum Coin Hangi Borsada
Tiktok İzlenme Satın Al