2

我正在尝试将 a 导出GridView到 Excel。

我尝试按照此处找到的步骤进行操作:

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

和其他类似的网站。

MyGridView没有任何不同于默认值和我的SqlDataSource用途的特殊属性(filterExpression如果这很重要)。

当我尝试上述解决方案时,不会出现异常,但不会生成 excel。

更新

我忘了提到它在GridView控件内asp:Content。我听说这可能很重要。

我的代码隐藏是这样的(我尝试了多种方法)。

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

1 回答 1

0

您可以在后面的代码上创建一个 GridView 并单独选择数据并按如下方式导出该 Gridview。所以您不必担心页面上的 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()
于 2013-08-22T00:02:58.630 回答