private static void EportAllDataToExcel(DataTable dt)
{
System.Web.UI.WebControls.DataGrid dgExport = null;
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
System.IO.StringWriter strWrite = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
if (dt.Rows.Count > 0)
{
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.Charset = "utf-8";
curContext.Response.AddHeader("Content-Disposition", "attachment;filename=1.xls");
strWrite = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWrite);
dgExport = new System.Web.UI.WebControls.DataGrid();
dgExport.DataSource = dt.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
dgExport.RenderControl(htmlWriter);
curContext.Response.Write(strWrite);
curContext.Response.Flush();
curContext.Response.End();
}
注意:在使用asp.net制作导出时,若页面导出控件的在 <asp:UpdatePanel > 控件中时,导出不能成功,用firefox或google chrome 的控制台进行监控时 可以看到页面报:
Sys.WebForms.PageRequestManagerParserErrorException:The message received from the server
count not be parsed.Common causes for this error are when the response is modified by calls to response.Write(),response filters,HttpModules,or server trace is enabled.的错误。
此时解决方法:在<asp:UpdatePanel > 控件中加入
<Triggers>
<asp:PostBackTrigger ControlID="buttonname" /> <!-buttonname 为要触发的事件控件ID->
</Triggers>