繁体   English   中英

在C#中将gridview导出到Excel

[英]Exporting a gridview to excel in c#

我必须将gridview导出为ex​​cel。 我在按钮单击事件函数中使用以下代码:

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();

当我运行此对话框时,将打开一个对话框,显示要下载一个空XML文件。 当我尝试调试它时,我发现网格具有数据,但未填充stringWriter。 我试图将内容类型更改为“ application / ms-excel”等,但没有结果。 代码中的错误是什么?stringWriter无法填充的原因可能是什么?

提前致谢

我假设grdVw.RenderControl(htw); 引发一个异常,即GridView没有以服务器形式呈现。

尝试在调试器中执行它,我相当确定您会看到该异常。

您可以通过重写VerifyRenderingInServerForm来避免此异常

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

看到这里这里

暂无
暂无

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

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