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

ASP.NET
析构函数的作用 什么是析构函数
asp.net下Request.QueryString取不到值的解决方法
设置DropDownList的当前选项
生成多字段排序分页的SQL的通用类
注册表中存储数据库链接字符串的方法
asp.net下百度的编码和解码
asp.net 操作excel的实现代码
用ASP.NET做的个性化的邮件发送系统
DotNet2.0 生成网站的测试
ASP.net 验证码实现代码(C#)
C#中string与byte[]的转换帮助类-.NET教程,C#语言
把jQuery的each(callback)方法移植到c#中
asp.net对URL含有中文参数的转换
C#语言初级入门介绍
C#编码好习惯小结
C#声明方法实例说明
C#使用正则表达式实例
C#列出局域网中可用SQL Server服务器(续)
将DataRow转成指定类型的类,并返回这个类的对象(带值)
asp.net OleDbCommand 的用法

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


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