/// <summary> /// ToExcel() /// </summary> public void ToExcel() { Response.Clear(); //清除缓冲区流中的所有内容输出 Response.Buffer = true; // Response.Charset = "GB2312"; //设置输出流的http字符集 //保存附件用"attachment;filename=bang.xls";在线打开用"online;filename=bang.xls" //可以是.doc、.xls、.txt、.htm、 Response.AppendHeader("Content-Disposition", "attachment;filename=bang.xls"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文 //设置输出文件类型为excel文件。保存为word时,应为"application/ms-word" //可以为application/ms-excel、application/ms-word、application/ms-txt、application/ms-html、或其他浏览器可直接支持文档 Response.ContentType = "application/ms-excel"; this.EnableViewState = false; //关闭保存视图状态 System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);//区域设置 System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); gvToExcel.RenderControl(oHtmlTextWriter); //将DataGrid(dgBang)中的内容输出到oHtmlTextWriter Response.Write(oStringWriter.ToString()); Response.End();//将当前所有缓冲的输出发送到客户端,并停止该页执行 }