[转]GridView导出Excel总结
GridView导出Excel方法
一、引用如下命名空间
using System.IO;
using System.Text;
二、详细代码
方法一:将代码直接写在页面
///
/// 数据导出
///
///
///
private void Export(string FileType, string FileName)
{
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;//注意编码
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
gridGatewayDetails.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
方法二、将以上代码改进成公共方法:
///
/// 将网格数据导出到Excel
///
/// 网格名称(如GridView1)
/// 要导出的文件类型(Excel:application/ms-excel)
/// 要保存的文件名
public static void GridViewToExcel(Control ctrl, string FileType, string FileName)
{
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;//注意编码
HttpContext.Current.Response.AppendHeader("Content-Disposition",
"attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
HttpContext.Current.Response.ContentType = FileType;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
ctrl.Page.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctrl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
三、注意事项:
在导出的时候,如果某个字段为长数字(如身份证号码511922198507151512)、以0开头的编号(如0809111212)之类的数据。如果不加处理在导出的Excel文件中将会被分别当作5.11922E+17和809111212来处理,这样与我们要达到 的实际效果不一致。所以我们要加以处理,即给单元格数据规定格式。常见的格式如下:
1) 文本:vnd.ms-excel.numberformat:@
2) 日期:vnd.ms-excel.numberformat:yyyy/mm/dd
3) 数字:vnd.ms-excel.numberformat:#,##0.00
4) 货币:vnd.ms-excel.numberformat:¥#,##0.00
5) 百分比:vnd.ms-excel.numberformat: #0.00%
使用方法如下:
//给第一个单元格设置格式为
e.Item.Cells[0].Attributes.Add("style","vnd.ms-excel.numberformat:@");
//给第四个单元格设置格式为
e.Item.Cells[3].Attributes.Add("style","vnd.ms-excel.numberformat:¥#,###.00");
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/suchgoingdown/archive/2009/03/10/3977013.aspx
转载于:https://www.cnblogs.com/itzsl/archive/2010/02/21/1670163.html
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
