【问题标题】:Export a data set to Excel and raise a file download dialog from an asp.net web method将数据集导出到 Excel 并从 asp.net Web 方法引发文件下载对话框
【发布时间】:2011-03-26 10:43:12
【问题描述】:

我正在使用以下代码将数据集导出到 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();

            }
        }       
    }

问题在于它没有提高文件下载量,因此没有进行导出。相同的代码在正常方法中工作正常。但是使用 web 方法它不起作用。

【问题讨论】:

    标签: asp.net excel dataset webmethod


    【解决方案1】:

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

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

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

    【讨论】:

    • 非常感谢。实际上我需要导出数据表并异步下载文件。但是如果我使用'document.location.href',我会看到一个回发。你有什么想法吗?避免它?
    • @kranthi - 在您的通话和点击按钮上返回 false。例如 onclick="return function();",并且你的函数必须返回 false。
    • @Aristos-我使用了以下 HTML 和函数 exporttoexcel() { document.location.href="Exporttoexcel.ashx";返回假; } 但我仍然看到回发发生...
    • @kranthi 您需要提供 javascript 代码,可能是在其他问题上,有些会帮助您。
    【解决方案2】:

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

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

    【讨论】:

    • 其实,这里使用 webmethod 的原因是我们想用 Jquery 异步完成导出操作。你能建议一个替代方案来满足我的要求吗?
    • 如果是这样,我只能回应@Aristos的建议。将 HttpHandler 创建为 ashx 类。将现有的 Excel 代码复制到 ashx 页面中。然后,您可以使用 ASHX 页面,就好像它是位于该位置的服务器上的 Excel 电子表格的 URL。
    • 听起来是个好主意。我刚刚尝试了@Aristos 的想法,这似乎工作正常。非常感谢。
    • 我尝试了@Aristos 的想法。但是当我重定向到 handler.ashx 页面时,我看到了一个回发。有没有办法避免它?
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 2014-12-21
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      相关资源
      最近更新 更多