导出GridView到Excel中

时间:2006/5/26 19:23:52      阅读:4958          
导出GridView到Excel中的关键之处
用法: ToExcel(GVStaff, TextBox1.Text)
 1Public Shared  Sub ToExcel(ByVal ctl As System.Web.UI.Control, ByVal FileName As String)
 2            HttpContext.Current.Response.Charset ="UTF-8"
 3            HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default
 4            HttpContext.Current.Response.ContentType ="application/ms-excel"
 5            HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+""+FileName+".xls")
 6            ctl.Page.EnableViewState =False
 7            Dim tw As System.IO.StringWriter =  New System.IO.StringWriter() 
 8            Dim hw As HtmlTextWriter =  New HtmlTextWriter(tw) 
 9            ctl.RenderControl(hw)
10            HttpContext.Current.Response.Write(tw.ToString())
11            HttpContext.Current.Response.End()
12End Sub

必须有下面这句!否则不会通过!

1Public Overrides  Sub VerifyRenderingInServerForm(ByVal control As Control)
2        ' Confirms that an HtmlForm control is rendered for
3End Sub

当用GridView导出Execl的时候,会发生只能在执行 Render() 的过程中调用 RegisterForEventValidation的错误提示。
有两种方法可以解决以上问题:
1.修改web.config(不推荐)<pages enableEventValidation ="false" ></pages>
2.直接在导出Execl的页面修改

<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true"

 CodeFile="ExportGridView.aspx.cs" Inherits="ExportGridView" %>

评论
  • Re:导出GridView到Excel中  (2006/6/16 11:29:52) by towaim 
    very good
    非常感谢
标 题:
 
姓 名:
 
主 页:

验证码:

评论:
 

Because of the cache,you may see your comments several minutes later.