首页 > 编程 > .NET > 正文

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

2024-07-10 13:10: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();
        }
    }
}

  • 本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。
  • 发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表