简体   繁体   中英

Problems exporting gridView to Excel

I am trying to export a GridView to 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
  2. export gridview to excel file

And other similar sites.

My GridView does not have any special properties different from default and my SqlDataSource uses filterExpression if that is important.

When I try the above mentioned solutions no exception occurs, but the excel is not produced.

UPDATE

I forgot to mention that the GridView is inside a asp:Content control. 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. So You don't have to worry about the Gridview on the Page.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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