Columns are autogenerated in gridview.Gridview has paging.Can I export gridview to excel,if gridview has paging.
you can export the grid view to excel .....
public static void Export(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
// add the header row to the table
if (gv.HeaderRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
GridViewExportUtil.PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
//Export Gridview Data to Excel File and Save Excel file to Server Folder Rather than
//allowing user to Open or Save it.
public static void ExportToFolder(string fileName, GridView gv)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
// add the header row to the table
if (gv.HeaderRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
GridViewExportUtil.PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
//Create file
System.IO.TextWriter w = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath("~") + "\\" + fileName);
w.Write(sb.ToString());
w.Flush();
w.Close();
}
}
}
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
GridViewExportUtil.PrepareControlForExport(current);
}
}
}
pls go through this link for more info
Related
I have used gridview in my C# asp.net form application and I have enabled "AllowPaging" and now whenever I want to convert it to excel only the first page is shown. The conversion is done using "HtmlTextWriter" and "StringWriter".
-Thanks in advance.
To export excel from gridview you can use the following class in your project.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web;
namespace gride_edit
{
public class GridToExcel
{
public static void ExportToExcel(string strFileName, GridView gv)
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
// add the header row to the table
if (gv.HeaderRow != null)
{
PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
PrepareControlForExport(row);
row.Style["background-color"] = "#FFFBD6";
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", strFileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is HiddenField)
{
control.Controls.Remove(current);
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
PrepareControlForExport(current);
}
}
}
}
}
and can call this function to export.
GridToExcel.ExportToExcel("Report" + DateTime.Now.ToString("yyyyMMddhhmmss").ToString() + ".xls", GridView1);
And for export one excel from multiple paged gridview, just use these line before calling the convert function "ExportToExcel()".
GridView1.AllowPaging = false;
bindGridView();
I got the "GridToExcel" class from internet. It worked for me, hope it will work for you too. Please let me know.
In general you can use the following function
public void Export(HttpResponseBase Response, object data)
{
var gridItem = new System.Web.UI.WebControls.GridView();
gridItem.DataSource = data;
gridItem.DataBind();
StringWriter writer = new StringWriter();
HtmlTextWriter html = new HtmlTextWriter(writer);
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=result.xls");
Response.ContentType = "application/excel";
gridItem.RenderControl(html);
Response.Write(writer.ToString());
Response.End();
}
and you can call this function as
var details = /* your query result goes here */ ;
Export(Response , details );
hope it helps you
I want to export data from GridView into an excel file on ASP.NET website. I added a GridView only for this purpose
<body>
<form id="mainForm" runat="server">
<asp:GridView ID="exportGrid" runat="server">
</asp:GridView>
</form>
....
</body>
In codebehind I have this:
public override void VerifyRenderingInServerForm(Control control) { }
var result = GetDataIQueryable(); //A method that returns an IQueryable
exportGrid.DataSource = result;
exportGrid.DataBind();
Response.Clear();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + "ExcelFile.xls");
Response.ContentType = "application/excel";
var sw = new System.IO.StringWriter();
var htw = new HtmlTextWriter(sw);
exportGrid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
The problem is that the popup that allows me to save the excel file on my computer is not appearing. What should I change in my code ?
Use this code on your button click event
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FormReport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
BindGridView();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
GridView1.Dispose();
}
}
#endregion
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
and on .aspx page use
<%# Page Title="" Language="C#" EnableEventValidation="false"%>
I know this is a bit too late, but i am posting this just for information. I found the answer in the comments but i would still like to submit a answer with code , because i myself found it difficult to find the code so the answer is for if your grid is inside update panel. You need to add a post back trigger to the button.
private void RegisterPostBackControl()
{
ScriptManager.GetCurrent(this).RegisterPostBackControl(yourButton);
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
Your Buttons Click Event :
protected void yourButton_Click(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "full", true);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FormReport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
yourGrid.AllowPaging = false;
var emps = FunctionThatGetsGridValues();
yourGrid.DataSource = emps;
yourGrid.DataBind();
yourGrid.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in yourGrid.HeaderRow.Cells)
{
cell.BackColor = yourGrid.HeaderStyle.BackColor;
}
foreach (GridViewRow row in yourGrid.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = yourGrid.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = yourGrid.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
yourGrid.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
yourGrid.Dispose();
}
}
And On Page Load Dont forget to add :
protected void Page_Load(object sender, EventArgs e)
{
this.RegisterPostBackControl();
}
i am using ExportToExcel dll.In first iteration my dataset contain below record
KeyName English Hindi
Name engval hival
And second iteration my dataset conatin below record
KeyName English Hindi
Name engval hival
i have to create xsl file on run time one by one as below.how to apply the style on it
that it look like good.
hindi.xsl
KeyName English Hindi
Name engval hival
punjabi.xsl
KeyName English panjabi
Name engval punjabival
Edit:using GridViewExportUtil
i am trying to create xsl one by one.below is my logic
for(int i=0;i<2;i++)
{
//
****logic here to get the record from db and fill the record into dsexcel***
//
gvruntime.DataSource = dsExcel;
gvruntime.DataBind();
string headername = string.Empty;
headername = i+".xls";
GridViewExportUtil.Export(headername, this.gvruntime);
}
in this case only last file is overight to previous one..pls tell me how to resolve it
Please try this code, this code will export gridview data to excel. You need to first bind your dataset to gridview then call this function
GridViewExportUtil.Export("hindi.xsl", this.grdhindi);
GridViewExportUtil.Export("punjabi.xsl", this.grdpunjabi);
// calss code
public class GridViewExportUtil
{
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <param name="gv"></param>
public static void Export(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
//HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Private);
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
table.GridLines = gv.GridLines;
// add the header row to the table
if (gv.HeaderRow != null)
{
//gv.HeaderRow.Font.Bold = true;
GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
GridViewExportUtil.PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
byte[] s = Encoding.UTF8.GetBytes(sw.ToString());
HttpContext.Current.Response.AddHeader("Content-Length", s.Length.ToString());
HttpContext.Current.Response.BinaryWrite(s);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
/// <summary>
/// Replace any of the contained controls with literals
/// </summary>
/// <param name="control"></param>
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
GridViewExportUtil.PrepareControlForExport(current);
}
}
}
}
Or you can use diffrent way to export griddata to excel
for(int i=0;i<2;i++)
{
gvruntime.DataSource = dsExcel.Table[i];
gvruntime.DataBind();
string headername = string.Empty;
headername = i+".xls";
// render the DataGrid control to a file
using(StreamWriter sw = new StreamWriter("c:\\"+headername+".xls"))
{
using(HtmlTextWriter hw = new HtmlTextWriter(sw))
{
gvruntime.RenderControl(hw);
}
}
}
I am using the below two function to export my gridview data to excel.The problem is,data is exported completely but right aligned,i need it center aligned,i am not able to figure it out..Can anyone help me in this regard.Any help would be greatly appreciated.
public static void GenerateExcel(GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment; filename=Leave_Report.xls");
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a table to contain the grid
Table table = new Table();
// include the gridline settings
table.GridLines = gv.GridLines;
// add the header row to the table
if (gv.HeaderRow != null)
{
PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
//Make Header Coloruful
for (int j = 0; j < gv.Columns.Count; j++)
{
//Apply style to Individual Cells
gv.HeaderRow.Cells[j].Style.Add("background-color", "#4DB4EE");
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
PrepareControlForExport(current);
}
}
}
try
wSheet.get_Range("B3", "B3").HorizontalAlignment = HorizontalAlign.Center;
instead of
wSheet.get_Range("B3", "B3").HorizontalAlignment = Constants.xlCenter;
Try this
foreach (GridViewRow row in gv.Rows)
{
foreach (TableCell cell in row.Cells)
{
cell.Attributes.CssStyle["text-align"] = "center";
}
}
I have Gridview and I have three options to export the data to excel sheet:
current page
all pages
top100 row
It worked will with current but the other options didn't work.
Code:
protected void btnExportGrid_Click(object sender, EventArgs e)
{
Table table = new Table
{
GridLines = this.gv_RquestedOrdres.GridLines
};
if (this.rdoBtnListExportOptions.SelectedIndex == 1)
{
this.gv_RquestedOrdres.AllowPaging = false;
this.gv_RquestedOrdres.DataBind();
}
else if (this.rdoBtnListExportOptions.SelectedIndex == 2)
{
this.gv_RquestedOrdres.PageSize = 100;
this.gv_RquestedOrdres.DataBind();
}
GridViewExportUtil.Export("Orders.xls", this.gv_RquestedOrdres);
}
private string Gridview(Panel gv)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.RenderControl(hw);
return sb.ToString();
}
GridViewExportUtil class:
public class GridViewExportUtil
{
public static void Export(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
using (StringWriter writer = new StringWriter())
{
using (HtmlTextWriter writer2 = new HtmlTextWriter(writer))
{
Table table = new Table();
if (gv.HeaderRow != null)
{
PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
foreach (GridViewRow row in gv.Rows)
{
PrepareControlForExport(row);
table.Rows.Add(row);
}
if (gv.FooterRow != null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
table.RenderControl(writer2);
HttpContext.Current.Response.Write(writer.ToString());
HttpContext.Current.Response.End();
}
}
}
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control control2 = control.Controls[i];
if (control2 is LinkButton)
{
control.Controls.Remove(control2);
control.Controls.AddAt(i, new LiteralControl((control2 as LinkButton).Text));
}
else if (control2 is ImageButton)
{
control.Controls.Remove(control2);
control.Controls.AddAt(i, new LiteralControl((control2 as ImageButton).AlternateText));
}
else if (control2 is HyperLink)
{
control.Controls.Remove(control2);
control.Controls.AddAt(i, new LiteralControl((control2 as HyperLink).Text));
}
else if (control2 is DropDownList)
{
control.Controls.Remove(control2);
control.Controls.AddAt(i, new LiteralControl((control2 as DropDownList).SelectedItem.Text));
}
else if (control2 is CheckBox)
{
control.Controls.Remove(control2);
control.Controls.AddAt(i, new LiteralControl((control2 as CheckBox).Checked ? "True" : "False"));
}
if (control2.HasControls())
{
PrepareControlForExport(control2);
}
}
}
}
You are using grid-view for exporting the data - it only means that current page of grid-view would be rendered into exported html. To render complete data (or top 100 rows), set your page size accordingly. So Page size of 100 rows with page index of 1 would give you top 100 rows export while disabling paging should give you all pages - revert the paging once export is over.
Yet another alternative is to use the actual data (that you have bound to gird) to do a CSV export (can be opened in excel) (or do html export using Table and Row but instead of using grid-view rows, use data to add cells into html Row)