Click here to Skip to main content
15,040,003 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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();


What I have tried:

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
Posted
Updated 11-Jul-21 15:31pm
v2
Comments
Richard Deeming 12-Jul-21 6:15am
   
NB: You are not exporting your grid to Excel. You are exporting it to HTML, but "lying" to the browser to get it to pass the HTML to Excel. Excel then attempts to convert the HTML to a proper Excel file.

You will get a content warning when Excel starts, and you will have virtually no control over the format and layout of the resulting file.

If you want to do it properly, you'll need to use a library that generates a real Excel file - for example, ClosedXML[^], or the OpenXML SDK[^].
xkarmax 14-Jul-21 5:23am
   
Yes thank you! I noticed this after a success export in excel. The result is the full page HTML. So the work around that I used is EPPLUS. And I also included an outside trigger so it wont have a problem when exporting a File because I have updatepanel on my page

1 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>
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900