GridView导出Excel方法
一、引用如下命名空间
using System.IO;
using System.Text;
二、详细代码
方法一:将代码直接写在页面
/// <summary>
/// 数据导出
/// </summary>
/// <param name="FileType"></param>
/// <param name="FileName"></param>
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();
}
方法二、将以上代码改进成公共方法:
/// <summary>
/// 将网格数据导出到Excel
/// </summary>
/// <param name="ctrl">网格名称(如GridView1)</param>
/// <param name="FileType">要导出的文件类型(Excel:application/ms-excel)</param>
/// <param name="FileName">要保存的文件名</param>
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");