导出数据集到Excel,并从一个asp.net web方法提高文件下载对话框 [英] Export a data set to Excel and raise a file download dialog from an asp.net web method

查看:102
本文介绍了导出数据集到Excel,并从一个asp.net web方法提高文件下载对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的code到一组数据导出到Excel表。

I am using the following code to export a data set to an Excel sheet.

[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在一个正常的方式正常工作。但随着网络的方法它不工作。

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.

推荐答案

我建议做一个HttpHandler在ASHX结束,和地点内他的code,创造Excel文件。

I suggest to make an HttpHandler ending in ashx, and place inside him your code that create the excel file.

然后从你的JavaScript code这样称呼它。

then call it from your javascript code like that.

document.location.href = "ExporttoExcel.ashx";

这篇关于导出数据集到Excel,并从一个asp.net web方法提高文件下载对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆