页面导出excel 后无奈的面对了另一个问题
就是导出excel 表之后 页面上的所有按钮 点击都没有反应,需要重新载入
在页面导出excel代码如下:
public void DataTableToExcel(DataTable dt,string filename) { if (dt != null & dt.Rows.Count > 0) { Response.Clear(); Response.Buffer = true; //Response.Charset = "utf-8"; Response.ContentEncoding = System.Text.Encoding.Default; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename, Encoding.Default).ToString()); Response.ContentType = "application/vnd.ms-excel"; this.EnableViewState = false; StringWriter oStringWriter = new StringWriter(); HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter); Response.Write(style); DataGrid ExcelDG = new DataGrid(); ExcelDG.DataSource = dt; ExcelDG.DataBind(); ExcelDG.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter.ToString()); Response.End(); } }
刚开始 我以为是response的 表头属性的缘故 或者是 response.Write 这个方法的问题
几经搜索,发现 是由于 response.end() 的缘故
所有 只需要写一个方法 refresh()放到 page_load 里 问题就解决了。
VB.NET 这个是根据C#的代码改写的 使用了 StringBuilder 。
sub refresh()
Dim beforeSubmitJS As StringBuilder = New StringBuilder()
beforeSubmitJS.Append("var exportRequested = false;" & vbCrLf)
beforeSubmitJS.Append("var beforeFormSubmitFunction =
theForm.onsubmit;" & vbCrLf)
beforeSubmitJS.Append("theForm.onsubmit = function(){ " & vbCrLf)
beforeSubmitJS.Append("var returnVal = beforeFormSubmitFunction();" &
vbCrLf)
beforeSubmitJS.Append("if(exportRequested &&
returnVal) {_spFormOnSubmitCalled=false; exportRequested=false;}" &
vbCrLf)
beforeSubmitJS.Append("return returnVal;" &
vbCrLf)
beforeSubmitJS.Append("}; " & vbCrLf)
Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), "alterFormSubmitEvent", beforeSubmitJS.ToString(), True)
Me.btnClose.Attributes("onclick") =
"javascript:exportRequested=true;"
Me.btnSave2Excel.Attributes("onclick") =
"javascript:exportRequested=true;"
Me.btnSelect.Attributes("onclick")
= "javascript:exportRequested=true;"
end sub
C#
public void refresh(Button btn)
{
string beforeSubmitJS = "\nvar exportRequested = false; \n";
beforeSubmitJS += "var beforeFormSubmitFunction = theForm.onsubmit;\n";
beforeSubmitJS += "theForm.onsubmit = function(){ \n";
beforeSubmitJS += "var returnVal = beforeFormSubmitFunction(); \n";
beforeSubmitJS += "if(exportRequested && returnVal) {_spFormOnSubmitCalled=false; exportRequested=false;} \n";
beforeSubmitJS += "return returnVal; \n";
beforeSubmitJS += "}; \n";
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alterFormSubmitEvent", beforeSubmitJS, true);
btn.Attributes["onclick"] = "javascript:exportRequested=true;";
}
调用例如下:
protected void Page_Load(object sender, EventArgs e)
{
refresh(btnExport);//这里改成你的按钮的名字即可
}
原理:页面按钮提交时会调用一个内置的方法并修改一个内置变量_spFormOnSubmitCalled,我们通过按钮来调用方法重置
这个参数的值,达到系统检索页面时,一直默认为未提交状态。