方案一: //注:在.aspx文件中第一行<%%>中加入EnableEventValidation="false" <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CardSelect.aspx.cs" Inherits="PersonMag" EnableEventValidation="false" %> //这里一定要引入命名空间 using System.Data.SqlClient; //为导入Excel引入命名空间 using System.Drawing; using System.IO; using System.Text; private void GridViewBind() { //GridView的绑定 } private void Export(string FileType, string FileName) { //GridView导出到Excel,导出所有页 Response.Charset = "GB2312"; Response.ContentEncoding = System.Text.Encoding.UTF8;//换成UTF7编码出现乱码 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); this.GridView1.AllowPaging = false;//取消分页 this.GridView1.AllowSorting = false;//取消排序 //this.GridView1.AutoGenerateColumns = true;//取消自动生成列 this.GridViewBind();//GridView的独立绑定函数 GridView1.RenderControl(hw); Response.Write(tw.ToString()); Response.End(); } protected void btnSqlToExcel_Click(object sender, EventArgs e) { //SqlToExcel按钮响应的事件 Export("application/ms-excel", "信息表.xls");//第一个参数是导出的类型,第二个参数是导出表的名称 } public override void VerifyRenderingInServerForm(Control control) { //重写此方法,确保程序运行时,指定的GridView控件总是位于<form runat="server">标记内 //base.VerifyRenderingInServerForm(control); } 方案二: public void CreateExcel(DataSet ds, string FileName) { StringBuilder sb = new StringBuilder(); StringBuilder sbb = new StringBuilder(); HttpResponse resp; resp = Page.Response; resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); resp.ContentType = "application/ms-excel"; resp.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls"); this.EnableViewState = false; string colHeaders = "", Is_item = ""; int i = 0; //定义表对象与行对象,同时使用DataSet对其值进行初始化 DataTable dt = ds.Tables[0]; DataRow[] myRow = dt.Select(""); //取得数据表各列标题,标题之间以/t分割,最后一个列标题后加回车符 colHeaders += "<table cellspacing=/"0/" cellpadding=/"5/" rules=/"all/" border=/"1/">"; colHeaders += "<tr style="/" mce_style="/""font-weight: bold; white-space: nowrap;/">"; for (i = 0; i < dt.Columns.Count; i++) { colHeaders += "<td>" + dt.Columns[i].Caption.ToString() + "</td>"; } colHeaders += "</tr>"; resp.Write(colHeaders); //逐行处理数据 foreach (DataRow row in myRow) { Is_item += "<tr>"; //在当前行中,逐列取得数据,数据之间以/t分割,结束时加回车符/n for (i = 0; i < dt.Columns.Count; i++) { if (dt.Columns[i].ColumnName.Equals("银行帐号") || dt.Columns[i].ColumnName.Equals("身份证号")) Is_item += "<td style="/" mce_style="/""vnd.ms-excel.numberformat:@/">" + row[i].ToString() + "</td>"; else Is_item += "<td>" + row[i].ToString() + "</td>"; } Is_item += "</tr>"; resp.Write(Is_item); Is_item = ""; } resp.Write("</table>"); //写缓冲区中的数据到HTTP头文件中 resp.End(); }