zl程序教程

您现在的位置是:首页 >  工具

当前栏目

ASP.NET技巧:数据岛出到Excel最为简易的方法

NetExcelASP方法数据 技巧 简易 最为
2023-06-13 09:13:42 时间

只需将ContentType设置为"application/vnd.ms-excel",表示以Excel方式输出.
代码如下:
DataToExcel.aspx:
<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="DataToExcel.aspx.cs"Inherits="DataToExcel"%>

<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
   <title>DataToExcel</title>
</head>
<body>
   <formid="form1"runat="server">
           <asp:GridViewID="GridView1"runat="server">
           </asp:GridView>
   </form>
</body>
</html>DataToExcel.aspx.cs
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Collections;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
usingSystem.Data.SqlClient;

publicpartialclassDataToExcel:System.Web.UI.Page
{
   protectedvoidPage_Load(objectsender,EventArgse)
   {
       if(!this.IsPostBack)
       {
           this.Response.ContentType="application/vnd.ms-excel";
           stringConnStr="server=localhost;uid=sa;pwd=;database=northwind";
           SqlConnectionConn=newSqlConnection(ConnStr);
           Conn.Open();
           stringsqlcmd="selectlastname,firstname,title,address,cityfromemployees";
           SqlCommandcmd=newSqlCommand(sqlcmd,Conn);
           SqlDataAdapteradapter=newSqlDataAdapter(cmd);
           DataSetds=newDataSet();
           adapter.Fill(ds);
           this.GridView1.DataSource=ds.Tables[0].DefaultView;
           this.GridView1.DataBind();
       }
   }
}