Search code examples
asp.netexport-to-excel

Exporting Gridview to excel asp.net not working


I tried exporting my Gridview data to excel but nothing happens when I clicked the button. I have tried looking for the problem using breakpoint then it always stopped at gridData.RenderControl(htmlWrite); then it will go out of the function

this is my code

            Response.Clear();

            Response.AddHeader("content-disposition", "attachment;filename = FileName.xls");
            Response.ContentType = "application/vnd.xls";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            gridData.RenderControl(htmlWrite);
            Response.Write(stringWrite.ToString());

            Response.End();

UPDATE~

I tried using try catch to see what is the problem and i saw that when you have buttons inside the gridview it will not continue with the rendercontrol so the solution that came up is to disable all the controls and hide the buttons before rendercontrol and it proceeded to the next lines but when I got to Response.End() it returned an error of thread was being aborted so I look the web for another solution and i found the HttpContext.Current.ApplicationInstance.CompleteRequest(); and after that the error is gone but the excel output is still missing


Solution

  • I found the solution for this kind of problem you have to put triggers outside of the ContentTemplate. maybe because UpdatePanel is not compatible with FileUpload.

    You need to include this to your code

        </ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="YourButtonID" />
        </Triggers>