简体   繁体   English

GridView Export to Excel正在导出整个aspx页面

[英]GridView Export to Excel is exporting entire aspx page

I am trying to export a gridview's contents to excel. 我正在尝试将gridview的内容导出为ex​​cel。 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). 这很好,除了它导出整个网页,而不仅仅是gridview(MailingList)。 Does anyone know how to fix this? 有谁知道如何解决这一问题?

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. 从技术上讲,这不是导出到excel,而是发送带有错误标题的html来欺骗浏览器以使用excel打开此内容。 If you stick with this solution you have to render just GridView on separate aspx page. 如果您坚持使用此解决方案,则必须在单独的aspx页面上呈现GridView。

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. 这个解决方案可能存在问题,擅长自我会警告用户内容不同于扩展,因为你发送html并且你的响应头文件说这是一个excel文件。 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. 更好地使用NPOI (xls)或/和EPPlus (xlsx)并完全控制您的excel导出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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