今天写了一个导出数据的代码,将数据导出到Excel和Doc中,方法如下:
public void ExportToExcel(string FileType, string FileName)
{
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
调用该方法分别导出到Excel和Doc中:
ExportToExcel("application/ms-excel", "学生信息.xls");和 ExportToExcel("application/ms-excel", "学生信息.doc");
运行时提示错误:System.Web.HttpException: 类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内。此时增加:
public override void VerifyRenderingInServerForm(Control control)
{
}
如果提示:System.InvalidOperationException: 只能在执行 Render() 的过程中调用 RegisterForEventValidation;哪是gridview的allowpaging属性设置为true则应该在<%@ Page Language="C#" Debug="true" %>中增加EnableEventValidation="false" 属性。
这样就一切OK啦!