在項(xiàng)目中我們經(jīng)常會(huì)遇到要求將一些數(shù)據(jù)導(dǎo)出成Excel或者Word表格的情況,比如中國(guó)移動(dòng)(我是中國(guó)移動(dòng)用戶)網(wǎng)上查話費(fèi)的頁面中就有一個(gè)導(dǎo)出到Excel的功能,光大網(wǎng)上銀行查看歷史明細(xì)也有這些功能....,原本以為這個(gè)問題不難的,不過看到網(wǎng)上經(jīng)常有朋友問,于是我整理了一下,供大家參考。 前臺(tái)頁面: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportDemo.aspx.cs" Inherits="ExportDemo" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www./1999/xhtml" > <head runat="server"> <title>GridView導(dǎo)出到Excel或Word文件——周公的博客:http://blog.csdn.net</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="gvPersonList" runat="server" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="Id" HeaderText="編號(hào)" /> <asp:BoundField DataField="Name" HeaderText="姓名" /> <asp:TemplateField HeaderText="性別"> <ItemTemplate> <%# Eval("Sex").ToString()=="true"?"男":"女" %> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Age" HeaderText="年齡" /> <asp:TemplateField HeaderText="婚否"> <ItemTemplate> <%# Boolean.Parse(Eval("Married").ToString())==true?"是":"否" %> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:Button ID="btnToExcel" runat="server" OnClick="btnToExcel_Click" Text="導(dǎo)出到Excel" /> <asp:Button ID="btnToWord" runat="server" OnClick="btnToWord_Click" Text="導(dǎo)出到Word" /> </div> </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; /// <summary> /// 程序說明:這是一個(gè)GridView導(dǎo)出成Excel或者Word文件的實(shí)例。為了演示,我采用了自動(dòng)生成DataTable,然后綁定。 /// 同時(shí)為了初學(xué)者查看代碼方便,關(guān)鍵處我都做了注釋。 /// 對(duì)程序說明,在asp.net 1.1中由于對(duì)控件呈現(xiàn)不是很嚴(yán)格,所以無需override void VerifyRenderingInServerForm(Control control)這個(gè)方法 /// 但在asp.net2.0中,控件的校驗(yàn)嚴(yán)格了,RenderControl代碼只有走正常流程在render方法中它自己調(diào)用才能成功, /// 在你自己寫的事件方法中調(diào)用就會(huì)出現(xiàn)這個(gè)錯(cuò)誤。這個(gè)錯(cuò)誤信息有點(diǎn)誤導(dǎo),你明明寫在服務(wù)器控件Form內(nèi),它照樣會(huì)這樣提醒你, /// 實(shí)際上是asp.net2.0設(shè)置了內(nèi)部變量控制RenderControl不允許在Render方法之外被輕易調(diào)用。如果不override VerifyRenderingInServerForm /// 就會(huì)報(bào)錯(cuò)。我們override void VerifyRenderingInServerForm(Control control)這個(gè)方法,里面不寫任何代碼即可 /// 作者:周公 /// 日期:2008-5-16 /// 網(wǎng)址:http://blog.csdn.net/zhoufoxcn /// </summary> public partial class ExportDemo : System.Web.UI.Page { private string firstName = "趙錢孫李周吳鄭王馮陳諸衛(wèi)蔣沈韓楊朱秦尤許何呂施張孔曹嚴(yán)華"; private string lastName = "猛勇剛強(qiáng)豹彪雁燕蓉菲"; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindGridView(); } } private void BindGridView() { DataTable myData = CreateDataTable(); Session["MyData"] = myData; gvPersonList.DataSource = myData; gvPersonList.DataBind(); } //手動(dòng)生成DataTable private DataTable CreateDataTable() { DataTable data = new DataTable(); DataColumn dcId = new DataColumn("ID", typeof(Int32)); //設(shè)置ID列自動(dòng)遞增 dcId.AutoIncrement = true; //設(shè)置ID列初始值為1 dcId.AutoIncrementSeed = 1; //設(shè)置ID列遞增步長(zhǎng)為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(); //隨機(jī)生成20條記錄 for (int i = 0; i < 20; i++) { dataRow = data.NewRow(); //隨機(jī)生成姓名 dataRow["Name"] = firstName.Substring(random.Next(firstName.Length), 1) + lastName.Substring(random.Next(lastName.Length), 1); //隨即生成介于20至100之間的年齡 int age = random.Next(20, 100); dataRow["Age"] = age; //隨即設(shè)置性別 bool sex = (random.Next(100) % 2 == 0) ? true : false; dataRow["Sex"] = sex; if (((sex == true) && (age >= 22)) || ((sex == false) && (age >= 20)))//男性結(jié)婚年齡大于22周歲,女性結(jié)婚年齡大于20周歲 { dataRow["Married"] = (random.Next(500) % 2 == 0) ? true : false; } else { dataRow["Married"] = false; } data.Rows.Add(dataRow); } return data; } //override掉這個(gè)方法 public override void VerifyRenderingInServerForm(Control control) { //注釋掉下面的代碼,否則在asp.net2.0下會(huì)報(bào)錯(cuò)(注:GridView是asp.net 2.0下的控件,1.1下一些控件也可以導(dǎo)出成Excel或者Word) //base.VerifyRenderingInServerForm(control); } protected void btnToExcel_Click(object sender, EventArgs e) { Response.Clear(); Response.BufferOutput = true; //設(shè)定輸出的字符集 Response.Charset = "GB2312"; //假定導(dǎo)出的文件名為FileName.xls Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //設(shè)置導(dǎo)出文件的格式 Response.ContentType = "application/ms-excel"; //關(guān)閉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(); } //導(dǎo)出成Word文件 protected void btnToWord_Click(object sender, EventArgs e) { Response.Clear(); Response.BufferOutput = true; //設(shè)定輸出的字符集 Response.Charset = "GB2312"; //假定導(dǎo)出的文件名為FileName.doc Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.doc"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); ////設(shè)置導(dǎo)出文件的格式 Response.ContentType = "application/ms-word"; //關(guān)閉ViewState gvPersonList.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(); } } 運(yùn)行效果: 需要說明的是:在asp.net2.0環(huán)境下,VerifyRenderingInServerForm(Control control)這個(gè)方法不override的話,則會(huì)出現(xiàn)“錯(cuò)誤提示:類型“GridView”的控件“GridView1”必須放在具有 runat=server 的窗體標(biāo)記內(nèi)”這個(gè)錯(cuò)誤。 |
|