导出到excel,如果不保存,会自动关闭页面的问题

 // 不显示删除回复显示所有回复显示星级回复显示得分回复 DataGrid导出到excel,如果不保存,会自动关闭页面的问题
                    //HttpContext.Current.Response.AppendHeader( "Content-Disposition ", "attachment;filename=Excel.xls ")   中去掉“attachment;”即可

public   void   DGToExcel(DataGrid   dataGrid)      
    {  
      HttpContext.Current.Response.AppendHeader( "Content-Disposition ", "attachment;filename=Excel.xls ");  
      HttpContext.Current.Response.Charset   = "UTF-8 ";          
      HttpContext.Current.Response.ContentEncoding   =System.Text.Encoding.Default;  
      HttpContext.Current.Response.ContentType   = "application/ms-excel ";
      dataGrid.Page.EnableViewState   =false;        
      System.IO.StringWriter     tw   =   new   System.IO.StringWriter()   ;  
      System.Web.UI.HtmlTextWriter   hw   =   new   System.Web.UI.HtmlTextWriter   (tw);  
      dataGrid.RenderControl(hw);  
      HttpContext.Current.Response.Write(tw.ToString());  
      HttpContext.Current.Response.End();  
    }  

 

  DataTable dt = (System.Data.DataTable)GridView1.DataSource;
                    string name = Server.MapPath("") + "//PsExcel//" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";
                    FileStream fs = new FileStream(name, FileMode.Create, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("gb2312"));
                    sw.WriteLine("人员工号,人员名称,帐号,初始密码,邮箱,手机,部门");
                    foreach (DataRow dr in dt.Rows)
                    {
                        sw.WriteLine(dr["Ps_NO"] + "," + dr["Ps_Name"] + "," + dr["Accounts"] + "," + dr["iniPassWord"] + "," + dr["Email"] + "," + dr["Phone"] + "," + dr["Org_Name"]);
                    }
                    sw.Close();
                    Response.AddHeader("Content-Disposition", "filename=" + Server.UrlEncode(name));
                    Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
                    Response.WriteFile(name); // 把文件流发送到客户端
                    Response.End();

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页