将数据集导出到Excel,并从asp.net Web方法提出文件下载对话框

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

问题是,它不提高文件下载,因此没有出口正在发生。 相同的代码在正常的方法中工作正常。 但使用networking方法,它不工作。

我build议让一个HttpHandler以ashx结尾,并把你的代码放在他的内部,创buildexcel文件。

然后从这样的JavaScript代码中调用它。

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

问题在于WebMethods并没有devise成允许你与Response对象进行交互(很明显,它不可用,你必须使用HttpContext.Current.Response才能得到它)。 WebMethods被devise为用户的黑匣子。 他们将执行和行动和/或返回一个价值。

也许你可以给我们一个更好的想法,你正在努力完成什么,我们可以build议一个备用的解决scheme。

你可以使用创build一个dynamiciframe的URL设置为Web处理程序来生成Excel这将提高文件下载与发布当前页面。