您的位置:首页 > 数据库

将数据库中的数据导出到Excel和Doc中

2007-10-11 16:22 309 查看
今天写了一个导出数据的代码,将数据导出到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啦!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: