将gridView导出到Excel时出现问题

时间:2013-08-21 21:30:58

标签: c# asp.net excel gridview

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

我试图按照此处的步骤进行操作:

  1. http://www.programming-free.com/2012/09/aspnet-export-grid-view-to-excel.html#.UhUREpK1F9o
  2. export gridview to excel file
  3. 和其他类似的网站。

    我的GridView没有任何与默认属性不同的特殊属性 如果这很重要,我的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(); 
    

1 个答案:

答案 0 :(得分: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()