ASP.NET 导出表格,文本文件等记录
时间:2011-02-16 来源:Rainr
1.导出表格
代码 private void ToExcel(Control control, string fileName){
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";
//这里文件名称使用一下Url编码,防止中文导致的乱码问题
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
TextWriter tw = HttpContext.Current.Response.Output;
HtmlTextWriter htw = new HtmlTextWriter(tw);
control.RenderControl(htw);
HttpContext.Current.Response.End();
}
2.导出文本
代码 private void ToTXT(string[] contents, string fileName){
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
//和导出表格一样的道理,这里输出的内容类型修改下.
HttpContext.Current.Response.ContentType = "application/ms-txt";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
TextWriter tw = HttpContext.Current.Response.Output;
foreach (string str in contents)
tw.WriteLine(str);
HttpContext.Current.Response.End();
}
相关阅读 更多 +