4

I am trying to export a gridview's contents to excel. I have some code:

public void ExcelDownload(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "UTF-8"; 
        Response.AppendHeader("Content-Disposition", "attachment;filename=MailingList.xls");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        Response.ContentType = "application/ms-excel";
        this.EnableViewState = false;
        System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("EN-US", true);
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        MailingList.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());
    }

which runs when a link is clicked. This works fine, except that it is exporting the entire webpage, instead of just the gridview (MailingList). Does anyone know how to fix this?

shawleigh17
  • 1,147
  • 4
  • 22
  • 42

1 Answers1

2

Tehnically speaking this is not export to excel, but you send a html with a wrong headers to trick browser to open this content with excel. If you stick with this solution you have to render just GridView on separate aspx page.

This solution has may problems, excel it self will warn user that content is different from extension, becouse you send html and your response headers are saying that this is a excel file. And I can bet that some antimalware software on client or something similar on server, will block this response since serving different content than declared in headers is known malware behaviour.

Better use NPOI (xls) or / and EPPlus (xlsx) and fully control your excel export.

Antonio Bakula
  • 20,445
  • 6
  • 75
  • 102
  • Ok, I am trying the EPPlus, now. Hoping it works! Thanks for your help. – shawleigh17 Mar 05 '12 at 20:06
  • oh it works great, you can see here example of exporting DataTable to xlsx http://stackoverflow.com/questions/9569401/c-sharp-create-modify-read-xlsx-files/9569827#9569827 – Antonio Bakula Mar 05 '12 at 20:28