Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
XML
public void ExportToExcel(DataTable dt, string FileName)
      {
         
              System.Web.HttpContext.Current.Response.Clear();
              System.Web.HttpContext.Current.Response.Buffer = true;
              System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + FileName + DateTime.Now + ".xls");
              System.Web.HttpContext.Current.Response.Charset = "";
              System.Web.HttpContext.Current.Response.ContentType = "application/text";
              StringBuilder sb = new StringBuilder();
              sb.Append("<table cellSpacing='0' cellPadding='0' align='center' border='1'><tr>");

              for (int k = 0; k <= dt.Columns.Count - 1; k++)
              {
                  //add separator
                  //& sw.ToString() & "</table>")
                  sb.Append("<th align ='Left' width = '50px'>");
                  sb.Append(dt.Columns[k].ColumnName.ToString());
                  sb.Append("</th>");
              }
              sb.Append("</tr>");
              //append new line
              //sb.Append(Constants.vbCr + Constants.vbLf);
              for (int i = 0; i <= dt.Rows.Count - 1; i++)
              {
                  sb.Append("<tr>");
                  for (int k = 0; k <= dt.Columns.Count - 1; k++)
                  {
                      //add separator
                      string retval = dt.Rows[i][k].ToString();
                      sb.Append("<td align ='Left' width = '50px'>");
                      sb.Append(dt.Rows[i][k].ToString().Replace(",", ";"));
                      sb.Append("</td>");
                  }
                  sb.Append("</tr>");
                  //append new line
                  //sb.Append(Constants.vbCr + Constants.vbLf);
              }
              sb.Append("</table>");
              System.Web.HttpContext.Current.Response.Output.Write(sb.ToString());
              System.Web.HttpContext.Current.Response.Flush();
              //HttpContext.Current.ApplicationInstance.CompleteRequest();

              System.Web.HttpContext.Current.Response.End();
          }
         
          }
}
Posted

1 solution

Make sure that there is no other logic to execute after the Response.End().
Response.End() is supposed to throw this exception which is by design.
You can try to resolve this by calling ApplicationInstance.CompleteRequest() instead of Response.End() .
Example:
C#
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();


Reference:
ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer[^]

Hope, it helps :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900