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

ASP.NET
DataList绑定到Row[]行集合的问题的方法
充分利用ASP.NET的三种缓存提高站点性能的注意方法
asp.net下文件上传和文件删除的代码
asp.net下日期加减的方法
asp.net动态载入用户控件的方法
asp.net下定制日期输出格式的代码
C#正则用法两例
asp.net图片上传生成缩略图的注意事项
ASP.NET中高质量缩略图的生成代码
DataList 中动态绑定服务器子控件的代码
asp.net下URL网址重写成.html格式、RSS、OPML的知识总结
使用UserControl做网站导航条的思路 分析
ASP.NET中使用AspnetAccessProvider
asp.net下实现URL重写技术的代码
为大家经常为md5加密过的常用admin,admin888,0000密码
利用MS AJAX注册Javascript命名空间并创建类
asp.net(c#)中取得文件物理路径
垃圾代码二三行 ASPX小马
.NET 2.0获取配置文件AppSettings和ConnectionStrings节数据的方法
.NET c# 单体模式(Singleton)

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 98 ::
收藏到网摘: 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();
}
}
}