Jump to content


Mário_Santos

Member Since 01/02/2012
Offline Last Active 08/02/2012, 09:08
-----

Topics I've Started

Exportar Gridview Para Excel

02/02/2012, 14:30

Olá Pessoal estou com problema para exportar Um GridView para o Excel, segue abaixo meu código, após passar pelo Response.End(); apresenta o seguinte erro
{Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}

Criei o botão abaixo:

protected void btnImprimir_Click(object sender, EventArgs e)
{

try
{
string attachment = "attachment; filename=Contacts.xls";
Response.ClearContent();

//Converter campos de controle como CheckBox, DropDownList..
PreparaGridView(gvResultado1);

gvResultado1.EnableViewState = false;

Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvResultado1.RenderControl(htw);
Response.Write(sw.ToString());

Response.End();

}
catch (Exception err)
{
throw err;
}

}


Estou usando esta função para tratar o checBocks que tenho no grid

private void PreparaGridView(Control gv)
{

LinkButton lb = new LinkButton();
Literal l = new Literal();
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(CheckBox))
{
l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
PreparaGridView(gv.Controls[i]);
}

}
}

Algué, ja passou por isso, ou poderia me dar help?

IPB Skin By Virteq