【发布时间】:2011-03-26 08:36:38
【问题描述】:
我正在尝试使用以下代码将数据集从 asp.net 页面方法(webmethod)导出到 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();
}
}
}
上面的代码似乎工作正常,除了下载文件对话框没有打开询问用户是否“保存”/“打开”对话框,因此我没有看到正在写入文件的响应。相反,当我在 Firebug 中检查响应时,我以 HTML 表格结构获取数据。
请问有人可以帮我吗?
谢谢。
【问题讨论】:
标签: .net excel ado.net dataset