title: Export a data set to Excel and raise a file download dialog from an asp.net web method
body: <p>I am using the following code to export a data set to an Excel sheet.</p>
  
  <pre><code>[WebMethod]
      public static void ExporttoExcel()
      {
          DataSet ds;
         productfactory pf=new productfactory();
          ds = pf.getproducts();
          HttpResponse response = HttpContext.Current.Response;
  
          // first let's clean up the response.object
          response.Clear();
          response.Charset = "";
          response.ContentEncoding = System.Text.Encoding.Default;
  
          // set the response mime type for excel
          response.ContentType = "application/vnd.ms-excel";
          response.AddHeader("Content-Disposition", "attachment;filename=\"products.xls\"");
  
          // create a string writer
          using (StringWriter sw = new StringWriter())
          {
              using (HtmlTextWriter htw = new HtmlTextWriter(sw))
              {
                  // instantiate a datagrid
                  DataGrid dg = new DataGrid();                    
                  dg.DataSource = ds.Tables[0];
                  dg.DataBind();
                  dg.RenderControl(htw);
                  string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\products.xls";                    
                  response.Write(sw.ToString());
                 // response.End();
  
              }
          }       
      }
  </code></pre>
  
  <p>The problem is that it's not raising file download and hence no export is taking place. The same code works fine in a normal method. But with the web method it's not working.</p>