Simple program with a button 'btnExportToExcel' when I click this button don't show any response.when I debug this button code after executing all lines shows the form after clicking button at second time cursor goes to another method named GridView1_RowCreated(used for designing grid) but don't response to convert grid to excel.
What should I do now?
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.AppendHeader("content-disposition", "attachment;
filename=Inventory.xls");
Response.ContentType = "application/ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
GridView1.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
//Add CSS class on header row.
if (e.Row.RowType == DataControlRowType.Header)
e.Row.CssClass = "header";
//Add CSS class on normal row.
if (e.Row.RowType == DataControlRowType.DataRow &&
e.Row.RowState == DataControlRowState.Normal)
e.Row.CssClass = "normal";
//Add CSS class on alternate row.
if (e.Row.RowType == DataControlRowType.DataRow &&
e.Row.RowState == DataControlRowState.Alternate)
e.Row.CssClass = "alternate";
}
You need to Rebind the GridView on the post back.
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.AppendHeader("content-disposition", "attachment; filename=Inventory.xls");
Response.ContentType = "application/ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
GridView1.DataBind();
GridView1.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
try this code working fine
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
// Grid_bindExcel();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment;filename=Category.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
Label lblheader = new Label();
lblheader.Font.Size = 14;
lblheader.Font.Bold = true;
lblheader.Text = "Category Detail";
lblheader.RenderControl(hw);
GrdExcel.Visible = true;
GrdExcel.RenderControl(hw);
Response.Write(sw.ToString());
Response.Flush();
Response.End();
GrdExcel.Visible = false;
}
public override void VerifyRenderingInServerForm(Control control)
{
}
Related
hope you can help me.
I am developing a web page that produces a GridView in aspx which works and a button that when is clicked exports the gridview to excel file. This second case doesn't work for me, the file is empty. Here it is the code:
protected void Button2_Click(object sender, EventArgs e) //click en botón Exportar- -Click to export
{
try
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "CUSS - Global Stats.xls"));
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
System.IO.StringWriter writer = new StringWriter();
System.Web.UI.HtmlTextWriter html = new System.Web.UI.HtmlTextWriter(writer);
GridView1.AllowPaging = false;
GridView1.RenderControl(html); //gpp prints outs
Response.Write(writer.ToString());
Response.Flush();
Response.End();
}
catch (Exception)
{
}
Gridview is properly produce in asp as shown in pic.GridViewResult
protected void Button1_Click(object sender, EventArgs e)
{
...
GridView1.DataSource = Prints.ToList();
GridView1.DataBind();
...
}
Can you pls help me?
There should be a better way to do it, but I 'make' my gridview again:
using ClosedXML.Excel;
Click event:
public void button1_Click(object sender, EventArgs e)
{
using(XLWorkbook libro_trabajo = new XLWorkbook())
{
DataSet ps = datos_referencias();
libro_trabajo.Worksheets.Add(ps);
libro_trabajo.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
libro_trabajo.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=reporte_clientes.xlsx");
using (MemoryStream memoria = new MemoryStream())
{
libro_trabajo.SaveAs(memoria);
memoria.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
Getting my data set:
public DataSet datos_referencias()
{
DataSet ds = new DataSet();
DataTable tabla_detallado = new DataTable("Clientes");
tabla_detallado.Columns.Add(new DataColumn("Cliente", typeof(string)));
objeto = new Conexion();
try
{
objeto.abrir_conexion_mysql();
objeto.cadena_comando_mysql = "SELECT * from ...ETC ";
objeto.aplicar_comando_mysql_extraccion();
while (objeto.leer_comando.Read())
{
DataRow fila = tabla_detallado.NewRow();
fila["Cliente"] = (objeto.leer_comando.GetString(1)).ToUpper();
tabla_detallado.Rows.Add(fila);
}
}
finally {objeto.cerrar_conexion_mysql_extraccion(); }
ds.Tables.Add(tabla_detallado);
return ds;
}
Maybe because of make response GZip ?
On filter ?
response.Filter = New GZipStream(response.Filter, CompressionMode.Compress)
I'm trying to export the contents of the gridview to excelsheet and the last row of the gridview is always missing in the excel sheet.
I think it might be due to the header row but could not figure out how to overcome this. Below is the code for exporting to excel sheet
private void btnExportToExcel_OnClick(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";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
GridView1.RenderControl(hw); //here gridview is not rendering last row
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
This is working fine for me. Here is my code behind with simple data.My aspx page has just a grid and an export button
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Id");
DataRow dr = dt.NewRow();
dr["Id"] = 1;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Id"] = 2;
dt.Rows.Add(dr);
//To Export all pages
grdTest.AllowPaging = false;
grdTest.AllowSorting = false;
grdTest.DataSource = dt;
grdTest.DataBind();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void btnExport_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";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
grdTest.RenderControl(hw); //here gridview is not rendering last row
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
}
I could not found solution online anywhere but I found the reason why this was happening, it was due to one additonal GridviewRow being added to the gridview on rowDatabound, and that addition of single row was skipping the very last row.
To fix this, before gridview databinding, I added one empty footer row to workaround the issue:
DataRow dr= dt.NewRow();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
I don't know why the alignment is not proper when viewed in excel and some of the colors are also not displayed.
Below is my code.
protected void Page_Load(object sender, EventArgs e)
{
//check if session is valid
// WebUtility.WebUtility.CheckValidSession(Context, ResponseSession);
tdOnTime2.BackColor = Color.FromName(Valuelist.FirstOrDefault().Color == "Amber" ? "Orange" : Valuelist.FirstOrDefault().Color);
tdAceeptableDelay2.BackColor = Color.FromName(Valuelist.Skip(1).FirstOrDefault().Color == "Amber" ? "Orange" : Valuelist.Skip(1).FirstOrDefault().Color);
tdDelayed2.BackColor = Color.FromName(Valuelist.LastOrDefault().Color == "Amber" ? "Orange" : Valuelist.LastOrDefault().Color);
tdOnTime.BackColor = Color.FromName(Valuelist.FirstOrDefault().Color == "Amber" ? "Orange" : Valuelist.FirstOrDefault().Color);
tdAceeptableDelay.BackColor = Color.FromName(Valuelist.Skip(1).FirstOrDefault().Color == "Amber" ? "Orange" : Valuelist.Skip(1).FirstOrDefault().Color);
tdDelayed.BackColor = Color.FromName(Valuelist.LastOrDefault().Color == "Amber" ? "Orange" : Valuelist.LastOrDefault().Color);
//get CP from querystring
int CPID ;
int.TryParse(Request.QueryString.Get("CPID"), out CPID);
this.ucComplianceReportForCP.CPID = CPID;
this.ucComplianceReportForCP.DisplayComplianceForCP();
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=ComplianceReport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
// rptCustomers.RenderControl(hw);
// this.ltExcelCPtitle.Visible = true;
pnlComplianceData.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
// ltExcelCPtitle.Visible = false;
}
Below is the image.
http://i.stack.imgur.com/6EiAY.png
save data gird view to excel in asp dot net. data is save when i am using padding in grid view than full data not show in excel sheet how to show full data of grid view in excel sheet when using padding in grid view
protected void btnexcel_Click1(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=ActualsAndBudgets.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
You can export to excel and apply styles and formatting see sample code below
protected void btnExportExcel_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);
GridView.AllowPaging = false;
// Re-Bind data to GridView
using (MSEntities1 CompObj = new MSEntities1())
{
// code for bind grid view
GridView.DataBind();
}
// Change the Header Row back to white color
GridViewC.Style.Add(" font-size", "10px");
GridView.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Apply style to Individual Cells
GridView.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[3].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[4].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[5].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[6].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[7].Style.Add("background-color", "green");
int k = GridView.Rows.Count;
for (int i = 1; i < GridView.Rows.Count; i++)
{
GridViewRow row = GridView.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
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");
row.Cells[3].Style.Add("background-color", "#C2D69B");
row.Cells[4].Style.Add("background-color", "#C2D69B");
row.Cells[5].Style.Add("background-color", "#C2D69B");
row.Cells[6].Style.Add("background-color", "#C2D69B");
row.Cells[7].Style.Add("background-color", "#C2D69B");
}
}
GridView.RenderControl(hw);
// style to format numbers to string.
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
Go through following code:
using System;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Whatever
{
///
/// This class provides a method to write a dataset to the HttpResponse as
/// an excel file.
///
public class ExcelExport
{
public static void ExportDataSetToExcel(DataSet ds, string filename)
{
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
}
}
NOTE: Above code belongs to this link.
You can follow discussion over that link and get more details.
Hope its helpful.
I want to export the parent grid view and nested gridview to an excel.
I have a code that only work to export a normal simple gridview.
Tried to debug the code, found there is no error or whatsoever.
It is just after i click the export button, it doesnt export to excel.
here is my code
protected void asd()
{
string title = "";
string attempt = "SELECT * FROM Poll Where PollID = '" + Session["abc"] + "'";
cmd = new SqlCommand(attempt, con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
title = dr["PollTitle"].ToString();
}
string filename = String.Format(title + " RESULTS. " + "{0}_{1}.xls",
DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
Response.Charset = "";
// SetCacheability doesn't seem to make a difference (see update)
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
// Replace all gridview controls with literals
ClearControls(GridView3);
// Throws exception: Control 'ComputerGrid' of type 'GridView'
// must be placed inside a form tag with runat=server.
// ComputerGrid.RenderControl(htmlWrite);
// Alternate to ComputerGrid.RenderControl above
System.Web.UI.HtmlControls.HtmlForm form
= new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(GridView3);
form.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text =
(string)control.GetType().GetProperty("SelectedItem").
GetValue(control, null);
}
catch
{ }
control.Parent.Controls.Remove(control);
}
else if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text =
(string)control.GetType().GetProperty("Text").
GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
return;
}
protected void Export_buttonClick(object sender, EventArgs e)
{
asd();
}
this code is working for a normal gridview, but not the one with nested gridview.
I've experienced the 'must be placed inside a form tag with runat=server' error in the past and resolved the issue by adding the following override method in my page codebehind:
public override void VerifyRenderingInServerForm(Control control) {}
More info on MSDN.
For reference, I also used this code for exporting my GridViews:
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=your_file.xls");
Response.Charset = "";
Response.ContentEncoding = System.Text.Encoding.Default;
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
your_GridView.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();