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();
Related
i am trying to get files as bytes from table and show , i am getting the files as dataset but when trying to move it as datatable it shows row as zero and moves out of the if condition
protected void btnview_Click(object sender, EventArgs e)
{
string code = txtbudid.Text;
try
{
{
using (MasterManagement mMgmt = new MasterManagement(General.ConnString()))
{
dsBud = mMgmt.getfile(code);
DataTable dt = new DataTable();
dsBud.Tables.Add(dt);
if (dsBud != null)
{
if (dt.Rows.Count > 0)
{
byte[] bytes = (byte[])dt.Rows[0]["filedata"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.ContentType = dt.Rows[]
Response.AddHeader("Content-disposition", "attachment;filename=" + dt.Rows[0]["filename"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
}
}
I have 2 issues which may not be related.
I have been unable to export excel sheet
I keep getting this error at Response.End()
Thread was was being aborted
For the first issue I tried testing whether the code worked or not by doing the following
.aspx.cs
private void BindSalesMargin()
{
DataTable dt = new DataTable();
objAcc.CompanyID = Convert.ToInt16(ddlCompany.SelectedValue);
objAcc.LocID = ddlLocation.Text;
objAcc.dtFrom = Calendar1.SelectedDate;
objAcc.dtTo = Calendar2.SelectedDate;
if (ddlResult.SelectedValue == "0")
{
objAcc.Result = "Under,Over,OK";
}
else
{
objAcc.Result = ddlResult.Text;
}
dt = objAcc.Sale_MarginMail();
SalesMargin.DataSource = dt;
SalesMargin.DataBind();
Session["Salesdt"] = dt;
if (((DataTable)Session["Salesdt"]).Rows.Count > 0)
{
grdexport.DataSource = (DataTable)Session["Salesdt"];
grdexport.DataBind();
string filename = "Sales_Margin.xls";
//string excelHeader = "";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
//hw.WriteLine("<b><u><font size=’3′> " + excelHeader + " </font></u></b>");
bandDiv.RenderControl(hw);
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
Response.ContentType = "application/vnd.ms-excel; charset=ISO-8859-1";
Response.Charset = "UTF-8";
this.EnableViewState = false;
Response.Write(tw.ToString().Replace("NULL", ""));
Response.Write(Response.OutputStream);
Response.Flush();
try
{
Response.End();
//Response.Close();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
//ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, GetType(), "", "alert(" + ex + ");", true);
}
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "", "alert('No data to Export for given details');", true);
}
}
and it works. But doesn't work on button click event for the below code.
.aspx
<div class="value">
<asp:Button ID="Export" runat="server" CssClass="Btn_Export" OnClick="Export_Click" Text="Export sales Margin" />
</div>
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindCompany();
//txtFrom.Text = DateTime.Now.AddMonths(-1).AddDays(1 - DateTime.Today.Day).ToString("dd-MMM-yyyy");
txtFrom.Text = DateTime.Now.AddDays(1 - DateTime.Today.Day).ToString("dd-MMM-yyyy");
txtTo.Text = DateTime.Now.ToString("dd-MMM-yyyy");
Calendar2.SelectedDate = Convert.ToDateTime(txtTo.Text);
Calendar1.SelectedDate = Convert.ToDateTime(txtFrom.Text);
BindSalesMargin();
}
}
private void BindSalesMargin()
{
DataTable dt = new DataTable();
objAcc.CompanyID = Convert.ToInt16(ddlCompany.SelectedValue);
objAcc.LocID = ddlLocation.Text;
objAcc.dtFrom = Calendar1.SelectedDate;
objAcc.dtTo = Calendar2.SelectedDate;
if (ddlResult.SelectedValue == "0")
{
objAcc.Result = "Under,Over,OK";
}
else
{
objAcc.Result = ddlResult.Text;
}
dt = objAcc.Sale_MarginMail();
SalesMargin.DataSource = dt;
SalesMargin.DataBind();
Session["Salesdt"] = dt;
}
protected void Export_Click(object sender, EventArgs e)
{
if (((DataTable)Session["Salesdt"]).Rows.Count > 0)
{
grdexport.DataSource = (DataTable)Session["Salesdt"];
grdexport.DataBind();
string filename = "Sales_Margin.xls";
//string excelHeader = "";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
//hw.WriteLine("<b><u><font size=’3′> " + excelHeader + " </font></u></b>");
bandDiv.RenderControl(hw);
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
Response.ContentType = "application/vnd.ms-excel; charset=ISO-8859-1";
Response.Charset = "UTF-8";
this.EnableViewState = false;
Response.Write(tw.ToString().Replace("NULL", ""));
Response.Write(Response.OutputStream);
Response.Flush();
try
{
Response.End();
//Response.Close();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
//ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, GetType(), "", "alert("+ ex +");", true);
}
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "", "alert('No data to Export for given details');", true);
}
}
So my question is Why does it not work? Why does it work in other similar modules where I have to export to excel? and how can I fix this?
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();
In my page I have two textbox controls, where I am gating the date from the Calendar Extender & in the export to excel Button I am going to export the Gridview data to excel sheet.
When I am gating the excel sheet its show the the textbox & button also from which i am export the excel Sheet.
I have written the export code in the Export Button.
Like:-
protected void Export_to_Excel_Click(object sender, EventArgs e)
{
try
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
Grd_MidData.AllowPaging = false;
bindgriddata();
//Change the Header Row back to white color
Grd_MidData.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < Grd_MidData.HeaderRow.Cells.Count; i++)
{
Grd_MidData.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
Grd_MidData.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
}
catch (Exception ee)
{
}
}
When I am gating the excel sheet it shows the gridview data along with the two text box & the button from where I am doing the filtering.
So any one suggest me, How to show only the gridview data but not show the Textbox & button on the excel sheet.
You have to bind the data to your excel code,
using below code
bindgriddata();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter ht = new HtmlTextWriter(sw);
Grd_MidData.RenderControl(ht);
Response.Write(sw.ToString());
Response.End();
it is working for me.
Here the gridview data is showing along with the From date: To Date: textbox & the button also. So how can i remove these field from the sheet.
you can use close xml to generate excel it will give more functionlity to create excel and formatting.
protected void Export_to_Excel_Click(object sender, EventArgs e)
{
bindgriddata();
Grd_MidData.DataSource = objDS; // Dataset
Grd_MidData.DataBind();
using (XLWorkbook wb = new XLWorkbook())
{
try
{
//creating worksheet
var ws = wb.Worksheets.Add("Report");
//adding columms header
int columnscount = objDS.Tables[0].Columns.Count;
char a = 'A';
for (int j = 1; j <= columnscount; j++)
{
string str = a + "1";
ws.Cell(str).Value = objDS.Tables[0].Columns[j - 1].ColumnName.ToString();
ws.Cell(str).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
a++;
}
ws.Columns().AdjustToContents();
//formatting columns header
var rngheaders = ws.Range("A1:J1");
rngheaders.FirstRow().Style
.Font.SetBold()
.Font.SetFontSize(12)
.Font.SetFontColor(XLColor.Black)
.Fill.SetBackgroundColor(XLColor.DeepSkyBlue)
.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center)
.Border.OutsideBorder = XLBorderStyleValues.Thin;
////adding data to excel
int k = 2;
foreach (DataRow row in objDS.Tables[0].Rows)
{
char b = 'A';
string str = b + "" + k;
for (int i = 0; i < objDS.Tables[0].Columns.Count; i++)
{
ws.Cell(str).Value = row[i].ToString();
ws.Cell(str).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
ws.Cell(str).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Left);
b++;
str = b + "" + k;
}
k++;
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Customer.xlsx");
}
catch { }
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
I had the same issue when exporting a GridView. I added a try/catch and exported the message to Excel and then realized that it was generating an error. I solved it thanks to the following answer: GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag