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

ASP.NET
.Net技术开发中两个“属性”引起的歧异
技术文档:解读.Net虚拟框架的实现原理
.Net课堂:总结必须学习的10项.NET技术
实现MSMQ消息加密的安全实践
C#中对DatagridView的部分常用操作
.Net基础:了解ASP.NET中的IFRAME框架挂马
ASP.NET中显示Linq To SQL输出的SQL语句
链表的顺序表示和实现(C++模板类实现)
如何在ASP.NET项目里面正确使用Linq to Sql
ASP.NET两个截取字符串的实用方法技巧
一个简单程序的反编译
ASP.NET MVC中你必须知道的13个扩展点
Entity Framework的默认值BUG解决方法
C#中通过Assembly类访问程序集信息
Java与.NET间进行Web Service交互的选择
C#中用鼠标移动页面功能的实现
程序员的信仰
ASP.NET多附件上传和附件编辑的实现
菜鸟课堂:在Visual C# .NET中跟踪和调试
IronPython和C#执行速度对比

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


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