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

王朝asp·作者佚名  2006-11-24
窄屏简体版  字體: |||超大  

只需将ContentType 设置为 "application/vnd.ms-excel",表示以Excel方式输出.

代码如下:

DataToExcel.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataToExcel.aspx.cs" Inherits="DataToExcel" %>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>DataToExcel</title>

</head>

<body>

<form id="form1" runat="server">

<asp:GridView ID="GridView1" runat="server">

</asp:GridView>

</form>

</body>

</html>DataToExcel.aspx.cs

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;

using System.Data.SqlClient;

public partial class DataToExcel : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!this.IsPostBack)

{

this.Response.ContentType = "application/vnd.ms-excel";

string ConnStr = "server=localhost;uid=sa;pwd=;database=northwind";

SqlConnection Conn = new SqlConnection(ConnStr);

Conn.Open();

string sqlcmd = "select lastname,firstname,title, address, city from employees";

SqlCommand cmd = new SqlCommand(sqlcmd, Conn);

SqlDataAdapter adapter = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

adapter.Fill(ds);

this.GridView1.DataSource = ds.Tables[0].DefaultView;

this.GridView1.DataBind();

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航