我使用以下代码将数据集导出到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方法,它不起作用。
发布于 2010-08-07 01:34:27
我建议创建一个以ashx结尾的HttpHandler,并将创建excel文件的代码放入其中。
然后像这样从你的javascript代码中调用它。
document.location.href = "ExporttoExcel.ashx";发布于 2010-08-07 02:02:27
问题是WebMethods的设计并不允许您与Response对象交互(很明显,它不可用,您必须使用HttpContext.Current.Response才能访问它)。WebMethods被设计成用户的黑盒。它们将执行and操作和/或返回值。
也许你可以给我们一个更好的想法,你试图完成什么,我们可以建议一个替代的解决方案。
发布于 2011-01-16 17:06:34
您可以使用创建动态iframe,并将URL设置为Web Handler以生成Excel,这将在不发布当前页面的情况下引发文件下载。
https://stackoverflow.com/questions/3425840
复制相似问题