简体   繁体   English

将gridView导出到Excel时出现问题

[英]Problems exporting gridView to Excel

I am trying to export a GridView to Excel. 我正在尝试将GridView导出到Excel。

I have tried to follow steps found here: 我试图遵循此处找到的步骤:

  1. http://www.programming-free.com/2012/09/aspnet-export-grid-view-to-excel.html#.UhUREpK1F9o http://www.programming-free.com/2012/09/aspnet-export-grid-view-to-excel.html#.UhUREpK1F9o
  2. export gridview to excel file 将gridview导出到excel文件

And other similar sites. 和其他类似的网站。

My GridView does not have any special properties different from default and my SqlDataSource uses filterExpression if that is important. 我的GridView没有与默认值不同的任何特殊属性,并且如果这很重要,我的SqlDataSource将使用filterExpression

When I try the above mentioned solutions no exception occurs, but the excel is not produced. 当我尝试上述解决方案时,不会发生任何异常,但是不会生成excel。

UPDATE UPDATE

I forgot to mention that the GridView is inside a asp:Content control. 我忘了提到GridViewasp:Content控件中。 I heard this might matter. 我听说这可能很重要。

My code-behind goes something like this ( I have tried multiple things ). 我后面的代码是这样的(我尝试了很多事情)。

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = String.Empty;
EnableViewState = false;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView3.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());         
HttpContext.Current.ApplicationInstance.CompleteRequest(); 

You can create a GridView on the code behind and select the data seperately and export that Gridview as follows. 您可以在后面的代码上创建GridView,然后分别选择数据并按如下所示导出该Gridview。 So You don't have to worry about the Gridview on the Page. 因此,您不必担心页面上的Gridview。

Dim GridView1 As New GridView

SqlDataSource1.SelectCommand = "SELECT * FROM TableName"
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()

Response.Clear()
Response.Buffer = True
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Me.EnableViewState = False
Dim oStringWriter As New System.IO.StringWriter
Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)

GridView1.RenderControl(oHtmlTextWriter)

Response.Write(oStringWriter.ToString())
Response.End()

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

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