Actually I have made a gridview control in a class library through which I use to generate a dll and that I am including in my application where ever I need to use that grid.
So in this case I want to implement export to excel option to my control. Below code shows my created grid control.
using System;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace IBControl
{
[Themeable(true)]
[DefaultProperty("Text")]
[ToolboxData("<{0}:IBGrid runat=server></{0}:IBGrid>"),
DisplayName("IBGrid"),
Description("A GridView control with DropDownList and Buttons in its Pager.")]
public class Class1
{
}
public class IBGrid : GridView
{
[Category("Paging")]
[DefaultValue("1")]
public ThisPagerType PagerType
{
get
{
return (ViewState["PagerType"] != null ? (ThisPagerType)ViewState["PagerType"] : ThisPagerType.DropDownList);
}
set
{
ViewState["PagerType"] = value;
}
}
public enum ThisPagerType
{
Regular = 0,
DropDownList = 1,
}
protected override void InitializePager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource)
{
if (PagerType == ThisPagerType.Regular)
{
// if PagerType is not DropDownList
// render the regular GridView Pager
base.InitializePager(row, columnSpan, pagedDataSource);
}
else
{
TableCell cell_1;
// if we are going to use dropdownlist
// our Pager with DropDownList control
// create our DropDownList control
DropDownList ddl = new DropDownList();
// populate it with the number of Pages of our GridView
for (int i = 0; i < PageCount; i++)
{
ddl.Items.Add(new ListItem(Convert.ToString(i + 1), i.ToString()));
}
ddl.AutoPostBack = true;
// assign an Event Handler when its Selected Index Changed
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
// synchronize its selected index to GridView's current PageIndex
ddl.SelectedIndex = PageIndex;
//LinkButton first = new LinkButton();
Button first = new Button();
first.Text = "First ";
// first button will always have a value of zero (0)
first.CommandArgument = "0";
first.Enabled = PageIndex > 0;
// add click event handler
first.Click += new EventHandler(navigate_Click);
//LinkButton prev = new LinkButton();
Button prev = new Button();
prev.Text = "Prev ";
// set Prev button argument's to current PageIndex minus 1
prev.CommandArgument = string.Format("{0}", (PageIndex - 1));
prev.Enabled = (PageIndex > 0);
prev.Click += new EventHandler(navigate_Click);
//LinkButton next = new LinkButton();
Button next = new Button();
next.Text = "Next ";
// set Next button argument's to current PageIndex plus 1
next.CommandArgument = string.Format("{0}", (PageIndex + 1));
next.Enabled = (PageIndex < (PageCount - 1));
next.Click += new EventHandler(navigate_Click);
//LinkButton last = new LinkButton();
Button last = new Button();
last.Text = "Last";
// Last button will always have a value equal to PageCount minus 1
last.CommandArgument = string.Format("{0}", (PageCount - 1));
last.Enabled = (PageIndex < (PageCount - 1));
last.Click += new EventHandler(navigate_Click);
Label lblnx = new Label();
Label lblpr = new Label();
lblnx.Text = " ";
lblpr.Text = " ";
// add our first TableCell which will contain the DropDownList
cell_1 = new TableCell();
// we just add a Label with 'Page ' Text
cell_1.Controls.Add(first);
cell_1.Controls.Add(prev);
cell_1.Controls.Add(lblnx);
cell_1.Controls.Add(PageOf());
// our DropDownList control here.
cell_1.Controls.Add(ddl);
// and our Total number of Pages
cell_1.Controls.Add(PageTotal());
cell_1.Controls.Add(lblpr);
cell_1.Controls.Add(next);
cell_1.Controls.Add(last);
// create a Table that will replace entirely our GridView's Pager section
Table tbl = new Table();
tbl.BorderWidth = 0;
tbl.Width = Unit.Percentage(100);
// add one TableRow to our Table
tbl.Rows.Add(new TableRow());
// the 2nd TableCell will display the Record number you are currently in.
TableCell cell_2 = new TableCell();
cell_2.Controls.Add(PageInfo(pagedDataSource.DataSourceCount));
// add now the 2 cell to our created row
tbl.Rows[0].Cells.Add(cell_1);
tbl.Rows[0].Cells.Add(cell_2);
// tbl.Rows[0].Cells.Add(cell_3);
tbl.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Left;
tbl.Rows[0].Cells[1].HorizontalAlign = HorizontalAlign.Center;
//tbl.Rows[0].Cells[2].HorizontalAlign = HorizontalAlign.Right;
// in Pager's Row of our GridView add a TableCell
row.Controls.AddAt(0, new TableCell());
// sets it span to GridView's number of columns
row.Cells[0].ColumnSpan = Columns.Count;
// finally add our created Table
row.Cells[0].Controls.AddAt(0, tbl);
}
}
protected virtual void navigate_Click(object sender, EventArgs e)
{
OnPageIndexChanging(new GridViewPageEventArgs(int.Parse(((Button)sender).CommandArgument)));
}
protected virtual void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
// on our DropDownList SelectedIndexChanged event
// call the GridView's OnPageIndexChanging method
// to raised the PageIndexChanging event.
// pass the DropDownList SelectedIndex as its argument.
OnPageIndexChanging(new GridViewPageEventArgs(((DropDownList)sender).SelectedIndex));
}
private Label PageOf()
{
// it is just a label
Label lbl = new Label();
lbl.Text = "Page ";
return lbl;
}
private Label PageTotal()
{
// a label of GridView's Page Count
Label lbl = new Label();
lbl.Text = string.Format(" of {0}", PageCount);
return lbl;
}
private Label PageInfo(int rowCount)
{
// create a label that will display the current Record you're in
Label label = new Label();
int currentPageFirstRow = ((PageIndex * PageSize) + 1);
int currentPageLastRow = 0;
int lastPageRemainder = rowCount % PageSize;
currentPageLastRow = (PageCount == PageIndex + 1) ? (currentPageFirstRow + lastPageRemainder - 1) : (currentPageFirstRow + PageSize - 1);
label.Text = String.Format("Record {0} to {1} of {2}", currentPageFirstRow, currentPageLastRow, rowCount);
return label;
}
protected override void Render(HtmlTextWriter writer)
{
// just a signature :) , has nothing to do with the functionality of the control.
System.Text.StringBuilder sb = new StringBuilder();
sb.AppendLine(("/").PadLeft(40, char.Parse("/")));
sb.AppendLine("/ ");
sb.Append(("GridEuo Control").PadRight(37, char.Parse(" ")));
sb.Append("/");
sb.AppendLine("/ ");
sb.Append(("Author: ").PadLeft(12, char.Parse(" ")));
sb.Append(("Manny Salazar").PadRight(25, char.Parse(" ")));
sb.Append("/");
sb.AppendLine("/ ");
sb.Append(("Email: ").PadLeft(12, char.Parse(" ")));
sb.Append(("mastereuo@yahoo.com").PadRight(25, char.Parse(" ")));
sb.Append("/");
sb.AppendLine("/ ");
sb.Append(("Date: ").PadLeft(12, char.Parse(" ")));
sb.Append(("2007.01.30").PadRight(25, char.Parse(" ")));
sb.Append("/");
sb.AppendLine("/ ");
sb.Append(("GridEuo Control").PadRight(37, char.Parse(" ")));
sb.Append("/");
sb.AppendLine(("/").PadLeft(40, char.Parse("/")));
writer.WriteBeginTag("!--");
writer.Write(sb.ToString());
writer.WriteEndTag("--");
base.Render(writer);
}
}
}
So in the above code I want to implement this. Please help me out on this.
If you want to integrate the function of exporting GridView to excel in your IBGrid you may need to add a button in it. You can add the button in the InitalizePager method. You can refer to the below code.
Button exportBtn = new Button();
exportBtn.Text = "ExportToExcel";
exportBtn.Click += new EventHandler(ExportToExcel_Click);
TableCell cell_export = new TableCell();
cell_export.Controls.Add(exportBtn);
tbl.Rows[0].Cells.Add(cell_export);
Then you can export to excel in the button click event. You can refer to the below code.
Furthermore, you should know the export button is in the same cell as the page index footer . In other words you need to set the page AllowPaging with true. You should set the page size with a small number to show the export button. It can be fixed by modifying
the structure of the InitializePager method. I just implement the function and you can changed it yourself.
You can refer to the Export To Excel control in the below link. It’s a custom control. Hope it can help you.
tripati_tutu
Member
30 Points
53 Posts
How to export gridview to excel in a console type application?
Feb 27, 2012 06:14 AM|LINK
Hi,
Actually I have made a gridview control in a class library through which I use to generate a dll and that I am including in my application where ever I need to use that grid.
So in this case I want to implement export to excel option to my control. Below code shows my created grid control.
using System; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace IBControl { [Themeable(true)] [DefaultProperty("Text")] [ToolboxData("<{0}:IBGrid runat=server></{0}:IBGrid>"), DisplayName("IBGrid"), Description("A GridView control with DropDownList and Buttons in its Pager.")] public class Class1 { } public class IBGrid : GridView { [Category("Paging")] [DefaultValue("1")] public ThisPagerType PagerType { get { return (ViewState["PagerType"] != null ? (ThisPagerType)ViewState["PagerType"] : ThisPagerType.DropDownList); } set { ViewState["PagerType"] = value; } } public enum ThisPagerType { Regular = 0, DropDownList = 1, } protected override void InitializePager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource) { if (PagerType == ThisPagerType.Regular) { // if PagerType is not DropDownList // render the regular GridView Pager base.InitializePager(row, columnSpan, pagedDataSource); } else { TableCell cell_1; // if we are going to use dropdownlist // our Pager with DropDownList control // create our DropDownList control DropDownList ddl = new DropDownList(); // populate it with the number of Pages of our GridView for (int i = 0; i < PageCount; i++) { ddl.Items.Add(new ListItem(Convert.ToString(i + 1), i.ToString())); } ddl.AutoPostBack = true; // assign an Event Handler when its Selected Index Changed ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged); // synchronize its selected index to GridView's current PageIndex ddl.SelectedIndex = PageIndex; //LinkButton first = new LinkButton(); Button first = new Button(); first.Text = "First "; // first button will always have a value of zero (0) first.CommandArgument = "0"; first.Enabled = PageIndex > 0; // add click event handler first.Click += new EventHandler(navigate_Click); //LinkButton prev = new LinkButton(); Button prev = new Button(); prev.Text = "Prev "; // set Prev button argument's to current PageIndex minus 1 prev.CommandArgument = string.Format("{0}", (PageIndex - 1)); prev.Enabled = (PageIndex > 0); prev.Click += new EventHandler(navigate_Click); //LinkButton next = new LinkButton(); Button next = new Button(); next.Text = "Next "; // set Next button argument's to current PageIndex plus 1 next.CommandArgument = string.Format("{0}", (PageIndex + 1)); next.Enabled = (PageIndex < (PageCount - 1)); next.Click += new EventHandler(navigate_Click); //LinkButton last = new LinkButton(); Button last = new Button(); last.Text = "Last"; // Last button will always have a value equal to PageCount minus 1 last.CommandArgument = string.Format("{0}", (PageCount - 1)); last.Enabled = (PageIndex < (PageCount - 1)); last.Click += new EventHandler(navigate_Click); Label lblnx = new Label(); Label lblpr = new Label(); lblnx.Text = " "; lblpr.Text = " "; // add our first TableCell which will contain the DropDownList cell_1 = new TableCell(); // we just add a Label with 'Page ' Text cell_1.Controls.Add(first); cell_1.Controls.Add(prev); cell_1.Controls.Add(lblnx); cell_1.Controls.Add(PageOf()); // our DropDownList control here. cell_1.Controls.Add(ddl); // and our Total number of Pages cell_1.Controls.Add(PageTotal()); cell_1.Controls.Add(lblpr); cell_1.Controls.Add(next); cell_1.Controls.Add(last); // create a Table that will replace entirely our GridView's Pager section Table tbl = new Table(); tbl.BorderWidth = 0; tbl.Width = Unit.Percentage(100); // add one TableRow to our Table tbl.Rows.Add(new TableRow()); // the 2nd TableCell will display the Record number you are currently in. TableCell cell_2 = new TableCell(); cell_2.Controls.Add(PageInfo(pagedDataSource.DataSourceCount)); // add now the 2 cell to our created row tbl.Rows[0].Cells.Add(cell_1); tbl.Rows[0].Cells.Add(cell_2); // tbl.Rows[0].Cells.Add(cell_3); tbl.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Left; tbl.Rows[0].Cells[1].HorizontalAlign = HorizontalAlign.Center; //tbl.Rows[0].Cells[2].HorizontalAlign = HorizontalAlign.Right; // in Pager's Row of our GridView add a TableCell row.Controls.AddAt(0, new TableCell()); // sets it span to GridView's number of columns row.Cells[0].ColumnSpan = Columns.Count; // finally add our created Table row.Cells[0].Controls.AddAt(0, tbl); } } protected virtual void navigate_Click(object sender, EventArgs e) { OnPageIndexChanging(new GridViewPageEventArgs(int.Parse(((Button)sender).CommandArgument))); } protected virtual void ddl_SelectedIndexChanged(object sender, EventArgs e) { // on our DropDownList SelectedIndexChanged event // call the GridView's OnPageIndexChanging method // to raised the PageIndexChanging event. // pass the DropDownList SelectedIndex as its argument. OnPageIndexChanging(new GridViewPageEventArgs(((DropDownList)sender).SelectedIndex)); } private Label PageOf() { // it is just a label Label lbl = new Label(); lbl.Text = "Page "; return lbl; } private Label PageTotal() { // a label of GridView's Page Count Label lbl = new Label(); lbl.Text = string.Format(" of {0}", PageCount); return lbl; } private Label PageInfo(int rowCount) { // create a label that will display the current Record you're in Label label = new Label(); int currentPageFirstRow = ((PageIndex * PageSize) + 1); int currentPageLastRow = 0; int lastPageRemainder = rowCount % PageSize; currentPageLastRow = (PageCount == PageIndex + 1) ? (currentPageFirstRow + lastPageRemainder - 1) : (currentPageFirstRow + PageSize - 1); label.Text = String.Format("Record {0} to {1} of {2}", currentPageFirstRow, currentPageLastRow, rowCount); return label; } protected override void Render(HtmlTextWriter writer) { // just a signature :) , has nothing to do with the functionality of the control. System.Text.StringBuilder sb = new StringBuilder(); sb.AppendLine(("/").PadLeft(40, char.Parse("/"))); sb.AppendLine("/ "); sb.Append(("GridEuo Control").PadRight(37, char.Parse(" "))); sb.Append("/"); sb.AppendLine("/ "); sb.Append(("Author: ").PadLeft(12, char.Parse(" "))); sb.Append(("Manny Salazar").PadRight(25, char.Parse(" "))); sb.Append("/"); sb.AppendLine("/ "); sb.Append(("Email: ").PadLeft(12, char.Parse(" "))); sb.Append(("mastereuo@yahoo.com").PadRight(25, char.Parse(" "))); sb.Append("/"); sb.AppendLine("/ "); sb.Append(("Date: ").PadLeft(12, char.Parse(" "))); sb.Append(("2007.01.30").PadRight(25, char.Parse(" "))); sb.Append("/"); sb.AppendLine("/ "); sb.Append(("GridEuo Control").PadRight(37, char.Parse(" "))); sb.Append("/"); sb.AppendLine(("/").PadLeft(40, char.Parse("/"))); writer.WriteBeginTag("!--"); writer.Write(sb.ToString()); writer.WriteEndTag("--"); base.Render(writer); } } }So in the above code I want to implement this. Please help me out on this.
Thanks.
Qi Wu - MSFT
Contributor
5794 Points
677 Posts
Re: How to export gridview to excel in a console type application?
Feb 29, 2012 08:00 AM|LINK
Hi,
If you want to integrate the function of exporting GridView to excel in your IBGrid you may need to add a button in it. You can add the button in the InitalizePager method. You can refer to the below code.
Button exportBtn = new Button(); exportBtn.Text = "ExportToExcel"; exportBtn.Click += new EventHandler(ExportToExcel_Click); TableCell cell_export = new TableCell(); cell_export.Controls.Add(exportBtn); tbl.Rows[0].Cells.Add(cell_export);Then you can export to excel in the button click event. You can refer to the below code.
protected void ExportToExcel_Click(object sender, EventArgs e) { SqlDataSource sq= this.Page.FindControl("SqlDataSource1") as SqlDataSource; GridView GridView1 = new GridView(); GridView1.DataSource = sq; GridView1.DataBind(); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "myFiles")); HttpContext.Current.Response.Charset = ""; HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; this.EnableViewState = false; StringWriter stringWrite = new StringWriter(); HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); GridView1.RenderControl(htmlWrite); HttpContext.Current.Response.Write(stringWrite.ToString()); HttpContext.Current.Response.End(); }Furthermore, you should know the export button is in the same cell as the page index footer . In other words you need to set the page AllowPaging with true. You should set the page size with a small number to show the export button. It can be fixed by modifying the structure of the InitializePager method. I just implement the function and you can changed it yourself.
You can refer to the Export To Excel control in the below link. It’s a custom control. Hope it can help you.
http://exporttoexcel.codeplex.com/
If you have any feedback about my replies, please contact msdnmg@microsoft.com
Microsoft One Code Framework
vinay13mar
Star
7756 Points
1626 Posts
Re: How to export gridview to excel in a console type application?
Feb 29, 2012 08:03 AM|LINK
Hi check the links
http://www.aspdotnet-suresh.com/2011/04/how-to-export-gridview-data-to-excel-or.html
http://stackoverflow.com/questions/6567482/how-to-convert-gridview-data-to-excel-sheet-in-asp-net-with-c-sharp-lang
http://www.c-sharpcorner.com/UploadFile/DipalChoksi/exportxl_asp2_dc11032006003657AM/exportxl_asp2_dc.aspx
V.K.Singh