我正在尝试从Internet Explorer写出一个Excel .xls文件。一种方法是工作,就是让asp:ImageButton的click事件完成工作。就是这样:
protected void imgExport_Click(object sender, EventArgs e)
{
GridView gv = new GridView();
gv.DataSource = list; // assume this has my data
gv.DataBind();
Response.Clear();
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=RoamingPartners.xls");
StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
gv.RenderControl(hwriter);
Response.Write(swriter.ToString().Replace("<br/>", " "));
swriter.Close();
hwriter.Close();
Response.End();
}
如上所述,这可行,并写出我的文件。
但是,我不想使用asp服务器控件。相反,我将上面的内容转换为WebMethod并通过jQuery进行ajax调用。请注意这一点 类似于上面的方法,除了我必须使用HttpContext.Current.Response而不是Response:
[WebMethod]
public static void ExportData()
{
GridView gv = new GridView();
gv.DataSource = list; // assume this has my data (I use country param to get it)
gv.DataBind();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=RoamingPartners.xls");
StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
gv.RenderControl(hwriter);
HttpContext.Current.Response.Write(swriter.ToString().Replace("<br/>", " "));
swriter.Close();
hwriter.Close();
HttpContext.Current.Response.End();
}
为了更好的衡量,我的ajax电话:
$.ajax({
type: "POST",
url: "Default.aspx/ExportData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("success");
},
failure: function (response) {
alert("failure");
}
});
问题是这会引发“线程被中止”。例外。有人建议捕获异常,但我仍然没有得到我的文件。 另一个建议是使用HttpContext.Current.ApplicationInstance.CompleteRequest()而不是HttpContext.Current.Response.End(),但这也不会写出文件。我如何让它工作?