Output a GridView to Excel outside of page
I want to have a helper class that can serve requests from multiple pages to output contents of any gridview to excel. But if I pass in the GridView it throws an error that it must be inside "form runat='server'" tags, which makes sense. However is there anyway to do this in a seperate class that is not directly connected to any particular page?
Here is the code:
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.GetStringBu开发者_开发技巧ilder().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();
}
}
For anyone who may have this problem the solution is to add this overrided method to the page that the GridView is coming from:
public override void VerifyRenderingInServerForm(Control control)
{
return;
}
精彩评论