/// 导出excel表格
///</summary>
publicstatic void SaveToExcel(System.Web.UI.Control ctl, stringfilename)
{
//清除客户端当前显示
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "GB2312";
//显示标头
HttpContext.Current.Response.AddHeader("Content-Disposition","attachment; filename=" +System.Web.HttpUtility.UrlEncode(filename,System.Text.Encoding.UTF8) + ".xls");//这样的话,可以设置文件名为中文,且文件名不会乱码。其实就是将汉字转换成UTF8
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
//HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.UTF7;
// 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!
HttpContext.Current.Response.ContentType ="application/ms-excel";//设置输出文件类型为excel文件。
StringWriter stringWrite = new System.IO.StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
ctl.RenderControl(htmlWrite);
HttpContext.Current.Response.Write(stringWrite.ToString());
HttpContext.Current.Response.End();
//HttpContext.Current.Response.Clear();
//HttpContext.Current.Response.Buffer = true;
//HttpContext.Current.Response.Charset = "utf-8";
//HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=" + Server.UrlEncode(filename));
//HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;//设置输出流为简体中文
//HttpContext.Current.Response.ContentType ="application/ms-excel";//设置输出文件类型为excel文件。
//this.EnableViewState = false;
//System.Globalization.CultureInfo myCItrad = newSystem.Globalization.CultureInfo("ZH-CN", true);
//System.IO.StringWriter oStringWriter = newSystem.IO.StringWriter(myCItrad);
//System.Web.UI.HtmlTextWriter oHtmlTextWriter = newSystem.Web.UI.HtmlTextWriter(oStringWriter);
//ctl.RenderControl(oHtmlTextWriter);
//HttpContext.Current.Response.Write(oStringWriter.ToString());
//HttpContext.Current.Response.End();
}
}
用此方法导出excel后,通过office2007打开会提示“您尝试打开的文件.xls的格式与文件扩展名指定的格式不一致”,选择打开文件后内容是正确的。原因尚未弄清!待解决
可参看
http://topic.csdn.net/u/20090322/01/b26d6fad-79d7-4963-8317-c7eefdb97072.html