2

我正在使用以下代码将数据集导出到 Excel 工作表。

[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();

            }
        }       
    }

问题是它没有增加文件下载,因此没有导出。相同的代码在正常方法中工作正常。但是使用网络方法它不起作用。

4

3 回答 3

2

我建议制作一个以 ashx 结尾的 HttpHandler,并将创建 excel 文件的代码放入其中。

然后像这样从您的javascript代码中调用它。

document.location.href = "ExporttoExcel.ashx";
于 2010-08-06T17:34:27.120 回答
1

问题是 WebMethods 的设计目的不是让您与 Response 对象进行交互(显然它不可用,您必须使用 HttpContext.Current.Response 才能访问它)。WebMethods 被设计成对用户来说是黑盒。他们将执行和操作和/或返回一个值。

也许您可以让我们更好地了解您要完成的工作,我们可以提出替代解决方案。

于 2010-08-06T18:02:26.800 回答
-1

您可以使用将 URL 设置为 Web 处理程序的动态 iframe 来生成 Excel,这将提高文件下载而不发布当前页面。

于 2011-01-16T09:06:33.927 回答