XuGang

记录一个程序员的成长

 

将GridView导入到Excel和word(完全可实现)

1.将GridView导入到Excel和word

需要注意两个地方:

1.EnableEventValidation="false" 必须加

2.下面这个事件必须加

public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    }

在我的资源里有相应的原代码下载

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="excel.aspx.cs" EnableEventValidation="false" Inherits="将GridView导出到Excel_excel" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>将Gridview导出到Excel,Word</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            CellPadding="4" DataKeyNames="stuid" DataSourceID="SqlDataSource1" ForeColor="#333333"
            GridLines="None">
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <Columns>
                <asp:BoundField DataField="stuid" HeaderText="编号" InsertVisible="False" ReadOnly="True"
                    SortExpression="stuid" />
                <asp:BoundField DataField="stuname" HeaderText="姓名" SortExpression="stuname" />
                <asp:CheckBoxField DataField="stusex" HeaderText="性别" SortExpression="stusex" />
                <asp:BoundField DataField="stuaddress" HeaderText="地址" SortExpression="stuaddress" />
                <asp:BoundField DataField="stuage" HeaderText="年龄" SortExpression="stuage" />
                <asp:BoundField DataField="stutuition" HeaderText="学费" SortExpression="stutuition" />
                <asp:BoundField DataField="stuaveragescore" HeaderText="成绩" SortExpression="stuaveragescore" />
            </Columns>
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <EditRowStyle BackColor="#999999" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        </asp:GridView>
   
    </div>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:myTestGridViewConnectionString %>"
            SelectCommand="SELECT * FROM [stu]"></asp:SqlDataSource>
        <asp:Button ID="Button1" runat="server" Text="导出到Excel" OnClick="Button1_Click" />
        <br />
        <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="导出到Word" Width="108px" />
    </form>
</body>
</html>

 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.IO;

public partial class 将GridView导出到Excel_excel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    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.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();

    }
    //导出到Excel
    protected void Button1_Click(object sender, EventArgs e)
    {
        ExportToExcel("application/ms-excel","学生信息.xls");

    }

    //导出到Word
    protected void Button2_Click(object sender, EventArgs e)
    {
        ExportToExcel("application/ms-excel", "学生信息.doc");
        //ExportToExcel("application/ms-word", "学生信息.doc");//都可以
       
    }

    //这个事件必须加
    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    }

}
当然上面的这些东东也是我从CSDN上面学来的,有一篇是看的青青月儿的,还有一篇,忘了是谁的啦,反正挺感谢的。


2.重载VerifyRenderingInServerForm

今天在做一个AjaxPro的应用时,VerifyRenderingInServerForm给我带来了麻烦,在网上找了找,发现大多数人的解决方法就是重载VerifyRenderingInServerForm,然后让它什么也不做。

        public override void VerifyRenderingInServerForm(Control control)
        
{
            
//base.VerifyRenderingInServerForm (control);
        }


这样做的确解决了我遇到的问题,但我看帮助对这个方法的说明,强调没有必要不要重写。

备注
如果该页当前不处于页处理中的呈现阶段,且位于 
<form runat=server> 标记内,则该方法将引发异常。需要位于服务器窗体内的控件可以在呈现期间调用该方法,以便在它们被放置到外面时显示明确的错误信息。发送回或依赖于注册的脚本块的控件应该在 Control.Render 方法的重写中调用该方法。呈现服务器窗体元素的方式不同的页可以重写该方法以在不同的条件下引发异常。

如果回送或使用客户端脚本的服务器控件没有包含在 HtmlForm 服务器控件 (
<form runat="server">) 中,它们将无法正常工作。这些控件可以在呈现时调用该方法,以在它们没有包含在 HtmlForm 控件中时提供明确的错误信息。

开发自定义服务器控件时,通常在为任何类型的输入标记重写 Render 方法时调用该方法。这在输入控件调用 GetPostBackEventReference 或发出客户端脚本时尤其重要。复合服务器控件不需要作出此调用。

除非要创建替换页框架,否则请不要重写此方法。


于是我跟踪了一下,发现页面的每个服务器端控件都会执行这个方法,结合我自己的实际情况,做了点小修改

        public override void VerifyRenderingInServerForm(Control control)
        
{
            
if (!control.GetType().Name.Equals("DataGridLinkButton"))
            
{
                
base.VerifyRenderingInServerForm (control);
            }

        }


因为我需要在AjaxMethod中获得一个控件的HTML输出到画面上,而这个控件是我new出来的,显然不可能在<form runat=server> 标记内,于是我就加了个判断,虽然还是没有做到十全十美(就是如果画面上本来就有的DataGridLinkButton也不做验证了。)但感觉比起直接把base方法调用注释掉还是合情合理些。

木野狐对这个问题也有篇文章描述了下。


3.Page.VerifyRenderingInServerForm 返回什么,怎样结合他确定是否将自定义控件写到页面上?

saucer(思归)回复于 2004-12-09 09:09:38

try   to   override   AddAttributesToRender,   for     example,   this   is   how   it   is   done   with   LinkButton   if   you   use   Reflector   to   see   the   implementation:  
   
  protected   override   void   AddAttributesToRender(HtmlTextWriter   writer)  
  {  
              if   (this.Page   !=   null)  
              {  
                          this.Page.VerifyRenderingInServerForm(this);  
              }  
              base.AddAttributesToRender(writer);  
              ....  
  }   
      
 


posted on 2007-09-14 14:05  钢钢  阅读(1289)  评论(3编辑  收藏  举报

导航