当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > ASP.NET技巧:数据岛出到Excel最为简易的方法

ASP.NET
如何用Response.Redirect方法传递汉字
在ASP.NET中调用存储过程方法新解
决定何时使用 DataGrid、DataList 或 Repeater(ASP.NET 技术文章)
AlternatingItemTemplate类似于 ItemTemplate 元素
c#中过滤html的正则表达式
ASP.NET:ADO.NET的DataAdapter对象
repeater分页 内容显示
内容添加asp.net
VS2003 SP1发布
DataReader深入解析:持续更新
C#.Net 学习笔记(一)
从ASP过渡到ASP.net遗留的二十大积习
如何改变asp.net项目名称
asp,asp.net学习教程下载
基于.net开发的遵循web标准的个人站点程序包下载
FileUpload1 上传文件类型验证正则表达式
ASP.NET与数据库相关技巧
读取TXT文件内容的方法
简单的启动窗体
c#中实现文件拖放打开的方法

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 58 ::
收藏到网摘: n/a

只需将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();
}
}
}