简体   繁体   中英

Exporting a gridview to excel in c#

I have to export an gridview to excel. I am using the following code in button click event funcion :

Response.Clear();

Response.Buffer = true;

Response.AddHeader("Content-Disposition","attachment;filename=sample.xls");

Response.Charset = "";

Response.ContentType = "app`enter code here`lication/vnd.xls";

StringWriter stringWriter = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(stringWriter);

grdVw.RenderControl(htw);

Response.Write(stringWriter.ToString());

Response.End();

when I run this a dialog box is opening showing to download an empty XML file. When I tried to debug it, I found that grid has data but it stringWriter is not getting populated. I tried to change the content type to "application/ms-excel" etc. but no result. What is the error in the code and what might be the reason fot stringWriter not getting populated?

Thanks in advance

I assume that grdVw.RenderControl(htw); raises an exception that the GridView was not rendered in server form.

Try to execute it in the debugger and i'm fairly sure that you'll see that exception.

You could avoid this exception by overriding VerifyRenderingInServerForm

public override void VerifyRenderingInServerForm(Control control)
{
    // Confirms that an HtmlForm control is rendered for the specified ASP.NET 
    // server control at run time.  
}

See here and here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM