前台代码:
<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" CodeFile="Default4.aspx.cs" Inherits="Default4" %>
<!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>无标题页</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="gvPersonList" runat="server" AutoGenerateColumns="False" AllowPaging="True" onpageindexchanging="gvPersonList_PageIndexChanging"> <Columns> <asp:TemplateField HeaderText="编号"> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("Id") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Name" HeaderText="姓名" /> <asp:TemplateField HeaderText="性别"> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Eval("Sex").ToString().ToLower()=="true"?"男":"女" %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="婚否"> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<%#Boolean.Parse(Eval("Married").ToString())==true?"是":"否" %>'></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:Button ID="btnToExcel" runat="server" Text="导出Excel" onclick="btnToExcel_Click" /> <asp:Button ID="btnToWord" runat="server" Text="导出Word" onclick="btnToWord_Click" /> </div> </form> </body> </html>
后台代码:
using System; using System.Collections; using System.Configuration; using System.Data; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts;
public partial class Default4 : System.Web.UI.Page {
private string firstName = "赵钱孙李周吴郑王冯陈诸卫蒋沈韩杨朱秦尤许何吕施张孔曹严华"; private String lastName = "猛勇刚强豹彪雁燕蓉菲";
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindGridView(); } }
//绑定表格GridView数据 private void BindGridView() { gvPersonList.DataSource = CreateDataTable(); gvPersonList.DataBind(); }
//手动生成DataTable private DataTable CreateDataTable() { DataTable data = new DataTable(); //ID列 DataColumn dcid = new DataColumn("id", typeof(Int32)); //设置ID列自动递增 dcid.AutoIncrement = true; //设置ID列初始值为1 dcid.AutoIncrementSeed = 1; //设置ID列递增步长为1 dcid.AutoIncrementStep = 1; //将ID列添加到DataTable中 data.Columns.Add(dcid); data.Columns.Add(new DataColumn("Name", typeof(String))); data.Columns.Add(new DataColumn("Age", typeof(int))); data.Columns.Add(new DataColumn("Sex", typeof(bool))); data.Columns.Add(new DataColumn("Married", typeof(bool))); DataRow dataRow = null; Random random = new Random(); for (int i = 0; i < 20; i++) { dataRow = data.NewRow(); //随机生成姓名 dataRow["Name"] = firstName.Substring(random.Next(firstName.Length), 1) + lastName.Substring(random.Next(lastName.Length), 1); //随机生成年龄 int age = random.Next(20, 100); dataRow["Age"] = age; //随机生成性别 bool sex = (random.Next(100) % 2 == 0) ? true : false; dataRow["Sex"] = sex; if (sex == true && age >= 22 || sex == false && age >= 20) { dataRow["Married"] = (random.Next(500) % 2 == 0) ? true : false; } else { dataRow["Married"] = false; }
data.Rows.Add(dataRow); }
return data; }
/// <summary> /// 导出数据函数 /// </summary> /// <param name="FileType">导出文件MIME类型</param> /// <param name="FileName">导出文件的名称</param> private void Exprot(String FileType, String FileName) { Response.Clear(); Response.BufferOutput = true; //设定输出字符集 Response.Charset = "GB2312"; Response.ContentEncoding = System.Text.Encoding.UTF8; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)); //设置输出流HttpMiME类型(导出文件格式) Response.ContentType = FileType; //关闭ViewState Page.EnableViewState = false; System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("ZH-CN", true); System.IO.StringWriter stringWriter = new System.IO.StringWriter(cultureInfo); HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter); gvPersonList.RenderControl(textWriter); //把HTML写回游览器 Response.Write(stringWriter.ToString()); Response.End(); Response.Flush(); }
//导出Excel protected void btnToExcel_Click(object sender, EventArgs e) { //Response.Clear(); //Response.BufferOutput = true; ////设定输出的字符集 //Response.Charset = "utf-8"; ////假定导出的文件名为FileName.xls //Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls"); //Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); ////设置导出文件的格式 //Response.ContentType = "application/ms-excel"; ////关闭ViewState //EnableViewState = false; //System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("ZH-CN", true); //System.IO.StringWriter stringWriter = new System.IO.StringWriter(cultureInfo); //System.Web.UI.HtmlTextWriter textWriter = new System.Web.UI.HtmlTextWriter(stringWriter); //gvPersonList.RenderControl(textWriter); ////把HTML写回浏览器 //Response.Write(stringWriter.ToString()); //Response.End(); Exprot("application/ms-excel","Employee.xls"); }
//导出Word protected void btnToWord_Click(object sender, EventArgs e) { //这里将导出的方法抽取了出来使用 Exprot("application/ms-word", "Employee.doc"); }
//确认在运行时为指定的 ASP.NET 服务器控件呈现在 HtmlForm 控件中。 //(检验Asp.Net服务器空间是否呈现在HTMLForm控件中) public override void VerifyRenderingInServerForm(Control control) { /* 对程序说明,在asp.net 1.1中由于对控件呈现不是很严格, * 所以无需override void VerifyRenderingInServerForm(Control control)这个方法 * 但在asp.net2.0中,控件的校验严格了,RenderControl代码只有走正常流程在render方法 * 中它自己调用才能成功,在你自己写的事件方法中调用就会出现这个错误。这个错误信息有点误导, * 你明明写在服务器控件Form内,它照样会这样提醒你, * 实际上是asp.net2.0设置了内部变量控制RenderControl不允许在Render方法之外被轻易调用。 * 如果不override VerifyRenderingInServerForm就会报错。 * 我们override void VerifyRenderingInServerForm(Control control)这个方法, * 里面不写任何代码即可*/ //base.VerifyRenderingInServerForm(control); }
/// <summary> /// 分页 /// </summary> protected void gvPersonList_PageIndexChanging(object sender, GridViewPageEventArgs e) { gvPersonList.PageIndex = e.NewPageIndex; BindGridView(); } }
需要注意的部分:
需要注意的是:在asp.net2.0环境下,VerifyRenderingInServerForm(Control control)这个方法不override的话,则会出现“错误提示:类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内”这个错误。
分页的情况下如果不想就得到一页的数据需要导出所有的数据:
1.由于gridview的内容可能是分页显示的,因此,这里在每次导出excel时,先将gridview的allowpaging属性设置为false,然后databind()一下,确保得到所有数据;
2.不用单独设置导出的路径,导出时会弹出对话框让你确认保存位置;
3.要写一个空的VerifyRenderingInServerForm方法(必须写),以确认在运行时为指定的ASP.NET 服务器控件呈现HtmlForm 控件;
4.导出后别忘记再重新设置其allowpaging属性; 当我把这些都设置好以后,点击[导出],出现了只能在执行 Render() 的过程中调用 RegisterForEventValidation(RegisterForEventValidation can only be called during Render(); ) 的错误,又检查代码,没发现问题啊,搞了一会弄不出来,然后搜索了一下,发现了解决办法: 修改你的aspx文件中的: <%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true" CodeFile="SysUser.aspx.cs" Inherits="Autho_SysUser2" %>
增加红色的部分就ok了。最后补充一点:千万不要和无刷新面板同时使用。会很麻烦!
|