/// <summary>
/// 导出Excel
/// </summary>
/// <param name="col"> Grid</param>
/// <param name="title">导出标题</param>
/// <param name="filename">导出名称</param>
/// <returns></returns>
public static bool ToExcel(GridView gv ,string fname)
{
try
{
string filename = HttpUtility.UrlEncode(fname + ".xls", System.Text.Encoding.UTF8);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Charset = "GB2312";
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename = " + filename);
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
gv.Page.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.RenderControl(hw);
System.Web.HttpContext.Current.Response.Write(fname);//这里添加一行设置标题
System.Web.HttpContext.Current.Response.Write("<br>制表日期:" + DateTime.Now.ToShortDateString());//这里添加一行设置标题
System.Web.HttpContext.Current.Response.Write(sw.ToString());
System.Web.HttpContext.Current.Response.End();
}
catch (System.Exception ex)
{
Console.Write(ex.Message);
return false;
}
return true;
}
补充:如果需要导出gridview所有数据及不分页;则在使用此方法前,需要设置
gridview1.allowpaging = false;
gridview1.databind();