Search code examples
.netexport-to-excel

Exception coming when exporting data to excel


I am getting following error while exporting data to excel sheet

ERROR:
Message : 
Exception of type 'System.Web.HttpUnhandledException' was thrown.
Error Description : 
System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

Anybody suggest me what i have to do.

CODE:
gridData.dataSource = GetData()
gridData.DataBind()


Response.Clear()
Response.AddHeader("content-disposition",   "attachment;filename=CompletionDatesReport.xls")
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/vnd.xls"
Dim stringWrite As StringWriter = New StringWriter()
Dim htmlWrite As HtmlTextWriter = New HtmlTextWriter(stringWrite)
gridData.RenderControl(htmlWrite)
Response.Write(stringWrite.ToString())
Response.End()

Solution

  • Without code we can only guess, but there is a big clue in the SqlException: Timeout expired - which suggests your query is taking too long. You can increase the timeout on a command (but try to keep it sane...) via SqlCommand.CommandTimeout, but writing the query to be more efficient, or not pulling as much data in one query, would usually be preferable.