GridView导出Excel最佳方案
一、通用类
/// <summary>
/// Summary description for Common
/// </summary>
public class Common
{
public delegate void OnDataBind(object sender, EventArgs e);
/// <summary>
/// 将网格数据导出到Excel
/// </summary>
/// <param name="ctrl">网格名称(如GridView)</param>
/// <param name="onDataBind">委托(绑定方法)</param>
public static void GridViewToExcel(GridView ctrl, OnDataBind onDataBind)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "GB2312";
string filename = "attachment;filename=" + HttpUtility.UrlEncode("MyExcelFile.xls", Encoding.UTF8).ToString();
HttpContext.Current.Response.AppendHeader("Content-Disposition", filename);
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
//取消分页,加载所有数据
ctrl.AllowPaging = false;
onDataBind(new object(), new EventArgs());
//导出数据到Excel
ctrl.RenderControl(oHtmlTextWriter);
HttpContext.Current.Response.Output.Write(oStringWriter.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
////设置分页,恢复数据
//ctrl.AllowPaging = true;
//ctrl.PageIndex = 0;
//onDataBind(new object(), new EventArgs());
}
}
二、页面调用
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void lbtnToExcel_Click(object sender, EventArgs e)
{
Common.GridViewToExcel(gvHarmlessList, new Common.OnDataBind(BindData));
}
public override void VerifyRenderingInServerForm(Control control)
{ }
说明:BindData为GridView数据绑定方法,目的是取消分页,重新加载数据。
三、样式设置
如果列表中有数字型的列,则需要在RowDataBound事件下设置样式。例如:e.Row.Cells[4].Attributes.Add("style", "vnd.ms-excel.numberformat:@");