简体   繁体   English

在C#中将gridview导出到Excel

[英]Exporting a gridview to excel in c#

I have to export an gridview to excel. 我必须将gridview导出为ex​​cel。 I am using the following code in button click event funcion : 我在按钮单击事件函数中使用以下代码:

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

when I run this a dialog box is opening showing to download an empty XML file. 当我运行此对话框时,将打开一个对话框,显示要下载一个空XML文件。 When I tried to debug it, I found that grid has data but it stringWriter is not getting populated. 当我尝试调试它时,我发现网格具有数据,但未填充stringWriter。 I tried to change the content type to "application/ms-excel" etc. but no result. 我试图将内容类型更改为“ application / ms-excel”等,但没有结果。 What is the error in the code and what might be the reason fot stringWriter not getting populated? 代码中的错误是什么?stringWriter无法填充的原因可能是什么?

Thanks in advance 提前致谢

I assume that grdVw.RenderControl(htw); 我假设grdVw.RenderControl(htw); raises an exception that the GridView was not rendered in server form. 引发一个异常,即GridView没有以服务器形式呈现。

Try to execute it in the debugger and i'm fairly sure that you'll see that exception. 尝试在调试器中执行它,我相当确定您会看到该异常。

You could avoid this exception by overriding VerifyRenderingInServerForm 您可以通过重写VerifyRenderingInServerForm来避免此异常

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

See here and here . 看到这里这里

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

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