如何使用 C# lang 将 gridview 数据转换为 ASP .net 中的 Excel 工作表
我想将 GridView 数据转换为 Excel 工作表。
我已经编写了下面的代码,但它给出了错误:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Avukat.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
Response.Write(stringWrite.ToString());
Response.End();
}
错误:
“GridView”类型的控件“ctl00_ContentPlaceHolder1_GridView1”必须放置在带有 runat=server 的表单标记内。
I want to covnvert GridView data to Excel sheet.
I have written the code below, but it gives error:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Avukat.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
Response.Write(stringWrite.ToString());
Response.End();
}
Error:
Control 'ctl00_ContentPlaceHolder1_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为您的 gridview 包含
linkbutton/Imagebutton 或其他类型的控件
,这就是当您尝试将 GridView 导出到 Excel 时出现异常的原因。在使用该控件之前,您需要在 Page 代码后面或 BasePage 代码后面添加以下几行。
您可以使用此代码,因为此代码经过测试并且运行良好:
I think your gridview contains a
linkbutton/Imagebutton or another type of control
, and that's why you are getting an Exception when you are trying to export the GridView to Excel.Before using the control you need to add the following lines in your Page code behind, or the BasePage code behind.
You can use this code, as this code is tested and worked perfectly:
你错过了这一部分:
我的意思是你应该使用这行代码:
而不是:
但我认为最好使用这个免费的开源组件,它可以从/导出不同的 Excel 和 Word 格式: http://npoi.codeplex.com/
You've missed this part:
I mean you should use this line of code:
Instead of:
But I think it would be better to use this free open source component which imports/exports from/to different excel and word formats: http://npoi.codeplex.com/
您只需要复制下面的代码。
You just need to copy below code.