views:

54

answers:

0

Hi,

I am trying to export a dataset to excel from asp.net page method(webmethod) using the following 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();

            }
        }       
    }

Above code seems to be working ok except for the thing that the download file dialog does not open up to ask user whether 'Save'/'Open' the dialog and hence I do not see the response being written to a file.Instead I am getting the data in a HTML tabular structure,when I checked for the response in Firebug.

Please could someone help me with it?

Thanks.