前台代码如下不多说:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false"%> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 3 <html xmlns="http://www.w3.org/1999/xhtml"> 4 <head runat="server"> 5 <title>无标题页</title> 6 <style type="text/css"> 7 #form1 8 { 9 height: 645px; 10 } 11 </style> 12 </head> 13 <body> 14 <form id="form1" runat="server"> 15 <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 16 AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" 17 GridLines="None" Height="234px" 18 onpageindexchanging="GridView1_PageIndexChanging" Width="782px"> 19 <PagerSettings FirstPageText="首页" LastPageText="尾页" 20 Mode="NextPreviousFirstLast" NextPageText="下一页" PreviousPageText="上一页" /> 21 <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> 22 <Columns> 23 <asp:BoundField DataField="id" HeaderText="序号"> 24 <ItemStyle HorizontalAlign="Center" /> 25 </asp:BoundField> 26 <asp:BoundField DataField="StuId" HeaderText="学号"> 27 <ItemStyle HorizontalAlign="Center" /> 28 </asp:BoundField> 29 <asp:BoundField DataField="StuPwd" HeaderText="密码"> 30 <ItemStyle HorizontalAlign="Center" /> 31 </asp:BoundField> 32 <asp:BoundField DataField="StuName" HeaderText="姓名"> 33 <ItemStyle HorizontalAlign="Center" /> 34 </asp:BoundField> 35 <asp:BoundField DataField="StuCardId" HeaderText="身份证号"> 36 <ItemStyle HorizontalAlign="Center" /> 37 </asp:BoundField> 38 <asp:BoundField DataField="TeaName" HeaderText="任课教师"> 39 <ItemStyle HorizontalAlign="Center" /> 40 </asp:BoundField> 41 </Columns> 42 <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 43 <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> 44 <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> 45 <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 46 <EditRowStyle BackColor="#999999" /> 47 <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> 48 </asp:GridView> 49 <br /> 50 <br /> 51 <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 52 Text="导出到Excel" /> 53 </form> 54 </body> 55 </html>
后台代码如下:注释很详细不再累赘
1 using System; 2 using System.Configuration; 3 using System.Data; 4 using System.Linq; 5 using System.Web; 6 using System.Web.Security; 7 using System.Web.UI; 8 using System.Web.UI.HtmlControls; 9 using System.Web.UI.WebControls; 10 using System.Web.UI.WebControls.WebParts; 11 using System.Xml.Linq; 12 using System.Data.SqlClient;///添加数据库操作的命名空间 13 using System.IO;///添加输出操作的命名空间 14 public partial class _Default : System.Web.UI.Page 15 { 16 /// <summary> 17 /// 绑定Gridview 控件的数据 18 /// </summary> 19 /// <returns></returns> 20 protected bool BindDB() 21 { 22 string sqlcon = ConfigurationManager.ConnectionStrings["DBString"].ConnectionString; 23 SqlConnection con = new SqlConnection(sqlcon); 24 con.Open(); 25 string strSelect = "select * from Student "; 26 SqlDataAdapter sda = new SqlDataAdapter(strSelect,sqlcon); 27 DataSet ds = new DataSet(); 28 sda.Fill(ds); 29 GridView1.DataSource = ds; 30 try 31 { 32 GridView1.DataBind(); 33 return true; 34 } 35 catch 36 { 37 return false; 38 } 39 finally 40 { 41 con.Close(); 42 } 43 } 44 protected void Page_Load(object sender, EventArgs e) 45 { 46 if (!IsPostBack) 47 { 48 BindDB();///数据库绑定 49 } 50 } 51 /// <summary> 52 /// Gridview 分页操作 没有分业的可以不添加此方法 53 /// </summary> 54 /// <param name="sender"></param> 55 /// <param name="e"></param> 56 protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) 57 { 58 GridView1.PageIndex = e.NewPageIndex; 59 BindDB(); 60 } 61 /// <summary> 62 /// Gridview数据导出到Excel的操作 63 /// </summary> 64 /// <param name="sender"></param> 65 /// <param name="e"></param> 66 protected void Button1_Click(object sender, EventArgs e) 67 { 68 #region 69 ///在导出的时候,如果某个字段为长数字(如身份证号码511922198507151512)、以0开头的编号(如0914490000) 70 ///之类的数据。如果不加处理在导出的Excel文件中将会被分别当作5.11922E+17和809111212来处理,这样与我们要达到的 71 ///实际效果不一致。所以我们要加以处理,即给单元格数据规定格式 72 ///即我们在导出的时候把类型改掉 73 //for (int i=0; i < GridView1.Rows.Count; i++) 74 //{ 75 // GridView1.Rows[i].Cells[4].Text = "'" + GridView1.Rows[i].Cells[4].Text; 76 //} 77 #endregion 78 79 ///另一种方式就是 80 ///解决思路:在Excel中作一个包含有"012457890"的内容,设定单元格的显示方式,然后保存成Html的文件, 81 ///在查看源代码. 发现在 CSS格式定义中有:td{mso-number-format:"\@";}.这样问题就容易解决了.我用的此种方式 82 83 GridView1.AllowPaging = false;///清除分页,便于导出数据 84 BindDB(); ///绑定Griedview数据 85 Response.ClearContent(); 86 Response.Charset = "GB2312"; ///设定输出的字符集 87 string strStyle = "<style>td{mso-number-format:\"\\@\";}</style>"; ///设置输出格式 88 89 ///解决导出到Excel2003乱码问题 90 ///HttpUtility.UrlEncode("学生信息表.xls", System.Text.Encoding.UTF8).ToString()) 91 Response.AddHeader("content-disposition", "attachment; filename=" + 92 HttpUtility.UrlEncode("学生信息表.xls", System.Text.Encoding.UTF8).ToString()); 93 Response.ContentType = "application/excel"; ///设置导出文件的格式 94 StringWriter sw = new StringWriter(); 95 HtmlTextWriter htw = new HtmlTextWriter(sw); 96 sw.WriteLine(strStyle); ///读取格式 97 98 ///GridView1.Columns[11].Visible = false; ///某一列Gridview数据不导出 99 100 GridView1.RenderControl(htw); 101 Response.Write(sw.ToString()); ///把HTML写回浏览器 102 Response.End(); 103 GridView1.AllowPaging = true;///恢复分业 104 BindDB();///绑定Griedview数据 105 } 106 /// <summary> 107 /// 此方法一定要重载,否则报错! 108 /// </summary> 109 /// <param name="control"></param> 110 public override void VerifyRenderingInServerForm(Control control) 111 { 112 } 113 }
主要解决了Gridview导出到Excel