开发者

Problem exporting a dataset to excel from a webmethod using asp.net

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.


If you can get your product data into a DataTable, try the following instead:

protected void ExportToExcel(DataTable myTable, string name)
    {
        //Set Response
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename="+name+".xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";

        //Print columns headers
        //manually create column headers
        Response.Write("Column1" + "\t");
        Response.Write("Column2" + "\t");
        Response.Write("\n");

        foreach (DataRow row in myTable.Rows) // Loop over the rows.
        {
            Response.Write(row["column1_database_name"].ToString() + "\t");
            Response.Write(row["column2_database_name"].ToString() + "\t");
            Response.Write("\n");
        }

        //End Response
        Response.End();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜