![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
/// <summary>
/// EXCEL导出方法
/// </summary>
/// <param name="control">控件名称</param>
/// <param name="filename">文件名称</param>
public void ToExcel(System.Web.UI.Control control, string filename)
{
//定义文档类型、字符编码
System.Web.HttpContext.Current.Response.Charset = "GB2312";
//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
//filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt .htm
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//Response.ContentType指定文件类型 可以为application/ms-excel、application/ms-word、application/ms-txt、application/ms-html 或其他浏览器可直接支持文档
System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
control.Page.EnableViewState = false;
control.RenderControl(hw);
System.Web.HttpContext.Current.Response.Write(tw);
System.Web.HttpContext.Current.Response.End();
}
/// EXCEL导出方法
/// </summary>
/// <param name="control">控件名称</param>
/// <param name="filename">文件名称</param>
public void ToExcel(System.Web.UI.Control control, string filename)
{
//定义文档类型、字符编码
System.Web.HttpContext.Current.Response.Charset = "GB2312";
//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
//filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt .htm
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//Response.ContentType指定文件类型 可以为application/ms-excel、application/ms-word、application/ms-txt、application/ms-html 或其他浏览器可直接支持文档
System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
control.Page.EnableViewState = false;
control.RenderControl(hw);
System.Web.HttpContext.Current.Response.Write(tw);
System.Web.HttpContext.Current.Response.End();
}
当出现"类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内。"错误时.在导出页面重载VerifyRenderingInServerForm方法。
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
}
{
}