日期:2014-05-18 浏览次数:20831 次
/// <summary> /// 导出Excel /// </summary> /// <param name="page">操作页面</param> /// <param name="fileName">导出的文件名称</param> /// <param name="text">要导出的内容</param> public void ExportExcel(Page page, string text) { page.EnableViewState = false; try { page.Response.ClearContent(); page.Response.Buffer = true; page.Response.Charset = "GB2312";//设置字符集,解决中文乱码问题 page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); page.Response.Write("<meta http-equiv=Content-Type content=\"text/html;charset=GB2312\">");//解决乱码问题 //解决HTTP头中文乱码问题 string strExcelText = "数据统计" + DateTime.Now.Date.ToShortDateString();//Excel显示的内容 string strEncode = System.Web.HttpUtility.UrlEncode(strExcelText, System.Text.Encoding.UTF8);//进行编码的格式,用gb2312出错 page.Response.AddHeader("content-disposition", "attachment;filename=\"" + strEncode + ".xls\"");//对保存标题进行编码 page.Response.ContentType = "application/vnd.xls";//设置输出格式 page.Response.Write(@"<html><body>"); StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); htw.WriteLine(text);//将数据输出 page.Response.Write(sw.ToString()); page.Response.Write("</body></html>"); page.Response.Flush(); page.Response.End(); } catch { return; } finally { //恢复原来控件内容 page.EnableViewState = true; } }