在页面外输出GridView到Excel

时间:2011-02-24 23:12:09

标签: c# asp.net gridview httpcontext

我希望有一个帮助程序类可以处理来自多个页面的请求,以将任何gridview的内容输出到excel。但是,如果我传入GridView,它会抛出一个错误,它必须在“form runat ='server'”标签内,这是有道理的。但是,无论如何在没有直接连接到任何特定页面的单独类中执行此操作?

以下是代码:

  public class Export 
{
    public static void ToExcel(GridView control, params string[] headers)
    {
        HttpResponse context = System.Web.HttpContext.Current.Response; 

        context.AddHeader("content-disposition", "attachment;filename=Report.xls");
        context.ContentType = "application/vnd.ms-excel";
        context.Charset = "";

        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

        stringWriter.GetStringBuilder().Append("<img src='C:\\logo.png'/>");
        stringWriter.GetStringBuilder().Append("<br />");
        stringWriter.GetStringBuilder().Append("<br />");
        stringWriter.GetStringBuilder().Append("<br />");
        stringWriter.GetStringBuilder().Append("<br />");
        stringWriter.GetStringBuilder().Append("<br />");
        stringWriter.GetStringBuilder().Append("<br />");
        stringWriter.GetStringBuilder().Append("<br />");
        stringWriter.GetStringBuilder().Append("<B>");
        stringWriter.WriteLine("Usage Report:  ");
        stringWriter.GetStringBuilder().Append("</B>");
        stringWriter.GetStringBuilder().Append("<br>");
        stringWriter.GetStringBuilder().Append("<br>");
        stringWriter.GetStringBuilder().Append("<table>");
        stringWriter.GetStringBuilder().Append("<tr>");
        stringWriter.GetStringBuilder().Append("<td colspan=4 bgcolor=Gainsboro align=center>");
        stringWriter.GetStringBuilder().Append("<B>");

        foreach (string str in headers)
        {
            stringWriter.Write(str);
            stringWriter.GetStringBuilder().Append("<br />");
        }

        stringWriter.GetStringBuilder().Append("</B>");
        stringWriter.GetStringBuilder().Append("</td>");
        stringWriter.GetStringBuilder().Append("</tr>");

        control.RenderControl(htmlWriter);

        stringWriter.GetStringBuilder().Append("</table>");
        context.Write(stringWriter.ToString());
        context.End();
    }
}

1 个答案:

答案 0 :(得分:1)

对于可能遇到此问题的任何人,解决方案是将此重写方法添加到GridView来自的页面:

    public override void VerifyRenderingInServerForm(Control control)
    {
        return;
    }